Wednesday, March 12, 2008

Java one-beaners

The get and set Java conventions sure seem out of date. They are the coding equivalent of pegging your Jeans. They repeat rather a rather boring statement, and feel like a Dick and Jane book. "See class. Class has Thing. Set Thing. Get Thing. Good Thing!"

To put this drudgery in its place, I don't give the dumb get and set methods the same posh multi-line status I give other methods. Instead, I relegate them to one-liners, which I henceforth dub "the one-beaner". When the one-beaner needs explaining, I stick the first explaination on the get method.
private Thing thing;

/** You really want to play with this class' thing. */
public Thing getThing() { return thing; }
public void setThing(Thing thing) { this.thing = thing; }
If my one-beaner needs extra logic, then it gets the full treatment. Extra whitespace like newlines to breathe. A comment describing perhaps why. Perhaps a shiatsu.
private Thing thing;

/** This thing ain't null. */
public Thing getThing() { return thing; }

/** Slap a IllegalArgumentException at the fool who tries to nullify this thing. */
public void setThing(Thing thing)
{
if (thing == null) throw new IllegalArgumentException("thing != null, fool!");
this.thing = thing;
}
Now, when I read my code, I can tell the one-beaners from the code that actually does something.

No comments: