I have the following use case , lot of code which was tightly coupled on a concrete type (say Concrete1). Later figured out the concrete type needs to be changed, so defined an interface . E.g
Class ABC { virtual int foo() = 0; virtual int getType() = 0; } class Concrete1 : public ABC { int foo() { ... } int getType() { return 1; } } class Concrete2 : public ABC { int foo() { ... } int getType() { return 2; } }
A static factory pattern was used for creation of the objects. So all places where the object new Concrete1 was created is replaced with ABCFactory::createType().
Now there are a lot of places in code where I need to check if the object returned by createType is whether Concrete1 or Concrete2 and accordingly do the relevant logic (So a lot of if else in the code 🙁 ).
I want to avoid a lot of if else in the code as part of this change. Any suggestions?
The thing which bothers me a lot is
if (abc.getType() == 1) { ... } else if (abc.getType() ==2) { ... }
the entire point of using interfaces is so that you can use polymorphism which means you should never have to check what type an instance is. doing so is a very big code smell (see Fowlers Refacotring). move the conditional logic to the concrete classes and add te function that will handle it to the interface
EDIT (Adding code example since initial post was done from cell phone):
You are trying to do:
Instead, try: