笔者的博客园地址,有更多Java开发干货:https://www.cnblogs.com/amberJava/

if-else深度优化:巧用状态变更枚举类: https://www.cnblogs.com/amberJava/p/12974976.html

If-else 过多,代码不易读,后人也不敢轻易修改。

个人觉得有如下几种优化方式,网上不胜枚举,可以自行百度,但是小编说的这个方法《if-else深度优化:巧用状态变更枚举》,网上例子不多。

业务场景:
例如在无人仓业务场景中,货架都放在储位上(储位就是地面上标记的某个点),正向流程:货架状态需要从空闲->预占->占用中->预释放->空闲。逆向流程相反。
储位状态需要根据不同的业务场景变更。

正常情况下,A服务请求批量变更储位状态,需要先校验状态是否正确,能否变更,if-else方法。在更新数据库构造更新体时,还需要设置变更前状态,变更后状态,if-else方法。

未优化前:

1.更新前校验

根据不同状态,判断是否可以变更。不能变更,返回错误体。

其中多重if-else嵌套,返回的错误信息也是+拼接

 1  for (StorageLocation requestPoint : request.getPointList()) {2             int taskType = requestPoint.getStorageStatus();3             if (PositionTaskType.PREOCCUPY.getTaskType().equals(taskType)) { //预占操作4                 if (!StorageStatusEnum.INIT.getStatus().equals(pointDBMap.get(requestPoint.getPoint()).getStorageStatus())) {5                     logger.error("{} 校验{}储位状态异常, 预占操作,状态应该是{} 实际是{},", request.getUuid(), requestPoint.getPoint(),StorageStatusEnum.INIT.getStatus(),pointDBMap.get(requestPoint.getPoint()).getStorageStatus());6                     response.setError(new Error(PositionErrorEnum.SYSTEMHANDLEEERROR.getErrorCode() + "", "校验"+requestPoint.getPoint()+"储位状态异常, 预占操作,状态应该是" + StorageStatusEnum.INIT.getStatus()+ " 实际是" + pointDBMap.get(requestPoint.getPoint()).getStorageStatus()));7                     return response;8                 }9
10             }else if (PositionTaskType.RELEASEPREOCCUPY.getTaskType().equals(taskType)) { //撤销预占操作
11                 if (!StorageStatusEnum.PREOCCUPY.getStatus().equals(pointDBMap.get(requestPoint.getPoint()).getStorageStatus())) {
12                     logger.error("{} 校验{}储位状态异常, 撤销预占操作,状态应该是{} 实际是{},", request.getUuid(), requestPoint.getPoint(),StorageStatusEnum.PREOCCUPY.getStatus(),pointDBMap.get(requestPoint.getPoint()).getStorageStatus());
13                     response.setError(new Error(PositionErrorEnum.SYSTEMHANDLEEERROR.getErrorCode() + "", "校验"+requestPoint.getPoint()+"储位状态异常, 撤销预占操作,状态应该是" + StorageStatusEnum.PREOCCUPY.getStatus()+ " 实际是" + pointDBMap.get(requestPoint.getPoint()).getStorageStatus()));
14                     return response;
15                 }
16
17             }else if (PositionTaskType.OCCUPY.getTaskType().equals(taskType)) { //占用操作
18                 if (!StorageStatusEnum.PREOCCUPY.getStatus().equals(pointDBMap.get(requestPoint.getPoint()).getStorageStatus())) {
19                     logger.error("{} 校验{}储位状态异常, 占用操作,状态应该是{} 实际是{},", request.getUuid(), requestPoint.getPoint(),StorageStatusEnum.PREOCCUPY.getStatus(),pointDBMap.get(requestPoint.getPoint()).getStorageStatus());
20                     response.setError(new Error(PositionErrorEnum.SYSTEMHANDLEEERROR.getErrorCode() + "", "校验"+requestPoint.getPoint()+"储位状态异常, 占用操作,状态应该是" + StorageStatusEnum.PREOCCUPY.getStatus()+ " 实际是" + pointDBMap.get(requestPoint.getPoint()).getStorageStatus()));
21                     return response;
22                 }
23
24             }else if (PositionTaskType.PRERELEASE.getTaskType().equals(taskType)) { //预释放操作
25                 if (!StorageStatusEnum.OCCUPY.getStatus().equals(pointDBMap.get(requestPoint.getPoint()).getStorageStatus())) {
26                     logger.error("{} 校验{}储位状态异常, 预释放操作,状态应该是{} 实际是{},", request.getUuid(), requestPoint.getPoint(),StorageStatusEnum.OCCUPY.getStatus(),pointDBMap.get(requestPoint.getPoint()).getStorageStatus());
27                     response.setError(new Error(PositionErrorEnum.SYSTEMHANDLEEERROR.getErrorCode() + "", "校验"+requestPoint.getPoint()+"储位状态异常, 预释放操作,状态应该是" + StorageStatusEnum.OCCUPY.getStatus()+ " 实际是" + pointDBMap.get(requestPoint.getPoint()).getStorageStatus()));
28                     return response;
29                 }
30
31             }else if (PositionTaskType.REVOKPRERELEASE.getTaskType().equals(taskType)) { //撤销预释放操作
32                 if (!StorageStatusEnum.PRERELEASEOCCUPY.getStatus().equals(pointDBMap.get(requestPoint.getPoint()).getStorageStatus())) {
33                     logger.error("{} 校验{}储位状态异常, 预释放操作,状态应该是{} 实际是{},", request.getUuid(), requestPoint.getPoint(),StorageStatusEnum.PRERELEASEOCCUPY.getStatus(),pointDBMap.get(requestPoint.getPoint()).getStorageStatus());
34                     response.setError(new Error(PositionErrorEnum.SYSTEMHANDLEEERROR.getErrorCode() + "", "校验"+requestPoint.getPoint()+"储位状态异常, 撤销预释放操作,状态应该是" + StorageStatusEnum.PRERELEASEOCCUPY.getStatus()+ " 实际是" + pointDBMap.get(requestPoint.getPoint()).getStorageStatus()));
35                     return response;
36                 }
37
38             }else if (PositionTaskType.RELEASE.getTaskType().equals(taskType)) { //预释放操作
39                 if (!StorageStatusEnum.PRERELEASEOCCUPY.getStatus().equals(pointDBMap.get(requestPoint.getPoint()).getStorageStatus())) {
40                     logger.error("{} 校验{}储位状态异常, 预释放操作,状态应该是{} 实际是{},", request.getUuid(), requestPoint.getPoint(),StorageStatusEnum.PRERELEASEOCCUPY.getStatus(),pointDBMap.get(requestPoint.getPoint()).getStorageStatus());
41                     response.setError(new Error(PositionErrorEnum.SYSTEMHANDLEEERROR.getErrorCode() + "", "校验"+requestPoint.getPoint()+"储位状态异常, 预释放操作,状态应该是" + StorageStatusEnum.PRERELEASEOCCUPY.getStatus()+ " 实际是" + pointDBMap.get(requestPoint.getPoint()).getStorageStatus()));
42                     return response;
43                 }
44             }
45         }

2.构造更新体代码。同样问题,if-else过多

 1 private QueryPoint getUpdatePoint( BatchPreReleaseStorageLocationRequest request,String operatorName,StorageLocation requestPoint){2         QueryPoint updatePoint = new QueryPoint();3         //条件4         updatePoint.setAreaId(request.getMapAreaId());5         updatePoint.setOrgNo(request.getOrgNo());6         updatePoint.setDistributeNo(request.getDistributeNo());7         updatePoint.setWarehouseNo(request.getWarehouseNo());8         updatePoint.setPositionId(requestPoint.getPoint());9         updatePoint.setUpdateUser(operatorName);
10         updatePoint.setContainerNo(requestPoint.getContainerNo());
11
12         if (PositionTaskType.PREOCCUPY.getTaskType().equals(requestPoint.getStorageStatus())) { //预占操作
13             updatePoint.setStorageStatus(StorageStatusEnum.PREOCCUPY.getStatus());
14             updatePoint.setOldStorageStatus(StorageStatusEnum.INIT.getStatus());
15         }else if (PositionTaskType.RELEASEPREOCCUPY.getTaskType().equals(requestPoint.getStorageStatus())) { //撤销预占操作
16             updatePoint.setStorageStatus(StorageStatusEnum.INIT.getStatus());
17             updatePoint.setOldStorageStatus(StorageStatusEnum.PREOCCUPY.getStatus());
18         }else if (PositionTaskType.OCCUPY.getTaskType().equals(requestPoint.getStorageStatus())) { //占用操作
19             updatePoint.setStorageStatus(StorageStatusEnum.OCCUPY.getStatus());
20             updatePoint.setOldStorageStatus(StorageStatusEnum.PREOCCUPY.getStatus());
21         }else if (PositionTaskType.PRERELEASE.getTaskType().equals(requestPoint.getStorageStatus())) { //预释放操作
22             updatePoint.setStorageStatus(StorageStatusEnum.PRERELEASEOCCUPY.getStatus());
23             updatePoint.setOldStorageStatus(StorageStatusEnum.OCCUPY.getStatus());
24         }else if (PositionTaskType.REVOKPRERELEASE.getTaskType().equals(requestPoint.getStorageStatus())) { //撤销预释放操作
25             updatePoint.setStorageStatus(StorageStatusEnum.OCCUPY.getStatus());
26             updatePoint.setOldStorageStatus(StorageStatusEnum.PRERELEASEOCCUPY.getStatus());
27         }else if (PositionTaskType.RELEASE.getTaskType().equals(requestPoint.getStorageStatus())) { //预释放操作
28             updatePoint.setStorageStatus(StorageStatusEnum.INIT.getStatus());
29             updatePoint.setContainerNo("");
30             updatePoint.setOldStorageStatus(StorageStatusEnum.PRERELEASEOCCUPY.getStatus());
31         }
32         return updatePoint;
33     }

