There are many problems with constructors that take arguments (for example, you cannot build an object in a few steps). Also, if you need a lot of arguments, you will ultimately get confused with the order of the parameters.
The final idea is to use a β free interface β. It works with setters that return this . Often set not specified in the method name. Now you can write:
User user = new User() .firstName( "John" ) .familyName( "Doe" ) .address( address1 ) .address( address2 ) ;
This has several advantages:
- It is very readable.
- You can change the order of the parameters without breaking anything
- It can handle single-valued and multi-valued arguments (
address ).
The main disadvantage is that you no longer know when the instance is "ready" for use.
The solution is to have many unit tests or specifically add the init () or "done ()" method, which performs all the checks and sets the flag "this instance is correctly initialized".
Another solution is a factory, which creates the actual instance in the build() method, which should be the last in the chain:
User user = new UserFactory() .firstName( "John" ) .familyName( "Doe" ) .address( address1 ) .address( address2 ) .build() ;
Modern languages ββlike Groovy turn this into a language:
User user = new User( firstName: 'John', familyName: 'Doe', address: [ address1, address2 ] )
Aaron digulla
source share