Swift: the correct way to initialize a model class with many properties

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 {
        // there is 20 properties like that
        let id : String
        let username : String
        let email : String
        ...
        var lastLoginDate : Date
        var lastPlayDate : Date
    
        // then HUUUUGE init
        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
    
        // then not so huge init
        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 {
        // there is 20 properties like that
        let id : String
        let username : String
        let email : String
        ...
        var lastLoginDate : Date?
        var lastPlayDate : Date?
    
        // then not so huge init
        init(id: String, 
             username: String,
             email: String) {
        }
    }
    
    // In other code 
    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?

+4
source share

Source: https://habr.com/ru/post/1669571/


All Articles