2
class Foo(){

String name;

public Foo(String name){
   //code to be inserted
}

public void setName(String name){
   this.name = name;
}

}

What would be better to insert in missing line AND why:

1.) this.name = name;

2.) setName(name);

LaRRy
  • 626
  • 5
  • 20

5 Answers5

6

It's up to you.

For example, if you want to perform some validation on the attribute passed to the contructor before storing it in the name variable, call the setter.

But if you want to avoid this kind of validation, or if your setter might throw an exception, assign the variable directly.

The most important here is having created a consistent instance at the end of the constructor method.

xlecoustillier
  • 16,183
  • 14
  • 60
  • 85
  • and if he wants to ignore those extra logic at initialization, call `this.name="xx";` depends on his logic. – Kent Mar 11 '13 at 11:09
  • @X.L.Any: Damn you. I was adding example for the same, you wrote it in one line. Anyways here is my +1. :) – Ajinkya Mar 11 '13 at 11:09
2
setName(name); 

Just in case if you have added some check in setter otherwise you can avoid setter.

For example

public void setWeight(int weight){
  if(weight<=0)
    this.weight = 50;  // set some default/average weight
  else
    this.weight = weight;
}
Ajinkya
  • 22,324
  • 33
  • 110
  • 161
1

In general a setter call is safer. The setter may have additional logic:

  1. Data validation
  2. State update: For example, setting a capacity of a collection sometimes means copying the data into a larger container.
  3. State update in order to maintain class invariants: setting one field may require a change in another to make them consistent.
Eyal Schneider
  • 22,166
  • 5
  • 47
  • 78
0
class Foo(){

   String name;

   public Foo(String name){
      this.name = name;    
   }

}

while setting the name you can call Foo(name)

PSR
  • 39,804
  • 41
  • 111
  • 151
0

In my opinion the best way is to Pass the values in the setter methods and the values which are more important in creating objects for that class then pass them in the Constructor.

If you try to pass all the values in the constructor then as your class grow it will become bigger and ugly having too many parameters to create the object.

So for example lets say your class Foo is dependant on a property int id and assuming you need to always execute some logic in the constructor based on this id. So you will create a constructor passing this id. And later use the setter methods to add values to the properties of that object.

  Foo(int id){

  }
user_CC
  • 4,686
  • 3
  • 20
  • 15