Recently I was reviewing a piece of code that was performing some computation on file sizes. The author of that code followed good programming practices and created a separate type for representing file sizes:
Yet when it came to computing a total size of set of files I saw code like this:
What is wrong with this code?
It forces readers to concentrate on irrelevant details like how
to sum a list of
FileSizes. As a programmer, reading a lot
of code I would prefer to see something like:
Which is shorter, easier to read and allows me to concentrate on the actual business problem that I try to solve.
As an another example, imagine what would happen if people started writing:
I hope that you agree with me that it would not be nice…
The general rule that is violated by both these examples
is called Single level of abstraction principle, you can read
more about it
In short it states that, all statements of a method should belong
to the same level of abstraction.
In other words we should not mix low and high level operations
in a single method. In our example
Aggregate and details how
to use it are low level, computing a total size of set of files is
on the other hand a high level one.
Fortunately for us, we may quickly add appropriate
to our program:
After this change we achieved code that is easy to read and also hides irrelevant details. Yay!