• Java好的编码习惯


    写在前面

    记录Java编程的一些好习惯,不难,但重要!!!

    1:使用有意义的变量名称

    如:

    // Good naming
    int age;
    void printName() {}
    class User {}
    
    • 1
    • 2
    • 3
    • 4

    反例:

    function isJieKuanText(uuid, asr_text, task_id) {}
    
    
    • 1
    • 2

    你可以猜下是什么意思,留言告诉我,当然如果你遇到了比较有意思的命名,也欢迎分享出来,大家同乐!!!

    2:避免使用魔法数字

    // 好的做法
    int age = 5;
    int multiplier = 2;
    int result = age * multiplier;
    final int MAX_SIZE = 10;
    for (int i = 0; i < MAX_SIZE; i++) {
      // do something
    }
    
    • 1
    • 2
    • 3
    • 4
    • 5
    • 6
    • 7
    • 8

    反例:

    if(conn.identity == -1 && dtmfNumber == "0") {}
    if(dtmfNumber  == "1" || dtmfNumber  == "2" || dtmfNumber  == "3" || dtmfNumber  == "4") {}
    
    • 1
    • 2

    3:不会改变的之使用常量

    提高安全性,避免值被意外修改导致bug。

    // 不好的做法
    public void calculate() {
      double taxRate = 0.25;
      double result = amount * taxRate;
    }
    
    // 好的做法
    public static final double TAX_RATE = 0.25;
    
    public void calculate() {
      double result = amount * TAX_RATE;
    }
    
    • 1
    • 2
    • 3
    • 4
    • 5
    • 6
    • 7
    • 8
    • 9
    • 10
    • 11
    • 12

    4:使用stringbuilder拼接字符串

    // 不好的做法
    String name = "John";
    String message = "Hello, " + name + "!";
    
    // 好的做法
    String name = "John";
    StringBuilder sb = new StringBuilder();
    sb.append("Hello, ");
    sb.append(name);
    sb.append("!");
    String message = sb.toString();
    StringBuilder sb = new StringBuilder();
    sb.append("Hello");
    sb.append(" ");
    sb.append("World");
    String message = sb.toString();
    
    • 1
    • 2
    • 3
    • 4
    • 5
    • 6
    • 7
    • 8
    • 9
    • 10
    • 11
    • 12
    • 13
    • 14
    • 15
    • 16

    因为stringbuffer是线程安全,所以会有额外的加锁释放锁的性能开销,非必要就不要使用了。

    5:有限的几种值使用枚举表示

    public enum CarType {
      SEDAN,
      HATCHBACK,
      SUV
    }
    
    • 1
    • 2
    • 3
    • 4
    • 5

    6:使用try-with-resources进行资源管理

    try (FileInputStream fileInputStream = new FileInputStream(file)) {
      // read from file
    } catch (IOException e) {
      // handle exception
    }
    
    • 1
    • 2
    • 3
    • 4
    • 5

    7: 对常量和静态方法使用静态导入

    import static java.lang.Math.PI;
    import static java.lang.Math.pow;
    
    double area = PI * pow(radius, 2);
    
    • 1
    • 2
    • 3
    • 4

    8: 使用final关键字保证不变性

    public final class Person {
      private final String name;
      private final int age;
    
      public Person(String name, int age) {
        this.name = name;
        this.age = age;
      }
    
      public String getName() {
        return name;
      }
    
      public int getAge() {
        return age;
      }
    }
    
    • 1
    • 2
    • 3
    • 4
    • 5
    • 6
    • 7
    • 8
    • 9
    • 10
    • 11
    • 12
    • 13
    • 14
    • 15
    • 16
    • 17

    9:使用接口和抽象类实现代码可重用性

    // 没有接口
    class Dog {
        void bark() {
            System.out.println("Woof");
        }
    }
    
    class Cat {
        void meow() {
            System.out.println("Meow");
        }
    }
    
    // 使用接口
    interface Animal {
        void makeSound();
    }
    
    class Dog implements Animal {
        @Override
        void makeSound() {
            System.out.println("Woof");
        }
    }
    
    class Cat implements Animal {
        @Override
        void makeSound() {
            System.out.println("Meow");
        }
    }
    
    • 1
    • 2
    • 3
    • 4
    • 5
    • 6
    • 7
    • 8
    • 9
    • 10
    • 11
    • 12
    • 13
    • 14
    • 15
    • 16
    • 17
    • 18
    • 19
    • 20
    • 21
    • 22
    • 23
    • 24
    • 25
    • 26
    • 27
    • 28
    • 29
    • 30
    • 31

    10:使用检查异常来处理可恢复的错误

    可恢复,即可补偿。

    public void readFromFile(String fileName) throws FileNotFoundException, IOException {
      try (FileInputStream fileInputStream = new FileInputStream(fileName)) {
        // read from file
      }
    }
    
    • 1
    • 2
    • 3
    • 4
    • 5

    11:使用最小权限原则

    不需要的操作不提供,也不允许通过其他手段获得。

    public class BankAccount {
      private double balance;
    
      public double getBalance() {
        return balance;
      }
    
      // 只允许存款,不允许取款
      public void deposit(double amount) {
        balance += amount;
      }
    }
    
    • 1
    • 2
    • 3
    • 4
    • 5
    • 6
    • 7
    • 8
    • 9
    • 10
    • 11
    • 12

    12:使用常量而不是硬编码值

    // 硬编码值
    if (statusCode == 200) {
        // do something
    }
    
    // 常量值
    private static final int HTTP_STATUS_OK = 200;
    
    if (statusCode == HTTP_STATUS_OK) {
        // do something
    }
    
    • 1
    • 2
    • 3
    • 4
    • 5
    • 6
    • 7
    • 8
    • 9
    • 10
    • 11

    13:重写方法时使用@Override注释

    class Parent {
        void print() {
            System.out.println("Parent");
        }
    }
    
    class Child extends Parent {
        @Override
        void print() {
            System.out.println("Child");
        }
    }
    
    • 1
    • 2
    • 3
    • 4
    • 5
    • 6
    • 7
    • 8
    • 9
    • 10
    • 11
    • 12

    14:使用final关键字来防止类被继承或方法重写

    // Class final 避免被继承
    final class MyClass {}
    
    // Method
    class Parent {
        // final 避免被重写
        final void print() {}
    }
    
    class Child extends Parent {
        // Compilation error: Cannot override the final method from Parent
    }
    
    • 1
    • 2
    • 3
    • 4
    • 5
    • 6
    • 7
    • 8
    • 9
    • 10
    • 11
    • 12

    写在后面

    你有什么好的编程习惯,也留言告诉我吧!!!

    参考文章列表

    20 个 Java 最佳实践

  • 相关阅读:
    [AI-ML]机器学习是什么?一起了解!(一)
    Spring-依赖注入findAutowireCandidates源码实现
    代码随想录算法训练营第一天| 704、27、34、367、69
    Spring Boot 自动装配执行流程
    Java 近期新闻:JDK 19 进入 RDP2、Oracle 关键补丁更新、TornadoVM on M1、Grails CVE
    SpringBoot 整合ActiveMQ
    什么是RPA?RPA、智能自动化、人工智能、超自动化!你能区分吗?
    英伟达再放AI芯片“大招” H200 GPU是人工智能技术的里程碑
    【创建型】单例模式(Singleton)
    剑指 Offer II 093. 最长斐波那契数列
  • 原文地址:https://blog.csdn.net/wang0907/article/details/134502735