我现在已经在 3 个不同的场合遇到过这种情况。大多数时候重构一些代码。
假设我有:
//code block A
List<Bar> foo = doSomething(inputParams);
//code block B
现在,我需要重构
代码,以便我想使用doSomething()
方法的过程来做其他事情
。比方说,也创建一个 map (Bar.id -> Bar.name)。
有没有一种优雅的方法可以在不将可变映射传递给 doSomething() 并且不将代码复制到另一个 doSomethingDifferent()
的情况下执行此操作?
虚拟实现:
doSomething(){
List<Bar> ret = new ArrayList<Bar>();
while(//condition){
ret.add(new Bar());
}
returrn ret;
}
doSomethingDifferently(){
Map<Integer, String> ret = new HashMap<Integer, String>();
while(//condition){
Bar b = new Bar()
ret.put(b.getId(),b.getName());
}
returrn ret;
}
总结:
有没有比下面可能的解决方案更好的方法?
解决方案一:(重复代码)
List<Bar> foo = doSomething(inputParams);
Map<Integer,String> foobar = doSomethingDifferent(inputParams); //Very similar to doSomething
解决方案 2:(难以阅读)
Map<Integer,String> foobar = new HashMap<Integer,String>();
List<Bar> foo = doSomething(inputParams, foobar); //mutate the map
最佳答案
你返回不同的数据结构..
List<Bar> foo = doSomething(inputParams);
Map<Integer,String> foobar = doSomethingDifferent(inputParams);
你确定他们做类似的事情吗?如果是这样,您可以提取公共(public)部分或更改它们以返回相同的类型,然后很容易看出您可以做什么来避免重复代码。
关于java - 重构时充分利用现有方法,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/18081232/