5
I have a question about how to replace IF with polymorphism.
I will give the following example:
Let’s say I have the classes ExecucaoIndividual
and ExecucaoGeral
.
For this I created an interface to use the standard Strategy that has remained so:
interface IExecutor {
void Executar();
}
class ExecucaoIndividual : IExecutor {
public void Executar() {
//bla bla bla
}
}
class ExecucaoGeral : IExecutor {
public void Executar() {
//bla bla bla
}
}
Until then beauty, but in the base class where I will check which class I should call (individual or general), which would be the best approach not to have to be using:
IExecutor execucao;
if(determinadaCondicao)
execucao = new ExecucaoIndividual();
else
execucao = new ExecucaoFinal();
execucao.Executar();
I’ve seen some Factories
, Maps
, etc, but nothing that would take away my doubt. Someone can give me a light?
What is the problem with the approach you are currently using?
– PauloHDSousa
Man, I imagine you have nothing to do, by the example you gave, will have to continue with the conditional, to know which class the object should be instance...
– Felipe Avelar
I wonder if there’s any better approach to doing this :)
– Kevin
I don’t think so. It depends a lot on the code. The answers, I think, would be opinionated.
– Leonel Sanches da Silva
BTW, not always ifs are bad: http://answall.com/a/4745/1745
– hugomg
If you have many Executioner and are used in several classes, you can write something like a Factory. You pass the condition and receive the Executor. You will have the if’s same but only in one place.
– ramaral