Jürgen Paul
Jürgen Paul

Reputation: 15027

advantages on wrapping primitive types?

I was reading about Object Calisthenics and one of the rules was wrapping primitive types and strings:

class UIComponent {

    public function repaint($animate = true)
    {
     // 
    }

}

$component->animate(false);

becomes:

class UIComponent {

    public function repaint(Animate $animate)
    {
     //
    }
}

class Animate {

    private $animate;

    public function __construct($animate = true) 
    {
        $this->animate = $animate;
    }
}

$component->animate(new Animate(false));

What advantages do I gain with this technique? In my opinion, I think it just complicated things and added more lines of code.

Upvotes: 1

Views: 624

Answers (2)

John Hall
John Hall

Reputation: 1346

Imagine a new developer (or yourself maybe a year after you last touched the project) reading the code in the first example:

$component->repaint(false);

Without jumping to the definition of repaint() or otherwise reading your documentation for the method, you have absolutely no way of knowing what that false means in terms of how the method behaves. I mean, it literally reads "repaint false", so... repaint but... don't actually repaint? The intent is not clear, and that is a bad thing.

This extremely simple example serves to demonstrate how code readability can be greatly improved by wrapping primitives. The benefits are even greater when you want to start adding just a little bit of behavior like baking in simple validation and comparing itself against another instance.

You should have no concern at all in regards to the performance impact of new'ing up such a tiny little object. As for "more lines of code" why is that bad? SRP almost always results in "more code" but it is clean, readable and maintainable code.

Upvotes: 1

KingCrunch
KingCrunch

Reputation: 132011

In this case, it is true, that it is a little bit oversized, but there are other examples, where it can make sense

class Identifier {
  protected $id;
  public function __construct ($id) { 
    if (!preg_match('~^{a-z0-9]$~i', $id)) throw new Exception("Invalid id '$id'");
    $this->id = $id;
  }
  public function getId () { return $this->getId(); }
}

So this one is immutable and it ensures a specific format. When you type-hint against this class within another class, you don't need to test, whether or not the identifier is valid

class MyClass {
  protected $id;
  public function __construct (Identifier $id) { $this->id = $id; }
}

This is just a simple example and in fact it is not that common in php.

[..] and added more lines of code.

I don't think "more lines of code" is bad by itself. If it needs more lines (or even classes), to write readable and clean code, it is much much better, than compact, but unreadable stuff.

Upvotes: 4

Related Questions