java - Field initialization in class constructors: direct or through "setter"? -


i working on java project after period using c++ , c#, , have doubt best practices field initialization in constructors. basically, suppose have simple point class. in c++ field initialization in constructor like:

class point { public:     // default constructor     point(double x, double y) : x(x), y(y) { }  protected:    // coordinates    double x, y; }; 

in c# ...

class point {     // coordinates, automatic properties     public double x { get; protected set; }     public double y { get; protected set; }      // default constructor     point(double x, double y) {         x = x;         y = y;     }     } 

in java ... best practices suggest define getters / setters fields must accessed outside. advisable use them inside class well? doubt comes fact eclipse seems comfortable converting each this.field = field in class code setfield(field) fields have getters / setters, if reading / writing happens inside class code (therefore wouldn't need use class interface).

this adds function call each access. now, apart case in setting field involves other operation (i.e. validations, processing, etc.) has sense? common sense suggest using getters / setters similar using c# properties, here questioning c#'s automatic properties involve basic access, without processing. question is: there in calling getters / setters no additional processing inside class code?

thank you
tunnuz

getters setters encapsulates things. today there nothing process tomorrow may need process something. better use getters setters.

for default value initilization can use constructor.\ if there processing while setting getting use getters setters.

best practices use

  • constructor / initilizer block initilize member fields value.
  • from inside class access fields directly
  • from outside class use getters/setters

also see


Comments

Popular posts from this blog

python - Scipy curvefit RuntimeError:Optimal parameters not found: Number of calls to function has reached maxfev = 1000 -

c# - How to add a new treeview at the selected node? -

java - netbeans "Please wait - classpath scanning in progress..." -