Towers of Hanoi Algorithm in Java

There are countless implementations of the Towers of Hanoi to be found in internet. The point of this post is to write the program with readibility in mind, as an exercise.

I'll show the implementation first and then explain what makes the code "clean" or readable.


Here are the characteristics of the code above:

There is nice separation of concerns between the class that deals with the user and does the printing to screen and the class that encapsulates the algorithm. Even though the methods are all static, there is no reason to mix both.

There is an effort to make all statements inside a method be at the same level of abstraction, which should be one level below the level of abstraction of the method's name. Also, a method should do one thing and only one thing.

For example the method findSolution in TowersOfHanoiAlgorithm does some parameter checking, check for special cases, some other housekeeping and then calls to the algorithm itself.

Likewise, the method algorithm does one thing only, which is to check whether there is one disk left to move. Then does different things in each case, but it doesn't go in the details below that level: it relies on algorithmSeveralDisks.

Inside the method algorithmSeveralDisks there are three steps, which are the three high level steps of the towers of hanoi algorithm. The names of the methods are descriptive and precise. The methods encapsulate what are, in essence, one-liners, they are tightly coupled with the algorithm and are, certainly, not reusable. Their existence is based on documentation purposes only.

The naming is consistent. Words like source or dest are chosen, and those words are always used whether in variables or in methods to describe the same concept and abstraction. You won't find from, to or emptyPeg.

The names of methods that do similar things have similar names with the same structure. And, of course, the code is properly indented and formatted. (Well this is true in my source code, but not in the code presented above, since github fails to apply a smaller indentation.

Comments