lundi 13 février 2017

Swift: The proper way to initialize model class with a lot of properties

How do you initialize your classes/structs with a lot of properties?

This question could probably be asked without Swift context but Swift brings a flavour to it, so I add Swift tag in headline and tags.

Let's say you have a User class with 20 properties. Most of them should not be nil or empty. Let's assume these properties are not interdependent. Let's assume that 33% of it should be constant (let) by the logic of the class. Let's assume that at least 65% of them do not have meaningful default values. How would you design this class and initialize an instance of it?

So far I have few thoughts but none of it seems to be completely satisfactory to me:

  • put all of the properties linearly in the class and make 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 sub types and deal with smaller inits 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 requirements a bit: either declare some of the properties optional and set values after init or declare dummy default values and set normal values after init, which conceptually seems to be 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 nice paradigm/pattern how to deal with such situations?

Aucun commentaire:

Enregistrer un commentaire