代码重构
去掉if else
Optional.ofNullable(“xxx”).orElse(“yyy”);
String temp=xxx;
if(temp==null){
temp="bbb"
}
这种写法可以改写成 Optional.ofNullable(temp).orElse("bbb");
通过定义一个枚举消除
定义一个枚举 然后遍历这个枚举,通过for来缩if else
工厂|接口|实现类
if(xxx){#xxx 抽成Factory的条件
//内容1 #将内容抽成Interface 然后 xxx内容1xxx implments Interface
} else if(xxx){
//内容2 #将内容抽成Interface 然后 xxx内容2xxx implments Interface
}
改写成
Xxxx.java
private Interface xxxintefacexxx;
xxxintefacexxx = InterfaceFactory.createXxxInterface();
xxxintefacexxx.deal();
if(condition)改写成Factory
public xxxintefacexxx InterfaceFactory.createXxxInterface(){
if(xxx){
xxxintefacexxx = new Impl();
}else if(xxx){
xxxintefacexxx = new Impl();
}
return xxxintefacexxx
}
//变种的写法
static Map<String, Operation> operationMap = new HashMap<>();
static {
operationMap.put("add", new Addition());
operationMap.put("divide", new Division());
operationMap.put("multiply", new Multiplication());
operationMap.put("subtract", new Subtraction());
operationMap.put("modulo", new Modulo());
}
public xxxintefacexxx InterfaceFactory.createXxxInterface(type){
return operationMap.get(type);
}
方法链的调用
增加内部类对Model类的处理
public class Book {
private String name;
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
//定义一个内部类来处理Book的这个Model类
public static class BookVistor {
private AtomicBoolean forEachedOnce = new AtomicBoolean(false);
private List<Book> bookList;
private String param1;//处理后的结果
private String param2;//处理后的结果
public BookVistor(List<Book> bookList) {
this.bookList = bookList;
}
public String getParam1() {
foreachOnce();
return param1;
}
public String getParam2() {
return param2;
}
public void foreachOnce() {
if (forEachedOnce.get()) {
return;
}
for (Book book : bookList) {
param1 = "xxx";
param2 = "bbb";
}
forEachedOnce.set(true);
}
}
}
Feature Envy(依恋情结)
如果一个函数为了计算某个值,需要用到几个类的数据,就把函数移到最多被此函数使用的数据的类中
某个类太大
可以考虑移到 父类中abstract 或 移到 子类中去