您的位置:首页 > 编程语言

代码优化——去除你代码中的if...else...层层嵌套

2016-04-05 21:24 447 查看
首先来看问题代码:

public static String query(){
if(1==1){
if(2==2){
if(3==3){
if(4==4){
int b=0;
for(int i=0;i<10000;i++){
if(i<10){
continue;
}else{
b+=i;
return String.valueOf(b);
}
}
}else{
return "";
}
}else{
return "";
}
}else{
return "";
}
}else{
return "";
}
return "";
}

     其实我们会时常遇到这种逻辑上的嵌套判断,里面包含着各种循环,循环里面包含着小判断,刚开始的时候,代码还没有这么庞大,但是随着版本的迭代,后来的人很可能发现了这段代码有些逻辑上的小漏洞,于是就在这个基础上拼命加IF。。。else..最后搞得大家谁也不敢动这段代码,好像它一碰就会塌陷的样子。

     想到这个问题,是因为之前做过一个游戏的东西,本来就是个简单的抽奖逻辑,但是之后上线之前,PM大人让加上各种东西:比如,身份认证,线程安全,等待页面,活动未开始和活动已经结束处理等等。。。结果那个方法就神似了上面那个样子。

     今天写一段代码的时候,发现自己又陷入了各种if。。else嵌套,但是还好这次避开了这个坑:

public static String query(Student stu) throws NoSuchMethodException,
SecurityException, IllegalAccessException,
IllegalArgumentException, InvocationTargetException {
StringBuilder sb = new StringBuilder("select * from ");
Class stuClass = stu.getClass();// 获取class

/* 如果没有加入table注解,返回null */
if (!stuClass.isAnnotationPresent(Table.class)) {
return null;
}
Table table = (Table) stuClass.getAnnotation(Table.class);// 获取到table注解
sb.append(table.value() + " where 1=1 ");// 拼入表名称
/* 通过get方法获取field字段值 */
Field[] fields = stuClass.getDeclaredFields();// 获取类字段信息
for (Field fd : fields) {
if (!fd.isAnnotationPresent(Column.class)) {// 如果field未标记注解,不作为查询条件
continue;
}
String getMethodName = "get"
+ fd.getName().substring(0, 1).toUpperCase()
+ fd.getName().substring(1);
Method getMethod = stuClass.getMethod(getMethodName); // 获取到field的get方法
/* 如果函数动态调用返回值为空或者字段为integer未赋值,则不拼接 */
if (getMethod.invoke(stu) == null
|| (getMethod.invoke(stu) instanceof Integer && (Integer) getMethod
.invoke(stu) == 0)) {
continue;
}
if (getMethod.getReturnType() == String.class) {
sb.append("and " + fd.getName() + "='" + getMethod.invoke(stu)
+ "'");
} else if (getMethod.getReturnType() == int.class) {
sb.append("and " + fd.getName() + "=" + getMethod.invoke(stu));
}// 其他类型自己判断去吧。。。但是感觉这么写不好。。。。有待改进的方法

}

return sb.toString();
};


           看出来了么,在if语句中,通过提前返回来减少if的嵌套,在for循环中,通过continue来提前结束本次循环。基本思路都是让代码以最自然,最流畅,自正常的思路进行下去,避免自己在看代码的时候也陷入自己挖的思维巨坑。
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: