Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Constructor with all class properties or default constructor with setters?

Tags:

Following are the two approaches:

  • constructor with all the class properties

Pros: I have to put an exact number of types of parameters so if I make an error the compiler warns me (by the way, is there a way to prevent the problem of having erroneously switched two Integer on the parameter list?)

Cons: if I have lots of properties the instantiation line can become really long and it could span over two or more lines

  • setters and the default empty constructor

Pros: I can clearly see what I'm setting, so if I'm doing something wrong I can pinpoint it as soon as I'm typing it (I can't make the previuos error of switching two variables of the same type)

Cons: the instantiation of an object with lots of properties could take several lines (don't know if this is really a con) and if I forget to set a property the compiler doesn't say anything.

What will you do and why? Do you know of any light pattern (consider that it should be used everytime an object wth 7+ properties is instantiated) to suggest? I'm asking this because I tend to dislike large constructors where I can't figure out fast where is the variable I'm looking for, on the other hand I find the "set all properties" vulnerable to missing some of the properties.

Feel free to argument my assumptions in pros and cons as they are only mine thoughts :)

Update - a question I've found which is related to this: Building big, immutable objects without using constructors having long parameter lists

like image 938
Alberto Zaccagni Avatar asked May 06 '09 17:05

Alberto Zaccagni


People also ask

Should I use setters in constructor?

You should not call getters and setters from the constructor. A constructor constructs the specific class in which it is defined. It is its job to initialise the fields because - well - nothing else will. The only way to guarantee initialising the fields is to assign them.

Do you need getters and setters if you have a constructor?

Getters and setters are used after you have initialized your class members using the constructor. Getters are used to acquire class member values from the instance of the class by classes/functions located outside the class. Setters are used to alter the value of the corresponding class member in the same manner.

What is a default constructor does every class have a default constructor?

A default constructor is a constructor that either has no parameters, or if it has parameters, all the parameters have default values. If no user-defined constructor exists for a class A and one is needed, the compiler implicitly declares a default parameterless constructor A::A() .

What is the difference between setters and constructors?

The constructors are used to initialize the instance variable of a class or, create objects. The setter/getter methods are used to assign/change and retrieve values of the instance variables of a class.


2 Answers

You've missed the biggest pro of having a constructor with loads of parameters: it lets you create immutable types.

The normal way of creating immutable types without huge constructor nastiness is to have a helper type - a builder which maintains the values you'll want in your final object, then builds the immutable object when you're ready.

like image 96
Jon Skeet Avatar answered Oct 19 '22 23:10

Jon Skeet


You might look at the Builder pattern advocated by Joshua Bloch, and described in Effective Java. There's a presentation with the main points at http://developers.sun.com/learning/javaoneonline/2007/pdf/TS-2689.pdf; no doubt you could dig up a better reference.

Basically, you have another class, probably an inner class, which provides methods named after the properties being set, and which return the original builder so you can chain calls. It makes for quite a readable chunk of code.

For example, let's suppose I have a simple Message with a few properties. The client code constructing this could use a builder to prepare a Message as follows:

Message message = new Message.Builder()     .sender( new User( ... ) )     .recipient( new User( ... ) )     .subject( "Hello, world!" )     .text( messageText )     .build(); 

A fragment of Message.Builder might look similar to the following:

public class Builder {      private User sender = null;     // Other properties      public Builder sender( User sender ) {         this.sender = sender;         return this;     }     // Methods for other properties      public Message build() {         Message message = new Message();         message.setSender( sender );         // Set the other properties         return message;     }  } 
like image 44
Rob Avatar answered Oct 19 '22 23:10

Rob