Developers spend much more time reading the code rather than writing. For that reason readability and “clean code” practices are in general is very important. There is a lot of different rules exists to help developers structure their code in a way so it needs less effort for understanding and in maintenance. On top, there are also tools created to enforce those rules.
Now to the code. Looking at it from the high-level perspective it is easy to distinguish bigger blocks, like classes (not necessarily to follow the OOP paradigm, by “class” any top-level grouping can be mentioned) and their members. And the order of these members in class is very important.
There is a couple of most popular recommendations to that.
First one, it comes from the code style guidelines published by big tech players like Google or Oracle says that it is important to order class members by the level of exposure. This order fits good the code written in the form of a library:
- public members – class API, is the most important part, must fall into consumer’s eye as soon as possible so it stands at the first position;
- protected members – internal API, still important as it can be overridden thus needs to be at the second position;
- private members – pure internals, can be placed at the very last position.
An alternative recommendation suggested by Robert C. Martin can be formulated much more easily: order of the members must be defined like chapters in the fiction book, they must follow the execution flow “story” and explain the code without a need to jump around the text up and down. This style fits good typical services that define pure business logic, set of operations required to execute some user scenario.
So for the second approach there is not much what can be automatically enforced, whereas for the first one it is an opposite situation. But even if the idea is simple, sometimes it is just impossible to overcome language limitations and entirely follow the code style “public” -> “protected” -> “private”.
Leave a Comment