Mutator Methods Are Fine, but "get" and "set" Don't Communicate Intent

DZone 's Guide to

Mutator Methods Are Fine, but "get" and "set" Don't Communicate Intent

The basic problem: "set" and "get" don't tell you anything about what these methods (in any given class) actually do.

· Java Zone ·
Free Resource
A few days ago I tried to help you with making a decision when you should use a constructor and when a setter.

In one of the paragraph I wrote:

I don’t like setters. Why? Because those methods in some way break encapsulation.

After sharing this post there were developers that were arguing that setters can be useful.

What can I say?

I have to agree that methods that do nothing but set a field’s value may be needed to provide required functionality. I won’t even argue with that. To make my thinking clear, I don’t have a problem with mutator methods, I just don’t like all of those setX/getX methods. Why? I believe that each method is about behavior and its name should tell something about this behavior. Setters tell us nothing about behaviour and make implementation details leaking.

In the example from the previous post there were methods:

public void setSnapshotTaker(SnapshotTaker snapshotTaker) {
 // some code

public void setNotifier(Notifier notifier) {
 // some code
and after refactoring I renamed them into:
public void enable(SnapshotTaker snapshotTaker) {
 // some code

public void enable(Notifier notifier) {
 // some code
Has functionality changed? No, methods still just set the particular object’s field!
But with a different name we know what’s the purpose of those methods. We didn’t create them to set a field, we introduced them to make it possible to enable some optional functionality. The same functionality with a different name gives us more valuable information. Explains the Why, not How.

So, is it ok to have a method that does nothing but set an object field? Of course, sometimes it is needed.

Is it OK to name your method setX/getX? I think no, we can always give it a better name, give it a more meaningful name.

java ,spring ,dependency injection

Published at DZone with permission of Sebastian Malaca , DZone MVB. See the original article here.

Opinions expressed by DZone contributors are their own.

{{ parent.title || parent.header.title}}

{{ parent.tldr }}

{{ parent.urlSource.name }}