Search code examples
oopdesign-patternssignaturemethod-signature

Various params method signature versus one object param method signature


I need to construct objects with many properties. I could create one constructor with one param for each property:

class Friend{

    constructor(name, birthday, phone, address, job, favouriteGame, favouriteBand){
        this.name = name;
        this.birthday = birthday;
        this.phone = phone;
        this.address = address;
        this.job = job;
        this.favouriteGame = favouriteGame;
        this.favouriteBand = favouriteBand;
    }

}

or I could recieve one param with a literal object or an array with all the values:

class Friend{

    constructor(descriptor){

        this.name = descriptor.name;
        this.birthday = descriptor.birthday;
        this.phone = descriptor.phone;
        this.address = descriptor.address;
        this.job = descriptor.job;
        this.favouriteGame = descriptor.favouriteGame;
        this.favouriteBand = descriptor.favouriteBand;
    }

}

In which case should I use each one? Is there a design-pattern about this subject?

I'm interested in OOP. I'm using Javascript but it could be wrote in any other language supporting OOP (PHP, Java, C++, Python, any other possible)


Solution

  • The first one seems more explicit for the clients as each parameter is defined in the constructor declaration.
    But this way is also error prone as you have many parameters and some parameters have the same type. The client can easily mix them as these are passed to.
    So in this specific case, using a literal such as constructor(descriptor){...} seems clearer.

    I am not sure that this type of constructor be a design pattern. It is rather a constructor flavor that depends on the requirement but also on the language used.
    In JavaScript, it is common enough as it is straighter and it avoids writing boiler plate code for setters method or a builder constructor.
    But in other languages as Java, defining a constructor with so many arguments is a also bad smell but using a literal is not a possible alternative either. So using setters or a builder constructor is generally advised.