Getters and Setters

I’m running through Head First Java as a refresher, and they just introduced getters and setters. Oh, how I hate them.

The reason for getters and setters makes perfects sense: Sometimes you need to enforce value constraints, map internal values, log activities, etc. when exposing an object’s state. They can be valuable–even necessary sometimes.

It’s the needless repetition when you don’t need them that irks me. My inner minimalist screams in agony when I need to write a bunch of getters and setters with single-line bodies like instanceVariable = aValue; or return instanceVariable;. Even if the IDE manages some of the work around getters and setters, having valueless cruft cluttering my code drives me crazy: Less is always more when trying to understand or maintain code. I’m just plain happier using the simpler notation of instance.variable; every modern-day compiler or interpreter is smart enough to figure out if I’m getting or setting for itself.

It would make much more sense to declare handlers and associate them with instance variables. If you really don’t care about what comes in or goes out, no problem! If several instance variables need the same constraint checking, write the method once and associate it as many times as you like. What about something like this?

String instanceVariable = "default"
    onSet mySetHandler()
    onGet myGetHandler();

Anybody using languages that handle getters and setters like this? I’d be so envious.

Leave a Reply