What should be a quality code? Robert Martin expressed it incredibly accurately when he said: “The only adequate measure of the quality of the code is the number of cries of“ what the hell! ”Per minute.”
Let me clarify this idea.
Every time I read someone else's code, these are the thoughts that came to my mind:
- What the heck! (with disgust) - when in a certain code fragment there is no need.
- What the heck! (with admiration) - when the programmer did something very successful.
- What the heck! (with irritation) - when I cannot understand the horror that is before my eyes.
So what makes the first code impression? This is how clean and beautiful he is. Such code is a sign of the high professionalism of the person who wrote it.
')
The path to coding mastery goes through two important milestones. This is knowledge and labor. Knowledge gives patterns, principles, practical techniques, heuristic rules that are needed for professional growth. But this knowledge needs to be fixed. Here mechanical and visual memory comes into play, knowledge must firmly settle inside you through constant practice and hard work.
In short, learning to write clean code is hard work. You have to invest a lot of strength in it. You need practice. Moreover, there will be moments on this path when things stop, when nothing happens, but this should not stop you - step by step you will approach perfection, repeat everything again and again until everything turns out to be the way it should be. . There are no workarounds.
Here are a few ideas, guided by which you can move forward on the path of mastering the art of writing clean and beautiful code.
Names
Kendrick Lamar once said: "If I am going to tell a real story, I will start it with my name."
In the world of programs, we meet names literally everywhere. We give names to functions, classes, arguments, packages, anything. Names come up for files with program code, for folders, and for everything that is in them. We are constantly inventing names, and therefore names often become something that pollutes the code.
The name that you give to an entity should reveal its purpose, the intention with which you use it. Choosing good names takes time, but it saves a lot more time when passions run high. Therefore, pay attention to the names, and if you manage to find a name that best copes with the task entrusted to it, replace with it what you already use. Anyone who reads your code will be grateful for your attention to the names.
Always remember that the name of any variable, function, or class must answer three main questions about an entity: why it exists, what functions it performs, and how it is used.
In order to come up with good names, you need not only the ability to look for suitable words. It requires familiarity with the cultural context common to the programmers of the whole Earth, for which there are no boundaries. This can not be taught - everyone masters all this on their own, for example - by reading the quality code of other people.
One function - one task
Louis Sullivan once said a wonderful thing: “Form follows function.”
Each system is built on the basis of a language intended for a specific subject area, which is designed by programmers to accurately describe this area. Functions are the verbs of this language, and classes are nouns. Functions are usually the first line of organization of any programming language, and their quality writing is the essence of creating good code.
There are only two rules for writing pure functions:
- They should be small.
- They should solve only one problem and should do it well.
This means that the function should not be too large; it should not contain nested structures. Thus, if we talk about indentation when formatting the code, there should not be more than one or two. This approach simplifies the reading of functions, their understanding and practical application. In addition to this, we must also ensure that all expressions in a function are at the same level of abstraction.
Mixing levels of abstraction in a function is always very confusing and leads, over time, to the appearance of code that cannot be controlled normally. Experienced programmers see functions as something like stories they tell, rather than code they write.
They use the mechanisms of their chosen programming language to create clean, expressive, highly capable blocks of code that, indeed, can be excellent storytellers.
Code and Comments
Here is an interesting observation that Venus Williams made: “Everyone makes their own comments. So rumors are born.
Comments in the code resemble a double-edged knife. Nothing could be more useful than a comment made to a place. On the other hand, nothing can litter the code more than empty, useless comments that simply take up space on the screen. And nothing can be more destructive than comments that spread misinformation and lies.
Comments, at best, are a necessary evil. Why? They are not always - evil, but in most cases it is. The older the comments, the more difficult it becomes to keep them up to date. Many programmers have tarnished their reputation by saying that their comments, in the course of developing projects, have stopped agreeing with the code.
The code is changing and evolving. Code blocks are being moved. And the comments remain unchanged. This is already a problem.
Always remember that a clean and expressive code with a minimum of comments is much better than an intricate and complex text of a program with many explanations. Don't waste time trying to explain the mess you created, better take the time to clean up the code.
The importance of formatting
Robert Martin once remarked very precisely: “Code formatting is aimed at transferring information, and transferring information is a top priority for a professional developer.”
I think you can not underestimate this idea. Attention to code formatting is one of the most important characteristics of really good programming.
Formatted code is a window into your mind. We want to impress other people with our accuracy, attention to detail and clarity of thought. But if the one who reads the code sees erratic jumble of constructions, a jumble that has neither beginning nor end, this immediately casts a shadow on the author’s reputation. There is no doubt about it.
If you think that the most important thing for a professional developer is “to make the program work”, it means that you are very far from the truth. The functionality created today may well change in the next release of the program, but the readability of the code is what influences everything that happens to it from the very beginning of its existence.
The programming style and readability of the code continue to influence the program maintainability even after its initial appearance has been transformed beyond recognition.
Consider that you are remembered by those who read the texts of your programs, according to your style and accuracy, and very rarely - according to the functionality implemented in the code. Therefore, pay attention to formatting, for example, adhering to the rules that are accepted in your organization.
First try-catch-finally, then everything else.
Georges Kangil made the right observation when he said: "It is human nature to err, to persist in error is the work of the devil."
Error handling is done by all programmers. Where do errors come from? Anomalous input data may enter the system, devices may malfunction ... It is expected from developers that they ensure the correct operation of the programs created by them. However, the problem is not the error handling itself. The problem is to handle errors without disrupting the readability and cleanliness of the underlying code.
Many programs beyond measure are overloaded with error handling structures. As a result, the useful code is randomly scattered around these constructs. This leads to the fact that what constitutes the goal of the program is almost impossible to understand. This is completely wrong. The code must be clean and reliable, and errors must be handled elegantly and with taste. Such an approach to error handling is a sign of a programmer who knows his business well.
One way to handle error quality is to use try-catch-finally blocks correctly. They include potentially bad places, and with their help they organize interception and error handling. These blocks can be thought of as highlighting isolated scopes in code. When the code is executed in a try block, it indicates to the person who is reading the code that the execution can be interrupted at any time and then continue in the catch block.
Therefore, it is recommended to allocate try-catch-finally blocks at the very beginning of work on the program. This, in particular, will help you determine what the one who will read it can wait for the code, and it does not matter if the code runs without an error, or if the fragment enclosed in the try block fails.
In addition, always strive to ensure that each exception issued by your program would necessarily contain enough contextual information to determine the source of the error and the place in the code where it occurred. Constructive and informative error messages are what the programmer remembers even after he has moved to a new job.
Results
How to express, literally in two words, everything that we talked about? The answer to this question is the term “code sense”. This, in the programming world, is the equivalent of common sense.
Here is what Robert Martin says about this: “In order to write clean code, you must consciously apply a multitude of techniques, guided by a sense of“ purity ”acquired by hard work. A key role here is played by a sense of code. Some are born with this feeling. Others work to develop it. This feeling not only makes it possible to distinguish good code from bad code, but also demonstrates a strategy for applying our skills to transform bad code into clean code. ” To me, these are golden words.
The feeling of the code helps the programmer to choose the best tools available to him, the use of which will help him in his quest to create a clean and beautiful code that benefits other people.
A clean code writer is an artist. He is able to turn an empty screen into an elegant work of art that will be remembered for many years.
At the end of our talk about clean code, let us recall the words of Harold Abelson: “Programs must be written, first of all, in order for people to read them, and only the second - for the execution of the machine”.
Dear readers! What techniques do you use to improve the quality of your own code?
