Monday, January 3, 2011

Java Grievances part 3

The previous Java posts were about the library, this post is about Java classes missing properties. This means that you have to write code like this in Java:
float adjustX = 0.5;
for(int i = 0; i < some_object.getRectangle().getPoints().size(); i++)
some_object.getRectangle().getPoints().get(i).setX(
some_object.getRectangle().getPoints().get(i).getX() +
adjustX
);
Where properties can make the same code much more readable:
float adjustX = 0.5;
for(int i = 0; i < some_object.Rectangle.Points.Size; i++)
some_object.Rectangle.Points[i].X += adjustX;

This can actually be implemented without changing the Java bytecode, simply by adopting a standard syntax, eg.:
public property X {
float getX() { return m_x; }
void setX(float value) { m_x = value; }
}

The compiler is then free to emit code without the property part. This will make this feature just as useless as generics currently are, unless the compiler also assumes that the common getX/setX function pairs can be used as a property. This means that all those old libraries will suddenly appear to have properties when they have not.

Such a syntactic sugar model doesn't break anything, not even reflection, as the methods are there just as they should be.

This is in fact how they are implemented in C#/VB and others, and allows interoperability with languages that have no property features. Unfortunately some people confuse properties with instance variables, which they are not. Properties are NOT a way to get out of proper class encapsulation. Properties are also more expensive than variables as they can validate the input/output, cause events etc. so you would still need both.

No comments: