I have a method like this:
public void foo(String str){
do.something();
do.anotherthing();
do.somethingelse();
if(str.compareTo("choiceA")==0){
do.somethingforA();
}
else if(str.compareTo("choiceB")==0){
doanother.somethingforB();
doelse();
}
else if(str.compareTo("choiceC")==0){
dosomeother.somethingforC();
doblahblah();
writeblabla();
}
}
i want to design the code as defining different classes or methods for A, B and C.
but there is many lines (first three lines of method) that A, B and C sharing.
if i generate different method for A, B and C, i will have to change every method when i have to maintain in the future, thus i wont be able to get the help of designing code with a design pattern approach.
what do you advise?
Thanks for any idea.
What you looking for is
polymorphism.There are two “proper” object-oriented ways to do what you want. My personal preference goes to the second one, I’ll tell you why.
Inheritance: Have a superclass (maybe abstract) in which your method does all the common stuff (
do.something();,do.anotherthing();anddo.somethingelse();. Then this method should call anotherabstractmethod. You then define three subclasses of that class, each for one of the different choices (“choice A”, “choice B” and “choice C”). Each of your subclass implement the method in a different way, and does what you need to do.Composition: Instead of having subclasses, have an interface injected into the object that contains method
foo. This interfaces then has three different implementations, one for “choice A”, one for “choice B” and one for “choice C”.Personally I prefer composition over inheritance, because it usually produces a code that is more readable, less complicated, less buggy and a lot more testable (if you use an interface as suggested, then you can mock it in your unit-tests of the main class). It also ensures separation of concerns.