Agile Zone is brought to you in partnership with:

I am a programmer and architect (the kind that writes code) with a focus on testing and open source; I maintain the PHPUnit_Selenium project. I believe programming is one of the hardest and most beautiful jobs in the world. Giorgio is a DZone MVB and is not an employee of DZone and has posted 636 posts at DZone. You can read more from them at their website. View Full User Profile

Object Calisthenics

08.18.2011
| 7869 views |
  • submit to reddit

Calisthenics is a Greek-derived term for exercises, in the gym sense. I have object calisthenics, exercises for object-oriented programming, around for a long time and saw them as fascinating, but never got the time to try.

A disclaimer: the rules used during object calisthenics are meant to be used in katas and other exercises where there is a controlled environments, not in production code.

After all, even if you train on a treadmill, it does not mean that the maraton will have immediate measurements of your speed available, start/stop buttons and a costant inclination. And that you will run the same amount of kilometers at the same pace, or follow an identical diet. Or that you will put on additional weights (which is the best comparison.) Training conditions are different from race conditions.

The challenge

Object calisthenics consist in solving a programming problem and follow these constraints at the same time.

  1. Use only one level of indentation per method: the ides is avoiding nesting cycles and (worse) ifs
  2. Don’t use the else keyword: prevents conditional branches to favor polimorphism.
  3. Wrap all primitives and strings: exercise your naming and modelling muscles.
  4. Use only one dot per line: read as stricly respect the law of Demeter.
  5. Don’t abbreviate: for today, write firstElementSatisfyingCriteria, not elem.
  6. Keep all entities small: this is the only qualitative criteria. You can set a rough limit on lines of code, but it depends on the programming language.
  7. Don’t use any classes with more than two instance variables: with only two private fields you can reach the maximum theoretical cohesion of a class.
  8. Use first-class collections: no arrays or lists around which are not wrapped into an object containing them as the only private field.
  9. Don’t use any getters/setters/properties: favor encapsulation and procedures that manipulates the data near them.

My hands-on experience

I set out to implement the prime factors kata, where an integer number is decomposed into the list of its prime factors. It is a very simple problem, which can be solved with a brute force algorithm; but since it is simple, it provides a workbench for trying out object calisthenics in a limited amount of time.

Let's see how the 9 rules influenced my execution of the kata. My language of choice is PHP, as only one factor should be changed in each new kata execution.

1. Use only one level of indentation per method

