Reputation:
I have a for loop which is used in many classes but the task inside the for loops are different. For example Class Foo uses following
for(Pojoclass a : listofPojo){
if(a.getX().equals(b)){
methos(a.getX());
}
}
and class Bar uses following:
for(Pojoclass a : listofpojo){
if(a.getX().equals(x)){
methos(a.getX());
} // or some other logic
}
I find many such loops in my project which iterate on same object but do different behavior. How do I re-factor this?
EDIT : I am not dealing with string, I am dealing with POJO classes
Upvotes: 3
Views: 451
Reputation: 10700
You could use Google Guava and it's filter
and transform
methods. First filter out elements that don't match the predicate and then apply a function to the remaining one's. It's a little bit more code but gives you much flexibility.
Predicate<Pojoclass> predicate = new Predicate<Pojoclass>() {
public boolean apply(Pojoclass a) {
return a.getX().equals(b);
}
};
Function<Pojoclass, Void> function = new Function<Pojoclass, Void>() {
public Void apply(Pojoclass p) {
methos(p.getX());
return null;
}
};
Collections2.transform(Collections2.filter(listofPojo, predicate), function).toArray();
(Predicates and functions should be refactored nicely for reusage.)
Upvotes: 0
Reputation: 21409
You actually have the solution :) Whenever I hear 'different behaviour' I think of the Strategy pattern straight away! I suggest you do the following:
public void forLoopReplacement(IActionStrategy strategy, IList<Pojoclass> projo){
for(Pojoclass a : listofPojo){
strategy.doActionOn(a);
}
}
public interface IActionStrategy {
public void doAction(Pojoclass param);
}
Any new behavior you define in your application can be encapsulated in a class that implements IActionStrategy
.
I hope this helps. Regards,
Upvotes: 2
Reputation: 28316
You don't refactor this kind of thing - it's already nice and tidy.
Refactoring is designed to replace redundant (duplicated) code that is the same but simply takes different arguments. In your case, the code is different, so you can't (and shouldn't) refactor it.
For example, if you were repeatedly turning byte arrays into hexadecimal strings, you should make a function instead of having the same code repeated everywhere.
Upvotes: 3