优化后:

1.新增一个状态变更枚举类

public enum PositionTaskTypeStatus {PREOCCUPY(1, "预占用",0,1),RELEASEPREOCCUPY(2, "释放预占用",1,0),OCCUPY(3, "占用",1,10),PRERELEASE(4, "预释放",10,3),REVOKPRERELEASE(5, "撤销预释放",3,10),RELEASE(6, "释放",3,0),;private Integer taskType;private String taskName;private Integer fromStatus;private Integer toStatus;private static Map<Integer, PositionTaskTypeStatus> map = new HashMap<>();static {for (PositionTaskTypeStatus task : PositionTaskTypeStatus.values()) {map.put(task.getTaskType(), task);}}PositionTaskTypeStatus(Integer taskType, String taskName, Integer fromStatus, Integer toStatus) {this.taskType = taskType;this.taskName = taskName;this.fromStatus = fromStatus;this.toStatus = toStatus;}public Integer getTaskType() {return taskType;}public void setTaskType(Integer taskType) {this.taskType = taskType;}public String getTaskName() {return taskName;}public void setTaskName(String taskName) {this.taskName = taskName;}public Integer getFromStatus() {return fromStatus;}public void setFromStatus(Integer fromStatus) {this.fromStatus = fromStatus;}public Integer getToStatus() {return toStatus;}public void setToStatus(Integer toStatus) {this.toStatus = toStatus;}public static Map<Integer, PositionTaskTypeStatus> getMap() {return map;}public static void setMap(Map<Integer, PositionTaskTypeStatus> map) {PositionTaskTypeStatus.map = map;}public static String getTaskNameByTaskType(Integer taskType) {String taskName = "";for (PositionTaskTypeStatus e : PositionTaskTypeStatus.values()) {if (e.taskType.equals(taskType)) {taskName = e.taskName;}}return taskName;}public static boolean contains(Integer taskType){if(null == taskType){return false;}return map.containsKey(taskType)?true:false;}public static PositionTaskTypeStatus getEnumByKey(Integer taskType){return map.get(taskType);}/*** 操作类型、原始值是否可以修改* @param taskType* @param originalValue* @return*/public static boolean verify(Integer taskType,Integer originalValue){if(null==getEnumByKey(taskType)){return false;}if(!getEnumByKey(taskType).getFromStatus().equals(originalValue)){return false;}return true;}

2.更新前校验代码片段。

枚举状态变更类+google的前置检查方法,一行搞定。

//校验状态是否在枚举之内for(StorageLocation requestPoint : request.getPointList()){Preconditions.checkArgument(PositionTaskTypeStatus.contains(requestPoint.getStorageStatus()),"%s操作类型%s不存在",requestPoint.getPoint(),requestPoint.getStorageStatus());}

3.构造更新体代码

 1 private QueryPoint getUpdatePoint( BatchPreReleaseStorageLocationRequest request,StorageLocation requestPoint){2         QueryPoint updatePoint = new QueryPoint();3         updatePoint.setAreaId(request.getMapAreaId());4         updatePoint.setOrgNo(request.getOrgNo());5         updatePoint.setDistributeNo(request.getDistributeNo());6         updatePoint.setWarehouseNo(request.getWarehouseNo());7         updatePoint.setPositionId(requestPoint.getPoint());8         updatePoint.setUpdateUser(request.getOperatorName());9         updatePoint.setContainerNo(requestPoint.getContainerNo());
10         updatePoint.setStorageStatus(PositionTaskTypeStatus.getEnumByKey(requestPoint.getStorageStatus()).getToStatus()); //枚举类,设置更新状态
11         updatePoint.setOldStorageStatus(PositionTaskTypeStatus.getEnumByKey(requestPoint.getStorageStatus()).getFromStatus()); //枚举类 设置原始状态
12         return updatePoint;
13     }

看过后有没有恍然大悟的感觉,看看您代码中是否有这样的场景,赶快优化吧~~

笔者之后遇到的项目,都按照这种思想编码。有的项目业务状态多大20多种,if-else会看的很头疼。

持续优化:

参考: 用Java8 Lambda重构简单工厂模式   https://segmentfault.com/a/1190000021803985ttps://segmentfault.com/a/1190000021641277

if-else深度优化:巧用状态变更枚举类相关推荐

