I am working on a Java project after a period using C++ and C#, and I have a doubt about best practices for field initialization in constructors. Basically, suppose I have a simple Point class. In C++ my field initialization in the constructor would look 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, with 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 would suggest to define getters / setters for fields which must be accessed from the outside. But it is advisable to use them from inside the class as well? The doubt comes from the fact that Eclipse seems comfortable with converting each this.field = field
in the class code to setField(field)
for fields which have getters / setters, even if I reading / writing happens from inside the class code (therefore I wouldn't need to use the class interface).
This basically adds up a function call for each access. Now, apart from the case in which setting a field involves some other operation (i.e. validations, processing, etc.) has this any sense? Common sense would suggest that using getters / setters is similar to using C# properties, but here I am specifically questioning about C#'s automatic properties which only involve basic access, without any processing. So the question is: is there any good in calling getters / setters with no additional processing from inside the class code?
Thank you
Tunnuz