Tuesday, August 01, 2006

Property methods: just shoot me now

How much time I spend, writing crap like this:

class Something
private int id;
private String name;

public int getId() { return id; }
public void setId(int id) { this.id = id; }

public String getName() { return name; }
public setName(String name) { this.name = name; }

Any decent IDE will generate the property methods for you, but why is this necessary? Way back in ancient history, Visual Basic knew how to do the right thing: If you defined a setter for some property, then VB would call it when the application set the property. Set it how? With the equals operator, of course. (The equals operator was how software developers assigned values to variables prior to the release of the JavaBeans specification.) And if you defined a getter, then VB would call the getter when the app used the property in some non-lvalue context. If you didn't provide a getter or setter, then no problem, VB just treated the property as a regular old field.

In an anemic domain model, whole classes may exist with nothing but private fields and a public getter and setter for each. What's the point? Why not just make the fields public and be done with it?

Someone's going to say, well, we don't know what's going to happen in the future, and someday we might want to add actual business logic to one of those property methods. That seems like a great example of doing a lot of work now in order to avoid some potential work that may need to be done in the future, which is exactly what we shouldn't be doing. And anyway, if you really want a struct then you should just say so:

* This class is a structure used to pass A from X to Y.
* All fields are public. Do not add logic.
class Something
public int id;
public String name;

I think that my biggest gripe about the proliferation of property methods is that Java doesn't do anything to make it easier for us. Java forces us to decide, up front, whether we want to expose the field or "hide" it behind trivial methods, and then makes us actually write the trivial methods if we want them. VB got it right. Why can't Java?


Post a Comment

<< Home