扬州市建设局网站 竣工备案,html5静态模板,网络推广大概需要多少钱,杭州信贷网站制作1. 三目运算符
可以理解为条件 ?结果1 : 结果2 里面的?号是格式要求。也可以理解为条件是否成立#xff0c;条件成立为结果1#xff0c;否则为结果2。
实例#xff1a;
public String handle(int code) {if (code 1) {return success;} else {return 条件成立为结果1否则为结果2。
实例
public String handle(int code) {if (code 1) {return success;} else {return error;}
}对于条件只有两个的情况下可以使用三目运算符来解决。
优化
public String handle(int code) {return code 1 ? success : error;
}当条件较少时可以增强代码阅读性减少代码臃肿。
2. 枚举类
当条件过多时就不能用三目运算符了我们可以使用枚举类。
实例
/*** 根据code获取支付方式* param code* return*/
public String handle(int code) {if (code 1) {return 支付宝;} else if (code 2) {return 微信;} else if (code 3) {return qq;} else if (code 4) {return 银行卡;} else {return 现金;}
}如果后面又增加code就需要再写if-else会越来越长并不好维护。
我们可以采用枚举类来优化。
优化
public enum PayTypeEnum {ALIPAY(1, 支付宝),WECHAT(2, 微信),QQ(3, QQ),BANK_CARD(4, 银行卡),CASH(5, 现金);private static MapInteger, String payTypeMap new HashMap();static {for (PayTypeEnum payTypeEnum : PayTypeEnum.values()) {payTypeMap.put(payTypeEnum.getCode(), payTypeEnum.getType());}}public static String get(int code) {if (payTypeMap.containsKey(code)) {return payTypeMap.get(code);}return payTypeMap.get(5);}private int code;private String type;public String getType() {return type;}public void setType(String type) {this.type type;}public int getCode() {return code;}public void setCode(int code) {this.code code;}PayTypeEnum(int code, String type) {this.code code;this.type type;}
}public static void main(String[] args) {String res PayTypeEnum.get(5);System.out.println(res);
}只需要传入相应的code即可获取数据不需要再写过长的if-else了。如果需要新增在枚举类里拓展就好了。
3. 使用断言Assert类
对Object进行判空是这样的。
实例
public void handle() {StudentDo studentDo null;if (studentDo null) {System.out.println(对象为空);} else {if (studentDo.getName() null) {System.out.println(学生姓名不能为空);} else if (studentDo.getScore() null) {System.out.println(学生成绩不能为空);}}
}我们可以使用断言类
优化
public void handle1() {StudentDo studentDo null;Assert.notNull(studentDo, 对象为空);Assert.notNull(studentDo.getName(), 学生姓名不能为空);Assert.notNull(studentDo.getScore(), 学生成绩不能为空);
}后面再进行业务操作即可。
4. 使用return
实例
public void handle() {StudentDo studentDo null;if (studentDo ! null) {//业务操作} else {return;}
}优化
public void handle1() {StudentDo studentDo null;if (studentDo null) {return;}//业务操作
}5. jdk1.8 Optional
实例
String stahello;
if(stanull){System.out.println();
}else{System.out.println(sta);
}优化
String stahello;
String aOptional.ofNullable(sta).orElse();
System.out.println(a);