📜 ⬆️ ⬇️

Reflections on beautiful code


It’s customary to talk a lot about a beautiful code, to argue, to argue, and yet, it’s still not really clear what the “beautiful” code is and how it should be. The complexity of defining the “beauty of the code” is not surprising, since the concepts of “beauty” are different for everyone, not only in the world of programs, but in general, in the world of people. However, there are certain general criteria for beauty that most people agree with. They are difficult to formulate, but subconsciously, any person understands that this thing is beautiful, and this one is not very good.
Not so long ago, a very interesting survey was published, sharing the views of developers about beautiful code, according to their experience. In my opinion, it turned out a very interesting study. Let's try to speculate about it a little wider.

Now there is a lot of available methodological information, various schools, trends and even formal techniques of writing “beautiful code” are being formed. In this regard, it is difficult not to notice how young programmers are addicted to following a technique, arguing about seemingly unimportant things like “consider this piece of code to be consistent with the Zen of this or that ideology or not. And if you count, how ideologically it is clean?

On the other hand, more mature (and therefore cynical and pragmatic) developers know that a passion for ideology is often childish. And finally, very experienced gurus can reduce all the practices of a beautiful code to the mantra "Write the code, b - be!". It seems to them that this is enough. They simply do not realize that they get the beautiful code by itself, simply because of the great experience and stuffed cones. But still, what is it - a beautiful code?

In response to the survey, I estimated my development experience at 8 years old and answered in the appropriate group. I was very surprised that my answers almost completely coincided with the most popular ones in my “age” group. So, my peers are my like-minded people! Its cool!
')
If I were asked directly to the forehead about what a “beautiful code” is, then probably, I would answer with some common set of phrases, in the style of Captain. For me, the "beauty" of the code is determined, perhaps, by its grace, the absence of unnecessary complexity, the presence of a single idea ... something like that. If we could always write such code ... In real life, Ideally Beautiful Code can only be seen spherical, and in a vacuum.
No matter how pedantic and idealistic we are, we work within deadlines. Even if this is a work on an open and non-commercial project, even if we put all our experience, knowledge and soul into it, all the same, the desire to release, finally, the result of our work is published - this is the deadline that will come sooner or later. And since there is a deadline (a certain frontier, after which the code will have to leave its author), then there are compromises that you have to make in order to complete the work on time. Like it or not, but our work is difficult. Elegant architecture and solutions do not always light up our heads. This way crutches, stubs, hardcodes and other "little tricks" are born.
The difference between “as desired” and “how it happened” is the less, the better a person as a specialist. When the difference is very small, then such a code is usually beautiful.
So, let's go back to the questions that were raised in the above-mentioned voting about the beautiful code:

Beautiful code you need to write ... if possible.


Exactly, “if possible”. We all want to write beautiful programs that are charming in their grace. Show me a man who wants to create shitty things. I do not think that there are people who sincerely want this. The trouble is that it does not always work. Presses deadlines, draws the absence of muse, knowledge. An experienced programmer, fulfilling the "ugly" decision, will think up a way to remove it in the future. He knows exactly what is permissible evil, and what - frank mud.
A less experienced programmer doesn’t want to mess up either, but his criteria for “admissibility of evil” are often much lower. It is permissible to call all variables in one letter, to carry them all into the global scope, not to indent code. It works the same.
If possible, it is better not to write such code. If there is no opportunity (experience), then you still need to write. The road will be mastered by going, the task must be solved.

I think that beautiful code should ...


Here is more interesting. What are the essential criteria for beauty in code?
Look at the code where the indents are made according to the principle “where the cursor stood, there I write”, the variables are named without meaning, the logic is spread over the code, the user interaction is mixed with the database code. You only need a quick glance to firmly say: "The code is terrible." This is the code of an amateur, a very, very beginner programmer. I suppose you all wrote this when every cycle for you was a “brain test”. It passes with experience, but it is obvious that there can be no beauty in such a code.

In my opinion, beautiful code should be understandable, almost like natural language text. “Mnemonically clear,” read one of the answers. I think this is the most important criterion. The requirement for a uniform design style is one of the means of ensuring mnemonic clarity. Having a single style makes it easy to understand. Beautiful code should be kept in the same style. Not important in what, but in one. The simplest convention, for example, to name class member variables, starting with an underscore, increases readability by several times. A small underscore sharply highlights “local” method data and data on which the entire class depends. Another example is the common naming style of getter / setter methods. If they all start with a prefix, but the brain instantly understands what these methods are, why should they. No need to be distracted from the main reading and climb to another place in the code to get additional clarification.

