clean code

Sun, Jul 4, 2021 One-minute read

if-else

提前 return

if (condition) {
    // doSth
} else {
    return;
}

☕☕☕

if (!condition) {
    return;
} 
// doSth 

使用条件三目运算符

int price;
if (condition) {
    price = 80;
} else {
    price = 100;
}

☕☕☕

int price = condition ? 80 : 100; 

使用枚举

String OrderStatusDes;
if (orderStatus == 0) {
    OrderStatusDes = "AAA";
} else if (orderStatus == 1) {
    OrderStatusDes = "BBB";
} else if (orderStatus == 2) {
    OrderStatusDes = "ccc";
} 

☕☕☕

public enum OrderStatusEnum {

}

合并条件表达式

使用 Optianal

String str = "AAA";
if (str != null) {
    System.out.println(str);
} else {
     System.out.println("Null");
}

☕☕☕

Optional<String> strOptional = Optional.of("AAA");
strOptional.isPresentOrElse(System.out::println, () -> System.out.println("Null"));