Skip to main content

Command Palette

Search for a command to run...

Code Smell 190 - Unnecessary Properties

Stop thinking of data as attributes. They are only needed to back your behavior

Updated
1 min read
Code Smell 190 - Unnecessary Properties

TL;DR: Don't focus on accidental properties. You won't need many of them.

Problems

  • Anemic Models

  • Properties bloating

  • YAGNI violation

Solutions

  • Create attributes only to support your methods (behavior).

Context

Whenever they want to model a person or an employee, junior programmers or students add an attribute 'id' or 'name' without thinking if they are really going to need them.

We need to add attributes 'on-demand' when there's enough evidence. Objects are not 'data holders'.

Sample Code

Wrong

class PersonInQueue
  attr_accessor :name, :job

  def initialize(name, job)
    @name = name
    @job = job
  end
end

Right

class PersonInQueue

  def moveForwardOnePosition
    # implement protocol
  end
end

Detection

[X] Semi-Automatic

We can detect unused attributes.

But in many cases, we need an excellent designer to validate the actual need.

Tags

  • Anemic

Conclusion

Start designing your objects from the protocol.

Add attributes only when needed.

Relations

Credits

Photo by Melanie Pongratz on Unsplash


Object thinking focuses our attention on the problem space rather than the solution space.

David West


This article is part of the CodeSmell Series.

Code Smells

Part 1 of 50

In this series, we will see several symptoms and situations that make us doubt the quality of our developments. We will present possible solutions. Most are just clues. They are no hard rules.