The second very important criterion is code stability. As a rule, it is provided with tests. The stable code is not even beautiful in appearance. He is handsome in his evenness. I feel genuine pleasure when the code, which I consider to be reliable, suddenly works correctly if new data were submitted to it for which it was not designed. I am happy for such a code and even admire it (with myself, with myself, of course, to be cunning). The stable code is beautiful, like a good sportsman or musician. He moget, damn!

And the last, important criterion is the simplicity of expansion. Here and say a lot does not work. A lot of old tales are walking, like the one that they say, if the ship designer was asked to make a boat, and then hang the engine, accommodate 1000 passengers, not counting the crew, 300 boats and anti-aircraft gun, then he would have shouted "I am not a programmer!". Only changes are permanent in our work. The ability to foresee them is talent. When you contemplate the code where the extension points are gracefully included in the main task, then you say, “beautiful!”

In my opinion, these are the only mandatory criteria for "beauty" in the code. Neither comments, nor volume, nor even performance make the code “beautiful.” The beautiful and slow code is still beautiful (though not very). When you look at the code, it's beautiful, but when you launch it, you spit, yes. Perhaps it is as with a beautiful, but stupid and empty man.

I believe that beautiful code can ...


Oh, here is generally fun. It’s good to talk about ideality, to teach others well ... But we are all sinners. Who has never prescribed a hard value, instead of making an option - let him throw a stone at me first. Let's talk about the sins of the "beautiful code".

Of course, the beautiful code may not contain comments at all. The presence of comments is even a whole separate holivar. Let's try to deal with the comments. The main rebuke to comments is that they lie. The second reproach - they describe obvious things, and very rarely - really requiring clarification.

Some of the smart people said: “Comments should not say what the code does. Comments should say WHY he does it. " Golden words that are hard to argue with. The code itself answers the question "what?" When I see a complex or unclear construction in the code, it is important for me to understand why it is here. What happens if I remove or change it? If there is a comment next to such a construction, then, most likely, it will be in the style of “Assigning variable A to value B”. “Thanks for the help, damn it!”, - you swear and start the analysis.

Why it happens? In my opinion, the answer is obvious. The programmer works with pure thought. At the time of immersion in the task requires tremendous concentration. In the head of the programmer who is writing the code, fragile locks are constructed of mental constructions. It is worth a little distraction and everything collapses. Well, who will be distracted by commenting in such conditions? If sometimes the stream of consciousness of the author gives rise to comments of the aforementioned type, it is because he was working at this particular level of detail at the time of writing.

Most likely, this assignment “A = B” is really important, some key point of the algorithm, which the author found it necessary to mark. He did not write "why" it is necessary to do this assignment, because at that moment he considered it obvious. To this comment you just need to add "to the result of the method ...." and the comment will become much clearer. The trouble is that at the time of deep immersion, the author could not get out of the maximum level of detail, without destroying the crystal lock. The comment is extremely understandable, but useless if the reader is not in the state of immersion in the algorithm.

When the code is written, sometimes it is “combed”, and then the comments are overwritten and refined. And here is another ambush - the comment will sooner or later become obsolete, the code will be rewritten, and they will be forgotten about it.

Thus, the requirement to “remove comments, write self-documenting code“ is very fair. But however good the self-documenting code may be, it perfectly describes “What”, but rarely can answer the question “Why”. A beautiful code may not contain comments, but if they exist and explain why a particular fragment was written, they make the code even more beautiful.

The next “sinner”, which seems to me acceptable, is the size of the code. Beautiful code may be overly large. Often size is an attempt to achieve extensibility when the requirements for extensible functions are not defined. If so, then the thoughtful embedding of extension points, the emergence of architecture above a simple task makes the code even more beautiful. The fear of the requirement to “hang up an anti-aircraft gun” also forces us to build over-engineering monsters.

Brief summary

Each of us, without any articles, understands what a beautiful code is. Beauty has no formal criteria, but it feels quite clear. A beautiful code is one that does not cause the desire to immediately select everything and press Delete. The surprising unanimity of all „generations“ who took part in the survey about the beautiful code confirms this.

PS

This is my first article for Habr. I know how severe and harsh you are here, so I beg you, if something seems to be a blatant garbage, do not be lazy, please, apart from the minuses, write a few words - what exactly is wrong, okay?
Thanks for attention.

Source: https://habr.com/ru/post/212053/


All Articles