JavaRush /Java Blog /Random EN /Robert Martin, Clean Code. Kung Fu Code book review for d...
Artem Murk
Level 35
Днепр

Robert Martin, Clean Code. Kung Fu Code book review for developer

Published in the Random EN group
Hello Javarashians! This article is an overview of the book "Clean Code" by Robert Martin. Together we will look at ways to improve and optimize your code, and at the end you will find a small but interesting task.
"Clean Code" by Robert Martin.  Kung Fu Code Book Review for Developer - 1
Every day when we open your code editor we come across a lot of 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 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 disassemble products into millions of lines. I often heard answers from my fellow students such as "This code was written by me, and I'm not going to show it to anyone", but when I see Help requests with such a code on Help, I have to delve into and understand for a very long time (sometimes really long) what the person wanted to tell me, I even want to say “erase and rewrite again”! Appreciate the time and strength of people who want to help you, write correctly, and if you don’t know how, then it’s never too late to learn. Robert Martin's book compares favorably among books of this format in that it has many examples in Java. Maybe a bit of a fanatical statement on my part, but it is written in the OOP style, namely in writing parts and sections. Easy to understand and read, the book is easy to read on the road or in the evening before bed. "Clean Code" is divided into 3 parts. In the first part, we are offered to go through the theory of the book, learn about design patterns and good manners. The second part invites us to practice refactoring and writing, and the third part is the final squeeze of the "smells" of the code in the examples. Well, the author touched on a lot of topics for the knowledge of which you basically need knowledge of Java Core, but there are also sections devoted 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 is successfully googled, and even analyzed on the CodeGym 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 gleaned from the book. I would be grateful for comments on them, in which you can share your own vision of these statements. A brief summary of the main ideas that I gleaned from the book. I would be grateful for comments on them, in which you can share your own vision of these statements. A brief summary of the main ideas that I gleaned from the book. I would be grateful for 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 assignment of methods, or variables if there is a constant refactoring of the code.

2. Zakomentirovannyy 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. Headers of methods, classes and variables.

Worth a separate article to address this topic. Do not be lazy and write names that can tell about your purpose. Learn some standards in spelling titles. This topic "Masthev" for a detailed study.

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

Usually, a class can have variables and methods (static and non-static), a constructor, nested and inner classes, and enums. In a word, there is a lot of information, and it is necessary to determine for everyone their place in the class. If you look into 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 every 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 any. After the variables, I define the class constructors. Then I write methods for working with the class. After 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 the opening number 1. Each method contains operators of only one level of abstraction. You should not interfere with multi-level operations in the heap.

6. Error handling.

Checked or Uncheked 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 from the side and at Unchecked Exceptions. Indeed, unchecked Exception does not spoil the method signature, especially if you take into account that exceptions “break through” several layers at once. The inconvenience of the smallest change leads to the redefinition of the entire chain of methods before it is caught, which is extremely inconvenient for development in many cases.

7. Code formatting.

Properly formatted code is not only slick, but also readable. Immediately there is an idea of ​​\u200b\u200bbraces and actions inside. Using the example of conditions in the if, else constructs - you should not write everything in one line, it is better to transfer long chains.

8. Negatives in a condition.

Try to avoid denial in conditions, this is more of a psychological factor, our brain does not perceive denial well, and indeed! before the expression can be overlooked. For example, the negation of if (!condition.isTrue) is better to rewrite the method, this will greatly facilitate it like this (condition.isFalse)

9. Functions must perform a single operation.

If your method performs many operations, then divide them into single-operation methods. These methods are very easy to maintain, easy to test, and replace or remove as needed.

10. Don't repeat yourself.

Do not repeat code DRY (Don`t repeat yourself ). This is one of the fundamental rules that will reduce your code many times, keep it in your head. Try to put all your repeating pieces of code into a separate function. Of course you can talk a lot more about DRY, KISS(Keep it simple Stupid), SOLID , YAGNI. These terms are necessary for understanding and design. They deserve a separate article, maybe I'll write about them again, because this article is devoted to an overview of the book "Clean Code".
"Clean Code" by Robert Martin.  Kung Fu Code Book Review for Developer - 2
As promised, a small and easy task for you. The program should calculate the Obesity Index from the given data. Write in the comments the number of errors and corrections in the code. P.s. The code is working and does its job 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