Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Which way of setting fields value is better and why?

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);
    }
}
like image 982
sashaaero Avatar asked Jun 13 '15 00:06

sashaaero


Video Answer


1 Answers

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.

like image 186
kervin Avatar answered Oct 27 '22 00:10

kervin