Christopher Okhravi

Don’t use getters and setters. They break encapsulation.

That’s what they say.

They say we’re merely masking the ugly truth. That we’re directly accessing naked data.

But I don't get it.

Getters and setters are just methods with different syntax.
They give us a place to intercept the call to run arbitrary code.
Just like methods do.

We might ask for the damage of an attack and get back an int. But under the hood, the class might store it as a double. Or store nothing and compute it on the fly. That’s still encapsulation.

The underlying field might be expressed as a double even though we get an int back. In fact, the class might not even have any underlying field. The value could be computed.

The only reasonable argument against getters and setters that I can think of is that they promote a “Tell don’t ask” mindset. And sure, that’s a useful principle. Most of the time. But not all the time.

In practice, I’ve broken that principle many times and found my code to get clearer as a consequence of doing so.

Philosophy aside, there’s no pragmatic difference between using methods and getters and setters. Both hide the implementation details.

Getters and setters are just a convenient way of expressing nullary and unary methods when it’s intuitive for callers to use the assignment operator instead of method invocation syntax.

That’s all.

Tell me why I’m wrong.

My book, The Object Oriented Way, is about writing changeable software and cutting through dogma to see the connections between patterns, features, and principles.
Link in the comments.

2 months ago (edited) | [YT] | 33