Code Smell 01 - Anemic Models

Maxi Contieri - Oct 20 '20 - - Dev Community

Your objects have no behavior.

TL;DR: Don't use objects as data structures

Protocol is empty (with setters/getters).

If we ask a domain expert to describe an entity he/she would hardly tell it is 'a bunch of attributes'.

Problems

  • No Encapsulation.

  • No mapping to real world entities.

  • Duplicate Code

  • Coupling

  • Writer / Reader mismatch.

Solutions

1) Find Responsibilities.

2) Protect your attributes.

3) Hide implementations.

4) Delegate

Examples

  • DTOs

Sample Code

Wrong

<?

class Window {
    public $height;
    public $width;

    function getHeight() {
        return $this->height;
    }

    function setHeight($height) {
        $this->height = $height;
    }

    function getWidth() {
        return $this->width;
    }

    function setWidth($width) {
        $this->width = $width;
    }

}
Enter fullscreen mode Exit fullscreen mode

Right

<?

final Class Window{ 

  function area(){
    //...
  }

  function open(){
    //..
  }

  function isOpen(){
    //..
  }

}
Enter fullscreen mode Exit fullscreen mode

Detection

Sophisticated linters can automate detection.
They should ignore setters and getters and count real behavior methods.

Also Known as

  • Data Class

Tags

  • Anemic
  • OOP as Data
  • Encapsulation
  • Setters/Getters
  • Mutability

Conclusion

Avoid anemic models. Focus always on protocol instead of data.
Behaviour is essential, data is accidental.

Relations

More info


Object-oriented programming increases the value of these metrics by managing this complexity. The most effective tool available for dealing with complexity is abstraction. Many types of abstraction can be used, but encapsulation is the main form of abstraction by which complexity is managed in object-oriented programming.

Rebecca Wirfs-Brock

Credits

Photo by Stacey Vandergriff on Unsplash


This article is part of the CodeSmell Series.

Last update: 2021/05/30

. . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . .
Terabox Video Player