This driving force lead me to continuously extract methods: there is no way you can avoid multiple level of indentation without it. The extraction also forces you to consider which part of the current method scope is used inside of cycles and ifs, and pass it explicitly with parameters. In this diff, $divisor is the only parameter, and $divided gets encapsulated by the new method:

        for ($divisor = self::TWO(); $divisor->lessOrEqualTo($this); $divisor = $divisor->increment()) {
-            if ($this->divisibleBy($divisor)) {
-                $divided = $this->divideBy($divisor);
-                $factors = $divided->primeFactors();
-                $factors->add($divisor);
-                return $factors;
+            $factors = $this->decomposeWith($divisor);
+            if ($factors) {
+                break;

 

2. Don’t use the else keyword

No need for it, really. If you encapsulate the if in a method (at least), you can use return values in a functionally equivalent way:

  public function decomposeWith(IntegerNumber $divisor)
    {
        if ($this->divisibleBy($divisor)) {
            $factors = new PrimeFactors();
            $divided = $this->divideBy($divisor);
            $factors = $divided->primeFactors();
            $factors->add($divisor);
            return $factors;
        }
        return false;
    }

 

3. Wrap all primitives and strings

I immediately started by creating IntegerNumber. So what would have seem a global library function in a procedural approach - decomposing a number into a list of factors - became immediately a method on an instance of IntegerNumber.

Since there are some magic constants like 1 and 2 in this algorithm, I extracted them as well as I need them as IntegerNumber objects and not the scalars. nice side-effect.

<?php
class IntegerNumber
{
    private $number;
    
    public function __construct($number)
    {
        $this->number = $number;
    }

    public function primeFactors()
    {

4. Use only one dot per line

In the case of PHP, my language of choice, only one arrow after $this->, since the former arrow cannot be omitted. Respecting the Law of Demeter was not an issue in this small graph - but it forced me to continuously avoid foreign methods, substituting them with methods on the right class IntegerNumber or PrimeFactors.

5. Don’t abbreviate

I don't abbreviate really much, and in this case I tried to be even more expressive. So I extracted lots of methods in the IntegerNumber class to give a name to the various expressions, even if the call was as long as the expression itself due to the descriptive name.

    public function divisibleBy(IntegerNumber $factor)
    {
        return $this->number % $factor->number == 0;
    }

6. Keep all entities small

I found out that with all the other rules, it was not an issue. Factoring out cycles, collections, and methods continuously leaves a class with not many work to do (and that's a good thing: SRP). Especially methods are forced to be smaller than normal, due to 1.

7. Don’t use any classes with more than two instance variables

The problem was too small to test effectively this principle. I think the best way to trying it out is in some DDD-like exercise, where you decompose entities and value objects all the way down. In this problem, where the state is kept mostly by the stack of calls and numerical objects, there is no application of this constraint.

8. Use first-class collections

I had to introduce immediately the PrimeFactors class, which wrapped the result of the algorithm. This transformed the old array populated by a cycle into an object where methods can be added: I added both a factory method and an add() one which would have otherwise gone to the client class.

<?php
class PrimeFactors
{
    private $factors = array();

    public function fromScalars(array $scalars)
    {
        rsort($scalars);
        $factors = new self();
        foreach ($scalars as $scalar) {
            $factors->add(new IntegerNumber($scalar));
        }
        return $factors;
    }

    public function add(IntegerNumber $factor)
    {
        array_unshift($this->factors, $factor);
    }
}

 

9. Don’t use any getters/setters/properties

My classes don't have any getter to expose their fields: even comparison in the tests is made by building an equal object as the expectation. This goes hand in hand with 4: the absence of getters force you to add logic in the class where the private field resides, instead of in the file that you have already "opened" in your editor.

Lots of small operations (which you can easily perform externally with a line containing a getter call) get a name and are published in the interface:

    public function increment()
    {
        return new self($this->number + 1);
    }

Conclusions

These automatic rules are the simplest ones to move us towards object-oriented good habits, or at least to force us to think when we are about to break them. However, design cannot be enforced just by a few rules: there are always workarounds that infringe their spirit, like naming all the classes with the names of the 7 dwarfs.

Test-Driven Development helped me get to a design that respected the rules incrementally: first I made the code work, then I made it clean. Of course, all the cleaning procedure took place in the space of making a single test passing.

All in all, object calisthenics are a good exercise on design, which force you to think instead of cranking out code. Even 5 lines can get really complex to understand, but in this case readability is ensured; ease of understanding depends on who writes the code: I could have done a better job, but that's why I exercise in the first place. And the final code is really long: but the point was exercising, not reach perfect production code.

Published at DZone with permission of Giorgio Sironi, author and DZone MVB.

(Note: Opinions expressed in this article and its replies are the opinions of their respective authors and not those of DZone, Inc.)

Comments

Ivan Iordanov replied on Fri, 2011/08/19 - 3:13am

With code in second example you break the law of Demeter.

$divided = $this->divideBy($divisor);
$factors = $divided->primeFactors();
$factors->add($divisor);

The idea of using only one dot (arrow in this case) is NOT to make many variables that avoid multiple arrows. There is no difference betwen $this->divideBy($divisor)->primerFactors() and the code above. Main goal is to avoid errors in case divideBy throw and exception and $divided object is null. divideBy should return $factors as long as divideBy creates $divided object and the method knows if object is created or there is an error.

Other solution is to use adapter in case you need divideBy to returns divided object (but in this example you don't need it)

 Ivan

Giorgio Sironi replied on Sun, 2011/08/21 - 5:59am in response to: Ivan Iordanov

Thank you for noticing, it's the sign of missing methods in IntegerNumber where I could push this logic. Maybe I should try the kata with the rules applied one at the time.

Patrick Allaert replied on Thu, 2012/03/22 - 2:21pm

Just a side note since this post is also somehow about best practices, example of point 2 would have been better written: 

public function decomposeWith(IntegerNumber $divisor)
{
    if (!$this->divisibleBy($divisor)) {
        return false;
    }
    $factors = new PrimeFactors();
    $divided = $this->divideBy($divisor);
    $factors = $divided->primeFactors();
    $factors->add($divisor);
    return $factors;
}

 

Google for "return asap" or "guarde clause" to know more about it.

Regards,

Patrick 

Comment viewing options

Select your preferred way to display the comments and click "Save settings" to activate your changes.