  1. Java状态码枚举类

    前言:当浏览者访问一个网页时,浏览者的浏览器会向网页所在服务器发出请求.当浏览器接收并显示网页前,此网页所在的服务器会返回一个包含HTTP状态码的信息头(server header)用以响应浏览器的请 ...

  2. 举个栗子看如何做MySQL 内核深度优化

    2019独角兽企业重金招聘Python工程师标准>>> 本文由云+社区发表 作者介绍:简怀兵,腾讯云数据库高级工程师,负责腾讯云CDB内核及基础设施建设:先后供职于Thomson R ...

  3. 连麦互动直播 将成直播体验深度优化的必然形式

    视频流媒体文件从电视专网广播到PC公网点播,再到手机移动网络直播的转变,显然已经是2016年不能再热的话题.短短不到一年时间,市场上出现几百家直播APP,内容触及真人秀.赛事.旅游.电商.海淘.教育. ...

  4. 百度APP移动端网络深度优化实践分享(三):移动端弱网优化篇

    本文由百度技术团队"蔡锐"原创发表于"百度App技术"公众号,原题为<百度App网络深度优化系列<三>弱网优化>,感谢原作者的无私分享. ...

  5. mysql40190_MySQL 内核深度优化

    MYSQL数据库适用场景广泛,相较于Oracle.DB2性价比更高,Web网站.日志系统.数据仓库等场景都有MYSQL用武之地,但是也存在对于事务性支持不太好(MySQL 5.5版本开始默认引擎才是I ...

  6. LAMP 架构深度优化记录

    1.Apache worker/prefwork模式说明 在linux中,我们可以用httpd-l 查看安装的模块是prefork模式还是worker模式 [root@LAMP ~]# /applic ...

  7. 网络推广外包浅析当下网站优化处于健康状态有利于网络推广外包

    在当前的网站优化市场中我国仍处于积极发展阶段,尽管网站优化监管机制并不完善,仍有优化水平参差不齐的公司鱼目混珠,通过一些作弊方式完成企业网站整体排名优化获取网站权重,采用作弊行为是对网站未来优化运营状 ...

  8. JDBC批量Insert深度优化(有事务)

    JDBC批量Insert深度优化(有事务) 环境: MySQL 5.1 RedHat Linux AS 5 JavaSE 1.5 DbConnectionBroker 微型数据库连接池 测试的方案: ...

  9. 百度App网络深度优化系列(一):DNS优化

    一.前言 网络优化是客户端几大技术方向中公认的一个深度领域,所以百度App给大家带来网络深度优化系列文章,其中包含系列<一>DNS优化,系列<二>连接优化,系列<三> ...

最新文章

  1. html5绘制小鱼,HTML5 Canvas 深海游弋的鱼群
  2. anaconda安装yolov3_YOLOv3_图像识别_神经网络_人工智能
  3. Hadoop_23_MapReduce倒排索引实现
  4. windows 技术篇 - 启动项里没有的程序设置为开机启动方法
  5. 是vans_终于在中国发力的 Vans
  6. ADTF(Assist Automotive Data and Time-Triggered Framework)介绍
  7. HTTP/2 in GO(一)
  8. BaiduAI-GNN:2.2图学习初印象
  9. Leetcode每日一题:287.find-the-duplicate-number(寻找重复数)
  10. 测试PF_RING DNA驱动
  11. centos8终端fish安装
  12. 锅炉给水泵flash_锅炉给水泵故障实例
  13. axios下载流文件报错文件已损坏
  14. 为什么 zookeeper 节点数是奇数
  15. 托勒密定理 圆的内接四边形
  16. linux命令---dstat
  17. 痞子衡嵌入式:恩智浦i.MX RTxxx系列MCU启动那些事(7)- 从SD/eMMC启动
  18. 毕业论文答辩PPT制作技巧_01
  19. 使用aspose.word向word中插入书签
  20. java浏览器刷新页面_使用js刷新浏览器页面

热门文章

  1. 风云防火墙导致无法上网的问题解决(无法获取正确的网关MAC)
  2. 苹果发布iOS 11.2新测试版:只为iPhone X
  3. 海龟交易法则要点和应用
  4. 彻底解决中文乱码,然后升级后英文改为中文
  5. SNS平台ConcourseConnect
  6. Google 的怪异域名大全
  7. 3d文本样式cssjs特效代码
  8. App性能优化(一)—— 启动优化,冷启动,热启动,温启动
  9. 为什么河文档是黑人,而小河看起来却是个白人
  10. vue项目加入百度统计代码-统计网站浏览数据