java if else嵌套代码重构

java if else 如果嵌套很深,代码的易读性差和冗余,遇到多个判断条件,适当提前 return,可以让代码结构清晰。

我们下看一个反例,代码如下:

public static boolean isInArea(double latitue, double longitude, double areaLatitude1, double areaLatitude2, double areaLongitude1, double areaLongitude2) {
    if (isInRange(latitue, areaLatitude1, areaLatitude2)) {
        if (areaLongitude1 * areaLongitude2 > 0) {
            if (isInRange(longitude, areaLongitude1, areaLongitude2)) {
                return true;
            } else {
                return false; // 冗余
            }
        } else {
            if (Math.abs(areaLongitude1) + Math.abs(areaLongitude2) < 180) {
                if (isInRange(longitude, areaLongitude1, areaLongitude2)) {
                    return true;
                } else {
                    return false; // 冗余
                }
            } else {
                double left = Math.max(areaLongitude1, areaLongitude2);
                double right = Math.min(areaLongitude1, areaLongitude2);
                if (isInRange(longitude, left, 180) || isInRange(longitude, 0, right)) {
                    return true;
                } else {
                    return false; // 冗余
                }
            }
        }
    } else {
        return false;
    }
}

public static boolean isInRange(double point, double left, double right) {
    if (point >= Math.min(left, right) && point <= Math.max(left, right)) {
        return true;
    } else {
        return false; 
    }

}
该代码的功能就是判断一个GPS point是否在给定的矩形区域内,代码逻辑上没有问题,大量的if else 导致代码不简洁。
如下我重写了这两个方法,减少冗余的判断,提前用return 返回,减少使用else语句。
优化后的代码如下:
public static boolean isInArea(double latitue, double longitude, double minLatitue, double maxLatitue, double minLongitude, double maxLongitude) {
    // located in latitude range.
    if (!isInRange(latitue, minLatitue, maxLatitue)) {
        return false;
    }

    // Eastern or Western Hemisphere.
    if (minLongitude * maxLongitude > 0) {
        return isInRange(longitude, minLongitude, maxLongitude);
    }

    // One is Eastern, the other is Western, span zero.
    if (Math.abs(minLongitude) + Math.abs(maxLongitude) < 180) {
        return isInRange(longitude, minLongitude, maxLongitude);
    }

    // One is Eastern, the other is Western ,span 180.
    return isInRange(longitude, maxLongitude, 180) || isInRange(longitude, minLongitude, -180);
}

private static boolean isInRange(double point, double left, double right) {
    return point >= Math.min(left, right) && point <= Math.max(left, right);
}
 
优化后代码简洁很多,结构也清晰点。
当有大量的if else 嵌套可以考虑如下方法让代码结构整洁:
1. 在if中return,减少else
2. 利用三元表达是减少判断
3. 减少上面的判断冗余
 

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值