JavaRush /Java Blog /Random EN /How to write clean code

How to write clean code

Published in the Random EN group
Making your code clean and beautiful is a great way to meet deadlines. Robert Martin hit the nail on the head with one of his pithy statements: “The only true measure of code quality is the What-The-F**ks/Minute unit.” " in original). How to write clean code - 1Let me explain what this means. Every time I review code, my brain goes through one of three emotions:
  • “WTF?! What the heck?!" (with disgust) - this is not it... everything is very bad....
  • “WTF?! What the heck?!" (with admiration) - hmm, a smart guy did it!
  • “WTF?! What the heck?!" (with irritation) - some kind of confusion, what are we even talking about?!
So what is paramount and what exactly do we evaluate when we see some code? That's it: its purity and beauty. The ability to write clean and beautiful code is an indicator of a highly professional developer. Training in this skill is based on two components - knowledge and work. Knowledge teaches you patterns, principles, practices, heuristics. You need them to grow professionally. Only you must absorb this knowledge like a sponge through constant practice and hard work. In short, writing clean code is not easy. This is hard, painstaking work, and you will have to work hard at it. Through trial and error, you will improve by repeating the same steps over and over again until you find the solution you want. There is simply no simpler way. Below are some tips to help you learn how to write clean code.

What's in a name

Kendrick Lamar (American hip-hop artist - editor's note) once accurately noted: "If I'm going to tell the real story, I have to start with my name." The names in software development are everywhere. We name functions, classes, arguments, packages, programs—everything. We name source files and reference books and everything connected with it. We name things endlessly, and this becomes a critical part of working towards creating clean code. The name you give something should reflect the intent. Finding a good name is not easy, it takes time, but it also saves a lot of time when you have to deal with the code and the situation gets complicated. So be careful about this process and don't be afraid to change names later if you find something more suitable. Everyone who deals with your code will be very grateful to you.

Remember that the name of any variable, class, function must answer three main questions: why it (variable, function, etc.) exists, what it does and what it is used for.

This requires not only good descriptive skills, but also general erudition and a broad outlook. And no one can teach you this better than yourself.

clean code

“One function” - one thing

Louis Henry Sullivan (American rationalist and modernist architect) once famously said: “function determines form . ” He said this about the architecture of houses, but this does not change the essence. Each system is built on some domain-specific language that programmers create to accurately describe it. Functions act as verbs of the language, and classes are nouns. Most often, functions are paramount in the organization of a programming language, and writing them correctly is the essence of creating good code. There are only two golden rules for writing quality functions:
  1. They should be small
  2. They must do one thing, one task, and do it well
That is, your function should be small and should not contain nested structures. Thus, the function indentation levels should not be more than one or two. This approach makes the code much easier to read, understand, and comprehend. In addition, we must be sure that the expressions within the function are at the same level of abstraction. Mixing abstraction levels within a function always creates a lot of confusion and eventually leads to unmanageable code. The best programmers treat functions as stories to be told, not just code to write. They use the tools of their chosen programming language to create a rich, expressive, and cleaner block of code that can essentially act as a great storyteller.

“Comments don't make up for bad code”

Venus Williams, American tennis player and five-time Wimbledon champion, hit the nail on the head when she said: “Everyone leaves their comments. This is how rumors appear . " Comments are like a double-edged sword. A well-placed comment is a very useful thing. On the other hand, nothing clutters up space more than frivolous, useless comments. But the most damaging comments are those that spread misinformation and lies. In short, comments are a kind of necessary evil. Not always, but for the most part. Why? It's simple, the older the comment, the more difficult it is to maintain, and most programmers, as you know, do not always change comments along with changes in the code. The code moves and evolves. Parts of code are moved back and forth, but there are no comments. And this becomes a problem!

Remember: clean, clear code with few comments is much better than complex, cluttered code. Don't waste your energy explaining the chaos you created in the comments. Better spend that time cleaning up that mess.

clean code

“Code formatting is always a priority”

This was said by none other than Robert C. Martin, aka Uncle Bob, developer, author of many books on software development, consultant, co-author of the Agile manifesto, and so on. And he added: “Formatting code is a kind of communication. And communication is a top priority for any professional developer.” The above statement should not be underestimated, because it speaks to one of the most important characteristics of an excellent developer. Formatted code allows you to look deep into your mind. We want to impress people with our neatness, attention to detail, ability to organize and express our thoughts clearly. But if, when people look at the code, they see some kind of confusion, reminiscent of a vinaigrette, with neither beginning nor end, this negates your efforts and lowers the reputation of the developer. Don't even doubt it! You are very far from the truth if you think that the main thing in this business is that “the code just works.” The functionality you create today will most likely be changed in the next release, but the readability of the code will not change. The style of the code and its good readability make it easier to maintain the code for a long time, even after the original code has been changed beyond recognition.
Never forget that in the future, what will most likely be remembered is not your code itself, but your style and consistency. Therefore, make sure that the code is well formatted and follows simple rules that are understandable to all team members.

First create a "try-catch-finally" block

Georges Canguilhem (historian of science, philosopher) rightly noted: “To make mistakes is natural for a person, but to insist on mistakes is from the devil . ” Troubleshooting is something all programmers do. Invalid data may enter the input and devices may fail. And as developers, we need to make sure the code does what it's supposed to do. The issue is not just error handling, but “clean and easy to read” error handling. Many programs adapt to error handling. If you do this, everything descends into such chaos that the purpose and logic of the main code is destroyed. This is wrong, it shouldn't be this way. The code should be clean and reliable, and error handling should be seamlessly and naturally woven into the code. This is an indicator of a high-class programmer. And one of the ways to achieve this is through proper nesting and coverage of all errors in try-catch blocks. These blocks define the scope of your code. When you execute code in the try portion of a try-catch-finally block, you are stating that execution can abort at any time and then resume in a catch. Therefore, we recommend starting with try-catch-finally when you write code. This will help determine what the user can expect from the code, regardless of what goes wrong with the code during the try.
Always remember that every exception you throw must contain enough context to determine the location and source of the error. Creative and informative error messages are remembered long after the code has been written, even when the programmer is already busy with completely different tasks.
clean code

Let's sum it up

One unusual phrase will help us summarize all of the above. This is code-sense or “a sense of common code,” a kind of programmer equivalent of common sense. In the words of Robert Martin: “Writing clean code requires the systematic use of many small techniques, applied as a result of a meticulous and somewhat painful sense of “cleanliness.” These small techniques are collectively called code-sense . " Some of us have this “sound code sense” from the start, while others have to develop it through persistent practice. This instinct helps not only to recognize the difference between bad and good code, but also helps in the formation of strategies aimed at transforming bad code into good. Bad code ruins everything. Speaking figuratively, if you frost the most delicious cake with dog shit, then... uh... hardly anyone will like it. Code sense helps a programmer use the right tools to achieve his goal of creating clean code. A programmer who understands what code-sense is is an artist who can create a work of art on a blank screen that will be remembered for many years. As Harold “Hal” Abelson, professor of computer science at Mit and founding director of Creative Commons and the Free Software Foundation, summed it up: “Programs need to be written first so that people can read them, and then so that they can be executed.” car" . What you can read on the topic: “A handbook of Agile Software Craftsmanship” - Robert Martin. “A handbook of Agile estimation” - Mike Cohn About the author: Ravi Shankar Rajan is a Global IT Program Manager from Mumbai (India). Famous blogger, haiku poet, avid archeology and history buff. You can connect with him on Twitter , Medium , LinkedIn
Comments
TO VIEW ALL COMMENTS OR TO MAKE A COMMENT,
GO TO FULL VERSION