How do you initialize your classes / structures with more properties?
This question could be asked without a Swift context, but Swift brings it a taste, so I add the Swift tag to the title and tags.
Say you have a class Userwith 20 properties. Most of them should be neither empty nor empty. Suppose that these properties are not interdependent. Suppose that 33% of them should be constant ( let) according to the logic of the class. Assume that at least 65% of them do not have meaningful defaults. How would you create this class and initialize its instance?
I still have few thoughts, but none of this seems to me quite satisfactory:
put all the properties linearly in the class and make a huge init method:
class User {
let id : String
let username : String
let email : String
...
var lastLoginDate : Date
var lastPlayDate : Date
init(id: String,
username: String,
...
lastPlayDate: Date) {
}
}
try to group properties into subtypes and handle smaller values separately
class User {
struct ID {
let id : String
let username : String
let email : String
}
struct Activity {
var lastLoginDate : Date
var lastPlayDate : Date
}
let id : ID
...
var lastActivity : Activity
init(id: ID,
...
lastActivity: Activity) {
}
}
another solution is to break the requirements a bit: either declare some of the optional properties, or set values after initialization, or declare dummy defaults and set normal values after init, which conceptually looks the same
class User {
let id : String
let username : String
let email : String
...
var lastLoginDate : Date?
var lastPlayDate : Date?
init(id: String,
username: String,
email: String) {
}
}
var user = User(id: "1", username: "user", email: "user@example.com"
user.lastLoginDate = Date()
Is there a good paradigm / pattern on how to deal with such situations?
source
share