0

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?

Kukeltje
  • 12,223
  • 4
  • 24
  • 47
Peter
  • 131
  • 1
  • 14

3 Answers3

3

setter/getters are more preferable because you can encapsulate some processing in those accessor methods too


Also See

Community
  • 1
  • 1
jmj
  • 237,923
  • 42
  • 401
  • 438
3

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.everything is 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 if bfield doesn't need a backing field at all -- for instance, if setting it should set something on a sub-object), you'll be glad you called setBfield -- cause you won't have a dozen places to change code that sets bfield. Basically, if you need and already have a setBfield method, 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 bfield as well.

cHao
  • 84,970
  • 20
  • 145
  • 172
-2

Use eclipse! Let it do some work for you. Create a class Test like this.

public class Test {
   private String afield;
   private String bfield;
}

and then do these:

  • right click -> select 'Source' -> Generate constructor
  • right click -> select 'Source' -> Generate constructor with fields
  • right click -> select 'Source' -> Generate getters / setters

done :) and do lookup for java bean convention. your code would freak out any java exp dev! :)

Srinivas
  • 432
  • 5
  • 22
  • Thanks everybody. I will go with Getter and Setters but at the same time let me aks - if I am comapring these two variables, I think for the clarity point of view it will make more sense to say {this.aField == this.bField}. Correct me if I am wrong, please. – Peter Mar 23 '12 at 04:55
  • @Peter: It doesn't help clarity much if `afield` and `bfield` are not locals (or arguments); then it's just noise. – cHao Mar 23 '12 at 13:20