This question can be stupid, but I just want to know, is there any difference?
class A{
// common code
private int field;
public void setField(int field){
this.field = field;
}
//way 1
public A(int field){
this.field = field;
}
//way 2
public A(int field){
setField(field);
}
}
I suspect there is no "better" way, just want suits your purpose at the time.
I prefer Way #1 much of the time. This is because I try to make code as Encapsulated as possible. It also can, in ways, be considered a Functional way of programming Java, since you are reducing side effects. Sometimes eliminating them all together.
class A{
// common code
private int field;
public void setField(int field){
this.field = field;
}
//way 1
public A(int field){
this.field = field;
}
}
Can be rewritten as...
class A{
// common code
private final int field;
//way 1
public A(int field){
this.field = field;
}
Yes, it will not work if you need to change the value of field after instantiation. Also may be field another object or collection.
But in the effort of making the class as immutable as possible, the fields that can be marked as private final are done so.
And of course you can't do that with a setter method.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With