⭐⭐⭐ Spring Boot 项目实战 ⭐⭐⭐ Spring Cloud 项目实战
《Dubbo 实现原理与源码解析 —— 精品合集》 《Netty 实现原理与源码解析 —— 精品合集》
《Spring 实现原理与源码解析 —— 精品合集》 《MyBatis 实现原理与源码解析 —— 精品合集》
《Spring MVC 实现原理与源码解析 —— 精品合集》 《数据库实体设计合集》
《Spring Boot 实现原理与源码解析 —— 精品合集》 《Java 面试题 + Java 学习指南》

摘要: 原创出处 medium.com/@manuchekhrdev/20-java-best-practices-7e72da91ef25 「网络」欢迎转载,保留摘要,谢谢!


🙂🙂🙂关注微信公众号:【芋道源码】有福利:

  1. RocketMQ / MyCAT / Sharding-JDBC 所有源码分析文章列表
  2. RocketMQ / MyCAT / Sharding-JDBC 中文注释源码 GitHub 地址
  3. 您对于源码的疑问每条留言都将得到认真回复。甚至不知道如何读源码也可以请教噢。
  4. 新的源码解析文章实时收到通知。每周更新一篇左右。
  5. 认真的源码交流微信群。

Java最佳实践是帮助开发人员编写高效、可维护且无错误代码的指导原则。一些最佳实践包括使用有意义的变量名,遵循命名约定,编写可读和可维护的代码,最小化变量的作用域,避免魔术数字和字符串,使用try-with-resources,正确处理异常等等。

1.使用描述性且有意义的变量名称

// Bad naming
int a;
void m() {}
class MyC {}

// Good naming
int age;
void printName() {}
class User {}

2. 遵循类、方法和变量的正确命名约定

// 错误的命名
class my_class {
public void calculate() {
int a = 5;
}
}

// 正确的命名
class MyClass {
public void calculateValue() {
int age = 5;
}
}

3.避免使用“魔法数字”

// 不好的做法
int result = 5 * 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
}

4. 对不会改变的值使用常量

// 不好的做法
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;
}

5.不要写重复的代码(DRY原则)

// 不好的做法
public void calculateTax() {
double taxRate = 0.25;
double tax = amount * taxRate;
double total = amount + tax;
}

public void calculateTotal() {
double taxRate = 0.25;
double tax = amount * taxRate;
double total = amount + tax;
}

// 好的做法
public void calculateTax() {
double taxRate = 0.25;
double tax = amount * taxRate;
return tax;
}

public void calculateTotal() {
double tax = calculateTax();
double total = amount + tax;
}

6.使用try-catch块来处理异常

// 不好的做法
public void readFile() {
File file = new File("example.txt");
BufferedReader reader = new BufferedReader(new FileReader(file));
String line = reader.readLine();
// Do something with the line
}

// 好的做法
public void readFile() {
try {
File file = new File("example.txt");
BufferedReader reader = new BufferedReader(new FileReader(file));
String line = reader.readLine();
// Do something with the line
} catch (IOException e) {
e.printStackTrace();
}
}

7. 在finally块中关闭资源

// 不好的做法
public void readFile() {
BufferedReader reader = null;
try {
File file = new File("example.txt");
reader = new BufferedReader(new FileReader(file));
String line = reader.readLine();
// Do something with the line
} catch (IOException e) {
e.printStackTrace();
} finally {
reader.close();
}
}

// 好的做法
public void readFile() {
BufferedReader reader = null;
try {
File file = new File("example.txt");
reader = new BufferedReader(new FileReader(file));
String line = reader.readLine();
// Do something with the line
} catch (IOException e) {
e.printStackTrace();
} finally {
if (reader != null) {
try {
reader.close();
} catch (IOException e) {
e.printStackTrace();
}
}
}
}

8.使用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();

9. 使用枚举来表示常量值

public enum CarType {
SEDAN,
HATCHBACK,
SUV
}

10.使用try-with-resources进行资源管理

try (FileInputStream fileInputStream = new FileInputStream(file)) {
// read from file
} catch (IOException e) {
// handle exception
}

11. 对常量和静态方法使用静态导入

import static java.lang.Math.PI;
import static java.lang.Math.pow;

double area = PI * pow(radius, 2);

12.使用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;
}
}

13. 使用接口和抽象类实现代码可重用性

// 没有接口
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");
}
}

14.使用元数据注释

@Deprecated
public void oldMethod() {
// do something
}

@SuppressWarnings("unchecked")
List<String> list = (List<String>) new ArrayList();

15. 使用检查异常来处理可恢复的错误

public void readFromFile(String fileName) throws FileNotFoundException, IOException {
try (FileInputStream fileInputStream = new FileInputStream(fileName)) {
// read from file
}
}

16.使用最小权限原则

public class BankAccount {
private double balance;

public double getBalance() {
return balance;
}

// 只允许存款,不允许取款
public void deposit(double amount) {
balance += amount;
}
}

17. 使用常量而不是硬编码值

// 硬编码值
if (statusCode == 200) {
// do something
}

// 常量值
private static final int HTTP_STATUS_OK = 200;

if (statusCode == HTTP_STATUS_OK) {
// do something
}

18.使用 Diamond 运算符简化泛型类型推断

// 没有 Diamond 运算符
List<String> list = new ArrayList <String>();

// 使用 Diamond 运算符
List<String> list = new ArrayList <>();

19. 重写方法时使用@Override注释

class Parent {
void print() {
System.out.println("Parent");
}
}

class Child extends Parent {
@Override
void print() {
System.out.println("Child");
}
}

20.使用final关键字来防止类或方法重写

// Class
final class MyClass {}

// Method
class Parent {
final void print() {}
}

class Child extends Parent {
// Compilation error: Cannot override the final method from Parent
}

此外,通过尽量减少对象创建,使用StringBuilder进行字符串连接,以及针对特定任务使用正确的数据结构和算法来编写高效的代码也是非常重要的。代码也应该有适当的文档,并且应该使用单元测试来确保代码的正确性。

说到Java编程,一致性是关键。一致的编码风格、约定和实践使代码更易于阅读、维护和理解。通过遵循最佳实践,Java开发人员可以编写更好的代码,提高性能,并降低错误和bug的风险。

文章目录
  1. 1. 1.使用描述性且有意义的变量名称
  2. 2. 2. 遵循类、方法和变量的正确命名约定
  3. 3. 3.避免使用“魔法数字”
  4. 4. 4. 对不会改变的值使用常量
  5. 5. 5.不要写重复的代码(DRY原则)
  6. 6. 6.使用try-catch块来处理异常
  7. 7. 7. 在finally块中关闭资源
  8. 8. 8.使用StringBuilder类进行字符串串联
  9. 9. 9. 使用枚举来表示常量值
  10. 10. 10.使用try-with-resources进行资源管理
  11. 11. 11. 对常量和静态方法使用静态导入
  12. 12. 12.使用final关键字保证不变性
  13. 13. 13. 使用接口和抽象类实现代码可重用性
  14. 14. 14.使用元数据注释
  15. 15. 15. 使用检查异常来处理可恢复的错误
  16. 16. 16.使用最小权限原则
  17. 17. 17. 使用常量而不是硬编码值
  18. 18. 18.使用 Diamond 运算符简化泛型类型推断
  19. 19. 19. 重写方法时使用@Override注释
  20. 20. 20.使用final关键字来防止类或方法重写