Java中如何消除大量的if else (意面代码)
2018-03-04 12:18
681 查看
参考:
减少该死的 if else 嵌套
java如何消除繁琐的if else 语句?
如何无痛降低 if else 面条代码复杂度
用设计模式来代替臃肿的ifelse层层判断
你还在用if else吗?
如这段读取Excel单元格的代码,看着都烦
改造后
点击查看Github上的完整源码
- 正如所看到的, 需要新建一堆的处理类, 虽然新增了很多类, 但是职责很明确, 基本符合
减少该死的 if else 嵌套
java如何消除繁琐的if else 语句?
如何无痛降低 if else 面条代码复杂度
用设计模式来代替臃肿的ifelse层层判断
你还在用if else吗?
如这段读取Excel单元格的代码,看着都烦
try { for (int j = mainConfig.getContentStartNum(); j <= rowNum; j++) { row = sheet.getRow(j); T obj = target.newInstance(); for (int i = 0; i < colNum; i++) { Field colField = ExcelUtil.getOneByTitle(metaList, titleList[i]); colField.setAccessible(true); String fieldType = colField.getType().getSimpleName(); HSSFCell cell = row.getCell(i); int cellType = cell.getCellType(); System.out.println(colField.getName()+"|"+fieldType+" | "+cellType); if(HSSFCell.CELL_TYPE_STRING == cellType){ if("Date".equals(fieldType)){ colField.set(obj, DateUtil.parse(cell.getStringCellValue())); }else { colField.set(obj, cell.getStringCellValue()); } }else if(HSSFCell.CELL_TYPE_BLANK == cellType){ System.out.println("字段"+colField.getName()); if("Boolean".equals(fieldType)){ colField.set(obj, cell.getBooleanCellValue()); }else{ colField.set(obj, ""); } }else if(HSSFCell.CELL_TYPE_NUMERIC == cellType){ if("Integer".equals(fieldType) || "int".equals(fieldType)){ colField.set(obj, (int)cell.getNumericCellValue()); }else { colField.set(obj, cell.getNumericCellValue()); } }else if(HSSFCell.CELL_TYPE_BOOLEAN == cellType){ colField.set(obj, cell.getBooleanCellValue()); } } result.add(obj); } } catch (InstantiationException | IllegalAccessException | ParseException e) { e.printStackTrace(); }
改造后
private static Map<String, LoadCellValue> handlerMap = new HashMap<>(7); // 字典结合策略模式简化代码 static{ handlerMap.put("String", new StringHandler()); handlerMap.put("Date", new DateHandler()); handlerMap.put("Boolean", new BooleanHandler()); handlerMap.put("Long", new LongHandler()); handlerMap.put("Integer", new IntegerHandler()); handlerMap.put("Double", new DoubleHandler()); handlerMap.put("Float", new FloatHandler()); } HSSFCell cell = handlerMap.get(temp.getClass().getSimpleName()).loadValue(row, index, temp);
点击查看Github上的完整源码
- 正如所看到的, 需要新建一堆的处理类, 虽然新增了很多类, 但是职责很明确, 基本符合
对修改关闭对扩展开放的原则
相关文章推荐
- 代码重构----使用java有限状态机来消除太多的if else判断
- 代码重构----使用java有限状态机来消除太多的if else判断
- 代码重构----使用java有限状态机来消除太多的if else判断
- 【转】Java策略消除if else
- 【第1076期】 如何无痛降低 if else 面条代码复杂度
- Java编程细节重构之为什么if-else不是好代码详析
- 6个实例详解如何把if-else代码重构成高质量代码
- 代码中如何避免过多的if else
- 代码中如何避免过多的if else
- java开发C语言编译器:消除冗余语句和把ifelse控制语句编译成字节码
- 使用Command与Factory模式消除业务代码中的if,else语句
- Java技术_Java千百问(0017)_if else如何使用
- 如何在代码中减少if else语句的使用
- Java编程细节-重构-为什么 if-else 不是好代码
- 如何无痛降低 if else 面条代码复杂度
- JAVA代码 IF else语句
- 如何从java代码中访问web.xml 中的初始化参数
- 姚博文 如何看懂Java混淆后的反编译代码
- 如何跟踪Java代码的执行
- 如何快速理解其他人写的Java代码