我们发现一个问题在写代码的会用到很多的IF-ELSE,但是笔者在最近看一个项目的时候发现大量的IF-ELSE,笔者的眼睛都看花了,精简IF-ELSE ,漂亮多了,下面我就来将几种用法!
1.如果只存在两种结果,就像下面一样代码,就使用三目运算吧
实例代码:
//我们常规写法
if (state) {
//do Something
return true;
}else {
return false;
}
精简代码:
提前Return法
//精简写法,提前return
if (!state) {
return false;
}
//do Something
return true;
三目运算法
state ? true : false
2.数组小技巧
Google解释,这是一种编程模式,叫做表驱动法,本质是从表里查询信息来代替逻辑语句
示例代码:
public static int getMonthDays(int month) {
if (month == 1) return 31;
if (month == 2) return 29;
if (month == 3) return 31;
if (month == 4) return 30;
if (month == 5) return 31;
if (month == 6) return 30;
if (month == 7) return 31;
if (month == 8) return 31;
if (month == 9) return 30;
if (month == 10) return 31;
if (month == 11) return 30;
if (month == 12) return 31;
return 0;
}
public static int getMonthDaysTwo(int month) {
int monthDays[] = {31, 29, 31, 30, 31, 30, 31, 31, 30, 31, 30, 31};
return monthDays[--month];
}
3.枚举
示例代码
public class IF {
public static void main(String[] args) {
Status status = Status.valueOf("TRUE");
System.out.println("状态:"+status.Something());
}
}
enum Status {
TRUE{
@Override
boolean Something() {
//do Something
return true;
}
},
FALSE{
@Override
boolean Something() {
//do Something
return false;
}
};
abstract boolean Something();
}
4.键值对
示例代码
Map<Integer,Object> status = new HashMap();
status.put(1,"true");
status.put(0,"false");
System.out.println(status.get(1));
注意:这个玩玩就行了,因为new出来是去堆开辟了一个空间
运行效果图:
结语:If-Else作为每种编程语言都不可或缺的条件语句,一般建议嵌套不要超过层,如果一段代码存在过多的嵌套,后期维护难度也大大提高。