我正在重构一个超过 500 行的方法(不要问我为什么)
该方法主要是从数据库中查询 map 列表,并对列表中的每个 map 进行一些计算,并将该计算的值添加到 map 中。然而,有太多的计算和完成,代码已经超过 500 行!
这是一个示例预览:
public List<Hashmap> getProductData(...) {
List<Hashmap> products = productsDao.getProductData(...);
for (Product product: products) {
product.put("Volume",new BigDecimanl(product.get("Height")*
product.get("Width")*product.get("Length"));
//over 10 more lines like the one above
if (some condition here) {
//20 lines worth of product.put(..,..)
} else {
//20 lines worth of product.put(..,..)
}
//3 more if-else statements like the one above
try {
product.put(..,..)
} catch (Exception e) {
product.put("",..)
}
//over 8 more try-catches of the form above
}
关于如何重构这个的任何想法?
最佳答案
我想到的一个划分方法的简单想法是“找到有意义的小任务”,所以这里有一些提示:
为item级别做一个方法
processCollection(collection) {
// startup code
for (Item i: collection)
processCollectionItem(i, ...other args...);
// final code
}
尝试用自己的方法切割每个注释 block
// does a
instr 1
instr 2
instr 3
instr 4
// does b
instr 5
instr 6
instr 7
instr 8
转换为
a(...);
b(...);
尝试查看一些行是否是某种一般模式的具体表达
map.put(a[0], b[0]);
map.put(a[1], b[1]);
...
转换为
putKeysAndValues(a, b);
与
putKeysAndValues(a, b) {
for (int i=0; i<a.length; i++)
map.put(a[i], b[i]);
}
关于java - 重构一个简单填充的长方法,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/2956679/