How to write clean and beautiful code

Original author: Ravi Shankar Rajan
  • Transfer
What should be a quality code? Robert Martin expressed this incredibly accurately when he said: “The only adequate measure of code quality is the number of exclamations of“ what the hell! ”Per minute.”

image

Let me clarify this idea.

Every time I read someone else’s code, these are the thoughts that come to my mind:

  • What the heck! (with disgust) - when a certain piece of code is not necessary.
  • 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 in front of my eyes.

So, what makes the first impression of the code? This is how pure and beautiful he is. Such a code is a sign of high professionalism of the person who wrote it.

The path to coding mastery goes through two important milestones. This is knowledge and labor. Knowledge provides patterns, principles, practical techniques, heuristic rules that are necessary for professional growth. But this knowledge needs to be consolidated. Here mechanical and visual memory comes into play, knowledge must be firmly established within you through constant practice and hard work.

In short, learning to write clean code is hard work. You must put a lot of effort into it. You need practice. Moreover, on this path there will be times when things stop, when nothing works, but it should not stop you - step by step you will approach perfection, repeat everything again and again until everything turns out to be what it should be . There are no workarounds.

Here are a few ideas that guide you through the path to mastering the art of writing clean and beautiful code.

The 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 find names literally everywhere. We give names to functions, classes, arguments, packages, whatever. Names come up for files with program code, for folders, and for everything that is in them. We constantly invent names, and so names often become what pollutes the code.

The name that you give the entity should reveal its purpose, the intention with which you use it. Choosing good names takes time, but saves you a lot more time when passions run high. Therefore, pay attention to the names, and if you manage to find a name that better copes with the task assigned to it, replace it with what you are already using. Anyone reading your code will appreciate your attention to the names.

Always remember that the name of any variable, function, or class should answer three main questions about a certain 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. This requires familiarity with the cultural context common to programmers throughout the Earth, for which there are no boundaries. This can not be taught - everyone learns all this independently, for example - 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 verbs of this language, and classes are nouns. Functions are usually the first line of organization of any programming language, and their high-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 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 the 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 in functions something like the stories they tell, rather than the code they write.

They use the mechanisms of their chosen programming language to create clean, expressive, highly featured blocks of code that, indeed, can be great storytellers.

Code and comments


Here is an interesting observation that Venus Williams made: “Everyone makes their own comments. Thus 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 clutter up the code more than empty, useless comments that simply take up space on the screen. And nothing can be more destructive than comments spreading misinformation and lies.

Comments, at best, are a necessary evil. Why? They are not always evil, but in most cases they are. The older the comments, the more difficult it becomes to keep them up to date. Many programmers tarnished their reputation by the fact that their comments, during the development of projects, ceased to be consistent with the code.
The code is changing and evolving. Blocks of code are moved. And the comments remain unchanged. This is already a problem.

Always remember that clean and expressive code with a minimum of comments is much better than confusing and complex program text, which has a lot of explanations. Do not waste time explaining the mess you created; rather, take the time to clean up the code.

Importance of formatting


Robert Martin once very accurately remarked: "Formatting the code is aimed at transmitting information, and the transfer of information is the primary task of a professional developer."

I suppose you should not underestimate this idea. Attention to code formatting is one of the most important characteristics of truly 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 someone who reads the code sees messy piles of structures, a hash that has no beginning or end, this immediately casts a shadow on the reputation of the author of the code. There is no doubt about that.

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 very well change in the next release of the program, but the readability of the code is what affects everything that happens to it from the very beginning of its existence.

The style of programming and the readability of the code continue to affect the maintainability of the program even after its initial appearance has been transformed beyond recognition.
Keep in mind that you will be 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 adopted in your organization.

First try-catch-finally, then everything else


Georges Kangilem made the right observation when he said: "It is human nature to make mistakes, to persist in a mistake is the work of the devil."

All programmers are involved in error handling. Where do the errors come from? The system may receive abnormal input data, devices may malfunction ... They are expected from developers to ensure the correct operation of the programs they create. However, the problem is not the error handling itself. The problem is to handle errors without violating the readability and cleanliness of the main code.

Many programs are overloaded with error handling constructs. As a result, 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 tastefully. A similar approach to error handling is a sign of a programmer who knows his job well.

One way to properly handle errors is to use try-catch-finally blocks correctly. They include potentially bad spots, and with their help organize the interception and error handling. These blocks can be thought of as highlighting isolated visibility areas in code. When the code is executed in a try block, this indicates to the person reading the code that 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 expect from the code, it does not matter if the code is executed without an error, or a failure occurs in the fragment enclosed in the try block.

In addition, always strive to ensure that every exception thrown by your program necessarily contains 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 place of work.

Summary


How to express, literally in a nutshell, all 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: “To write clean code, you must consciously apply many tricks, guided by the sense of“ purity ”acquired by hard work. The key here is the sense of code. Some with this feeling are born. Others work to develop it. This feeling not only allows us to distinguish good code from bad code, but also demonstrates the strategy of applying our skills to transform bad code into clean code. ” For me, these are golden words.

The sense of code helps the programmer to choose the best tool available to him, the use of which will help him in his quest to create clean and beautiful code that benefits other people.

A programmer who writes clean code is an artist. He is able to turn a blank screen into an elegant work of art that will be remembered for many years.

At the end of our conversation about clean code, we recall the words of Harold Abelson: “Programs should be written, first of all, so that they can be read by people, and only the second - for execution by machine.”

Dear readers! What tricks do you use to improve the quality of your own code?


Also popular now: