DEV Community

Cover image for Code Smell 190 - Unnecessary Properties
Maxi Contieri
Maxi Contieri

Posted on • Originally published at maximilianocontieri.com

Code Smell 190 - Unnecessary Properties

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

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

Enter fullscreen mode Exit fullscreen mode

Right


class PersonInQueue

  def moveForwardOnePosition
    # implement protocol
  end
end

Enter fullscreen mode Exit fullscreen mode

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.

Oldest comments (2)

Collapse
 
jankapunkt profile image
Jan Küster

Hey Maxi, have you considered writing a (maybe open licensed) book as a definitive summary of this series?

Collapse
 
mcsee profile image
Maxi Contieri

yes. indeed :)