Skip to content

Object Calisthenics

Last Updated on 16/11/2020

Object Calisthenics logo

Object Calisthenics is an exercise proposed by Jeff Bay in the book The Thoughtworks Anthology, that outlines a set of nine rules to be used to write a new object-oriented project, with around 1000 lines of code, to help us design a piece of software that really implements encapsulation well.

Some of the nine rules are very strict and challenging to apply somewhere else besides the exercise project, but a few of them can be easily implemented in any real project, resulting in a great improvement of reusability, cohesion, readability and maintainability.

Let’s take a look into all of them in detail (click on the link) to see how we can apply them with the latest Java updates such as lambdas, and modern frameworks such as ORMs and annotation processors. Then, let’s elaborate on the benefits of using these rules.

The rules

  1. Use only one level of indentation per method.
  2. Don’t use the else keyword.
  3. Wrap all primitives and Strings.
  4. Use only one dot per line.
  5. Don’t abbreviate.
  6. Keep all entities small.
  7. Don’t use any classes with more than two instance variables.
  8. Use first-class collections.
  9. Don’t use any getters/setters/properties.

The exercise

I strongly suggest trying out the Object Calisthenics exercise. Try creating a new project, and writing at least 1000 lines of code that follows these nine rules.

When I did it a few years ago it felt a bit weird in the beginning. Wrapping all those primitives and creating a bunch of classes just to accommodate the attributes that would end in just one table on the database, seemed too much code to not do much.

However, shortly after I started to notice how insightful the experience was: I didn’t have to provide more fields than I needed to handle a simple operation such as updating a password; my service classes were really small since they had to deal with smaller objects; and I never had to look into the declaration of my constructor anymore to check whether the first String parameter was the username or the password, because they were no longer Strings but proper Username and Password objects.

The benefits

Those skills were quickly applied on my real projects: never used an else keyword anymore, now my code is easier to read with early returns, fewer lines and only one level of indentation; when an NPE is thrown, I know exactly where it happened since I am no longer chaining method calls in the same line.

Writing truly object-oriented code is challenging. Techniques such as Object Calisthenics, design patterns and best practices help us with accomplishing better this task.

Hope that happens to be as insightful to you as it were to me.
Happy coding =]

Leave a Reply

Your email address will not be published. Required fields are marked *