One : advance return, reduce else
If if-else Code block contains return sentence , It can be considered through advance return, Put the superfluous else kill .
Code example :
Before change :
if (condition1) { if (condition2) { return getSomething(); } else { return 0; }
} else { return 0; }
After change
// This is the best place flag The judged logic is described by supplementary notes boolean flag = !condition1 || (condition1 && !
condition2) if(flag) { return 0; } if (condition1 && condition2) { return
getSomething(); }
Two : Using ternary operators
Code example :
Before change :
int price ; if(condition){ price = 80; }else{ price = 100; }
After change :
int price ; int price = condition?80:100;
Three : use Java8 New features of Optional Judge whether it is null
Code example :
Before change :
String str = "xxxxx"; if (str != null) { System.out.println(str); } else {
System.out.println("Null"); }
After change :
Optional<String> strOptional = Optional.of("xxxxx"); strOptional.
ifPresentOrElse(System.out::println, () -> System.out.println("Null"));
Four : Use enumeration to reduce if --else
Code example :
Before change :
String OrderStatusDes; if(orderStatus==0){ OrderStatusDes =" Order not paid "; }else if(
OrderStatus==1){ OrderStatusDes =" Order paid "; }else if(OrderStatus==2){
OrderStatusDes=" Shipped "; } ...
After change :( Define an enumeration first )
public enum OrderStatusEnum { UN_PAID(0," Order not paid "),PAIDED(1," Order paid "),SENDED(2,
" Shipped "),; private int index; private String desc; public int getIndex() { return
index; } public String getDesc() { return desc; } OrderStatusEnum(int index,
String desc){ this.index = index; this.desc =desc; } OrderStatusEnum of(int
orderStatus) { for (OrderStatusEnum temp : OrderStatusEnum.values()) { if (temp.
getIndex() == orderStatus) { return temp; } } return null; } }
With enumeration , above if-else Logical branch , Can be optimized to one line of code :
String OrderStatusDes = OrderStatusEnum.0f(orderStatus).getDesc();

Technology
©2019-2020 Toolsou All rights reserved,
JAVA Detailed explanation of anomalies MySQL An interview is a must ! How to use it quickly html and css Write static page R Language cluster analysis case Dialogue between apple and Nissan suspended ,Apple Car How's it going ?java Realize the function of grabbing red packets SpringBoot practice ( five ):mybatis-plus In BaseMapper,Iservice and ServiceImpl Google says home office affects work efficiency !2021 Return to offline office in 2010 about keras use fit_generator Encountered in StopIteration Programmer Tanabata Valentine's Day confession code