We’ve all seem them before. They’re everywhere! In fact, it’s probably one the most popular anti-pattern in software development. I’m talking about the setter methods.

class Person {
    private String name;

    public void setName(String name) {
        this.name = name;
    }
}

Here we have a class Person with a setter method for the property name. It looks pretty innocent, right? But what’s really the difference to the following class?

class Person {
    public String name;
}

Uugh, that’s nasty!

If you’ve been working with an object oriented language before, you probably know that it’s a bad idea to expose a property to the public like that. But what’s really the difference to have a setter method?

None.

When you have a class with a setter method, or a public property, you expose its values to the public and allow anyone to mutate them. By doing so, you introduce a shared mutable state to your application. This is bad for several reasons. One of them is that it becomes hard to understand where the values origins from since they can be written in one place and read from another (and let’s not even talk about multithreading). When you have an application full of objects like this, the entire application becomes hard to reason about and bugs will follow.

You might argue that having a setter method is better than a public property. What if we need to apply some kind of logic, like validating the name, before setting the value? Then we can use the setter method to validate it before we set it. First off, is it then still a setter method? Either way, I bet that if you have a look in the code of your current project, it’s very likely that you won’t find much logic in your so-called setter methods. And even if you find a few cases where more logic is needed, there are better ways to approach this!

But don’t get me wrong. I don’t suggest that you should expose your properties publicly instead of using setters. Instead I suggest that you shouldn’t create a mutable object in the first place. Always make the properties immutable! If you need to change the value of a property, let’s create a new object with a different set of values. With this very simple idea you solve all the hard problems caused by a shared mutable state. You should have a very good reason to create a mutable object, and performance is likely not one of them.

My suggestion: Make all the properties final/readonly and set the values in the constructors. That’s it!