Java – refactoring a simple populated long method
•
Java
I'm refactoring a method with more than 500 lines (don't ask me why) @ h_ 403_ 7@
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
}
Solution
I came up with a simple idea to divide a method by "finding meaningful small tasks", so here are some tips: @ h_ 403_ 7@
processCollection(collection) {
// startup code
for (Item i: collection)
processCollectionItem(i,...other args...);
// final code
}
// 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]);
}
The content of this article comes from the network collection of netizens. It is used as a learning reference. The copyright belongs to the original author.
THE END
二维码
