Code Smell 28 - Setters

Code Smell 28 - Setters

Maxi Contieri

Published on Nov 19, 2020

2 min read

Subscribe to my newsletter and never miss my upcoming articles

Listen to this article

The first exercise junior programmers do. IDEs, tutorials and senior developers keep teaching them this anti-pattern.


  • Mutability

  • Information Hiding

  • Anemic Models

  • Fail Fast

  • Integrity

  • Duplicated Code


  1. Avoid Setters

  2. Set essential attributes on private initialization.

Sample Code


Mutation brings lots of problems

Information Hiding Violated


First step will be to forbid public attributes (if language allows them).

Secondly, we will search for methods setXXXX(), analyzing method structure (should be an assignment to attribute xxxx).

We should not forbid methods setting accidental state since this is valid. You should not name them setters, since they ask the object to change, but they don't set anything.


  • DTOs


Setting attributes is safe for non-essential attributes.

Essential behavior is what distinguishes one object from another.

It is related to behavior and not data. It's not a primary key definition.

Some patterns, like Builder require setting the parts in a controlled, incremental way. Validations are done at the end and the real entity metaphor requires it.

Setting accidental values has many drawbacks and considerations already mentioned.


  • Mutation

  • Information Hiding


Creating incomplete and anemic objects is a very bad practice.

This habit violates mutability, fail fast principle and real world bijections.


More Info

Here is the full discussion on Setters


Photo by Victor Rodriguez on Unsplash

Object-oriented programming languages support encapsulation, thereby improving the ability of software to be reused, refined, tested, maintained, and extended. The full benefit of this support can only be realized if encapsulation is maximized during the design process.

Rebecca Wirfs-Brock

This article is part of the CodeSmell Series.

Share this