I have summarized 12 suggestions for writing high-quality code

foreword

After working for so many years, I have seen many codes, some are well written, and some are badly written. Good code is nothing more than making your code readable, maintainable, and extensible. It is not difficult to say, and it is not easy to say simple, so in this article I will summarize some practices on how to write clean code after so many years of work.

Welcome to pay attention to the personal public account [JAVA Xuyang] exchange and study

1. Use clear and meaningful naming

One of the most important principles of clean code is to use clear and meaningful naming. This makes it easy for other developers to understand what your code is doing and reduces the chance of errors. For example, instead of using a variable named "d" for distance, use a variable named "distance".

// Bad
int d = getDistance();

// Good
int distance = getDistance();
复制代码

2. Use the appropriate data type or data structure

Another important principle of clean code is to use proper data types, this ensures that your code will work properly and reduces the chance of errors. For example, instead of using a string to represent age, use an integer.

// Bad
String age = "25";

// Good
int age = 25;
复制代码

3. Keep the method short and to the point

Clean code is also about keeping methods short and to the point, a method should do only one thing and should be easy to understand which makes it easier to test and maintain the code. For example, instead of putting all the code that handles an order in one method, it can be broken down into smaller methods for validation, calculation, and saving.

// Bad
public void processOrder(Order order) {
    // lots of code
    }

    // Good
    public void processOrder(Order order) {
        validateOrder(order);
        calculateTotal(order);
        saveOrder(order);
    }
复制代码

4. Write clear and meaningful notes

Another important principle of clean code is writing clear and meaningful comments. Comments should explain why the code does what it does, not how it does it. This makes your code easier for other developers to understand.

// Bad, 只说明是递增
// increments count 
count++;

// Good,说明业务需要每次加1
// Increment the count by 1
count++;
复制代码

5. Use whitespace and indentation to improve readability

Clean code also means making it easy to read, using spaces and indentation to improve code readability. This makes it easier for other developers to understand what your code is doing.

// Bad
if(a==b){c=d;}

// Good
if (a == b) {
    c = d;
}
复制代码

6. Use exception handling the right way

Clean code requires exceptions to be handled in a correct manner. You should only catch exceptions that you can handle, and handle them in a specific way, avoiding catch-all exception handlers.

// Bad
try {
    // some code
} catch (Exception e) {
    // handle exception
}

// Good
try {
    // some code
} catch (IllegalArgumentException e) {
    // handle specific exception
} catch (Exception e) {
    // handle general exception
}
复制代码

7. Use encapsulation to hide implementation details

Encapsulation is a technique that helps hide the implementation details of a class and makes it more flexible and extensible. By using encapsulation, you can change the implementation of a class without affecting the rest of the code.

// Bad
public class BankAccount {
    public double balance;
    // other methods
}

// Good
public class BankAccount {
    private double balance;
    // other methods
}
复制代码

8. Use inheritance and polymorphism to write reusable code

继承和多态性是面向对象编程的强大功能,可让您编写可重用的代码。通过使用继承,您可以创建一个包含公共代码的基类,然后创建继承该代码的子类。通过使用多态性,您可以编写以通用方式处理不同类对象的代码。

// Bad
public class Square {
    // code specific to squares
}

public class Circle {
    // code specific to circles
}

// Good
public class Shape {
    // common code for all shapes
}

public class Square extends Shape {
    // code specific to squares
}

public class Circle extends Shape {
    // code specific to circles
}
复制代码

9.使用设计模式解决常见问题

通过使用设计模式,您可以编写易于理解、维护和扩展的代码。例如,策略模式是一种设计模式,可让您编写灵活且易于扩展的代码。

// Bad
public class OrderProcessor {
    public void processOrder(Order order) {
        // lots of code
    }
}

// Good
public class OrderProcessor {
    public void processOrder(Order order) {
        OrderStrategy strategy = new OrderStrategy(order);
        strategy.process();
    }
}
复制代码

10.使用单元测试确保代码按预期工作

干净的代码也与测试有关。通过编写单元测试,您可以确保您的代码按预期工作并且易于维护。单元测试是测试单个代码单元的自动化测试。

public class BankAccountTest {
    @Test
    public void testDeposit() {
        BankAccount account = new BankAccount();
        account.deposit(100);
        assertEquals(100, account.getBalance());
    }
}
复制代码

11.使用代码审查来提高代码质量

干净的代码也与协作有关。通过使用代码审查、结对编程和指导,您可以提高代码质量并使其更易于理解和维护。

12.使用工具来提高代码质量

开发工具安装 checkstyle 这样的代码格式化工具来检查代码,同样,sonarQube 也可以帮助检查代码中的问题。

总结

总而言之,代码不是写给自己看的,而是写给别人看的。你得想办法让你的代码能让别人容易看的懂、容易维护、能够很好的扩展,那么你才是一个合格的程序员,本文介绍了一些最佳实践和示例,希望对你有帮助。

欢迎关注个人公众号【JAVA旭阳】交流学习

Guess you like

Origin juejin.im/post/7192404260946968613