JavaRush /Java Blog /Random EN /Robert Martin, Clean Code. Review of the book on “kung fu...
Artem Murk
Level 35
Днепр

Robert Martin, Clean Code. Review of the book on “kung fu code” for developers

Published in the Random EN group
Hello Javarashevites! This article is a review of the book “Clean Code” by Robert Martin. Together we will look at ways to improve and optimize your code, and at the end a small but interesting task awaits you.
"Clean Code" by Robert Martin.  Review of the book on “kung fu code” for developers - 1
Every day, when we open your code editor, we are faced with many classes, functions and variables. The best option is if this is your code written from scratch, written once, there are few lines in it, you are working on it alone, there are no edits and no further support from the customer. BUT! As practice shows, yes, I think you yourself understand that this does not happen. Basically, we will have to somehow interact with members of our team, maintain the “Hindu” code, and parse products into millions of lines. I have often heard answers like this from my training colleagues: “This code was written by me, and I am not going to show it to anyone,” but when I see requests on Help for Help with such code, it takes a very long time (sometimes really a long time) to delve into and understand What did the person want to tell me, I even want to say “erase and rewrite again”! Appreciate the time and energy of people who want to help you, write correctly, and if you don’t know how, it’s never too late to learn. Robert Martin's book stands out among books of this format in that it contains many examples in Java. This may be a bit of a fanatical statement on my part, but it was written in OOP style, namely in the writing of parts and sections. Easy to understand and read, the book is easy to read on the go or in the evening before bed. Clean Code is divided into 3 parts. In the first part, we are asked to go through the theory of the book, learn about design patterns and rules of good manners. The second part invites us to practice refactoring and writing, and the third part is the final summary of the code “smells” in the examples. Well, the author touched on many topics for which you will mainly need knowledge of Java Core, but there are also sections dedicated to JUnit Unit Tests, Log4j Logging, knowledge of the simplest patterns in design (but as I said above, there are not many of them, and everything incomprehensible can be successfully googled, yes and analyzing it in the JavaRush course). All chapters of the book are not related to each other; you can successfully start reading from the chapter that you like. A brief summary of the main ideas that I picked up from the book. I would be grateful for your comments on them, in which you can share your own vision of these statements.

1. Comments == evil.

In most cases, comments are crutches with which we try to cover up our bad code. And in some cases, they also lie about the purpose of methods or variables if there is constant code refactoring.

2. Commented code, dead code.

Leaving these pieces of code in your application is tantamount to garbage. Unused code accumulates over time and interferes with the cleanliness of your application, check the code for such modules from time to time.

3. Headings of methods, classes and variables.

It is worth separate articles to discuss this topic. Don’t be lazy and write names that can tell about their purpose. Learn some standards in spelling titles. This topic is “Must Have” for detailed study.

4. Each method and variable has its place in the class hierarchy.

Typically, a class can have variables and methods (static and non-static), a constructor, nested and inner classes, and enums. In short, there is a lot of information, and it is necessary to determine everyone’s place in the class. If you look at the java core classes, you will see that the structure is clearly structured, we can see each part in its place, of course in your projects it can change within the project, but not in each class. For myself, I have defined the following construction structure: At the beginning of the class I have static variables, then object variables + Enums if they exist. After the variables, I define the class constructors. Then I write methods for working with the class. After the methods I write getters and setters. And at the very end I have inner classes. You can use my structure or write your own in the comments.

5. Levels of abstraction of methods.

For me this was discovery No. 1. Each method contains operators at only one level of abstraction. You shouldn’t mix multi-level operations together.

6. Error handling.

Checked or Unchecked Exceptions, which is better to use in the project (what do you think?, write comments)? I am a supporter of checked, but the book helps to look at Unchecked Exceptions from the outside. Indeed, unchecked Exception does not disfigure the method signature, especially considering that exceptions “pierce” several layers at once. The inconvenience of the smallest change leads to redefinition of the entire chain of methods before catching it, which is extremely inconvenient for development in many cases.

7. Code formatting.

Properly formatted code is not only clear, but also highly readable. You immediately get an idea of ​​the brackets and the actions inside. Using the example of conditions in the if, else constructs, you shouldn’t write everything in one line, it’s better to move long chains.

8. Negations in the condition.

Try to avoid denial in conditions, this is more of a psychological factor, our brain does not perceive denial well, and yes! before the expression may not be noticed. For example, negating if (!condition.isTrue) is better to rewrite the method, it will make it much easier like this (condition.isFalse)

9. Functions must perform one operation.

If your method performs many operations, then divide them into single-operation methods. These methods are very easy to support, easy to test, and, if necessary, replaced or removed.

10. Don't repeat yourself.

Don't repeat the code DRY (Don`t repeat yourself). This is one of the fundamental rules that will reduce your code significantly, keep it in mind. Try to put all your repeated pieces of code into a separate function. Of course, we can talk a lot more about DRY, KISS(Keep it simple Stupid), SOLID , YAGNI. These terms are essential for understanding and design. They are worth a separate article, perhaps I will write about them again, since this article is devoted to a review of the book “Clean Code”.
"Clean Code" by Robert Martin.  Review of the book on “kung fu code” for developers - 2
As promised, a small and easy task for you. The program must calculate the Obesity Index based on the given data. Write in the comments the number of errors and fixes in the code. P.S. The code is working and performs its function if used correctly.
//Weight in kg.
//Height in metres.
public class sample {
    public static void main (String[] args) {
        humanIMB humanIMB = new humanIMB(80,1.52);
        System.out.println(humanIMB.Result());
    }
}
class humanIMB {
    public double W; //Weight Human
    public double H; // Height Human
    private static double imb;
    public humanIMB(double w, double h) {
        W = w;
        H = h;
        imb = W / (H * H);
    }
    public double takeW() {
        return W;
    }
    public void putW(double w) {
        W = w;
        imb = W / (H * H);
    }
    public double takeH() {
        return H;
    }
    public void putH(double h) {
        H = h;
        imb = W / (H * H);
    }
    public static double takeImt() {
        return imb;
    }
    public static String Result() {
        String  string = null;
        if (imb >=18.5 & imb <25) {
            string ="Норма, ты в форме!";
        }
        if (imb >=25 & imb <30) {
            string ="Предожирение. Эй, поосторожнее с пирожными ";
        }
        if (imb >=30) {
            string ="Ожирение. SCHWEINE! Хватит жрать, иди на треню!";
        }
        if (imb <18.5) {
            string ="Дефицит массы тела. В модели решил переквалифицироваться?";
        }
        return string;
    }
}
Comments
TO VIEW ALL COMMENTS OR TO MAKE A COMMENT,
GO TO FULL VERSION