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);
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);
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.
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;
}
In general a setter call is safer. The setter may have additional logic:
class Foo(){
String name;
public Foo(String name){
this.name = name;
}
}
while setting the name you can call Foo(name)
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){
}