I am just learning and would like to know about a piece of code that sets the object variable.
What is the correct way to set object variable bfield in the follwoing test class?
public class test {
private String afield;
private String bfield;
public test() {
buildList();
}
public void buildList() {
some code to derive and populate afield.
this.bfield = this.afield; // ( 1)
setBfield(afield); // (2) say getter and setters do exist
bfield = afield; // (3)
}
What is the right way to do? I soption 1 OK or option 2?
Any of the three will work, of course.
I generally don’t like option 1, unless i’m differentiating between an instance member and an argument. For example,
public void buildList(String bfield) { this.bfield = bfield; }.this.everythingis extra noise; if you don’t need it, all it does is give the bugs more code to hide in. 🙂Option 2 is more future-proof; if ever you change things so that something else has to be set along with
bfield(or ifbfielddoesn’t need a backing field at all — for instance, if setting it should set something on a sub-object), you’ll be glad you calledsetBfield— cause you won’t have a dozen places to change code that setsbfield. Basically, if you need and already have asetBfieldmethod, i’d recommend using it in most cases.If you have a field you know will always be contained within the object itself, and is independent of other fields, option 3 is typically faster. Plus, you don’t have to create a setter (read: pollute your interface), if you don’t want outside code to be able to set
bfieldas well.