java if else嵌套代码重构
来源:互联网 发布:淘宝的追加评论在哪里 编辑:程序博客网 时间:2024/06/10 05:22
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. 减少上面的判断冗余
阅读全文
0 0
- java if else嵌套代码重构
- if else 的代码重构
- 代码重构----使用java有限状态机来消除太多的if else判断
- 代码重构----使用java有限状态机来消除太多的if else判断
- 对if/else重构
- 重构删除if else
- if...else嵌套
- if , if else , if else if , if的嵌套
- 过多的if else重构
- if-else重构与设计模式
- Java语言——else if语句嵌套的优化
- Java中条件语句和if-else的嵌套原则
- 重构—改善代码既有设计 之if/else使用
- if else及嵌套循环
- 嵌套的if-else语句
- if..else语句的嵌套
- IF ELSE语句(嵌套)
- 嵌套if-else与多重~
- 单链表
- drag 弹框
- PHP 时间戳转换成 已读文本:刚刚、几小时前、几分钟前、昨天
- Linux 常用命令
- drag confirm
- java if else嵌套代码重构
- Android Studio 升级到3.0遇到的坑
- List去重
- mysql数据库sql语句集锦
- es6之decorator
- 冒泡排序
- java 核心代码加密思路
- 子类与继承
- Ionic3项目开发——发起定向HTTP请求