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
You actually have the solution 🙂 Whenever I hear ‘different behaviour‘ I think of the Strategy pattern straight away!
I suggest you do the following:
Any new behavior you define in your application can be encapsulated in a class that implements
IActionStrategy.I hope this helps.
Regards,