Wednesday, February 24, 2016

Method’s name change a lot

A few days ago I tried to help you with making a decision when you should use constructor and when 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 it name should tell something about this behavior. Setters tell us nothing about behaviour and make implementation details leaking.

In the example from 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 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 different name gives us more valuable information. Explains the Why, not How.


So, is it ok to have a method that do 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.


No comments:

Post a Comment