IFs and Object Orientation - C #

5

I have a question about how to replace IF with polymorphism.

I'll give you the following example:

Let's say I have the ExecucaoIndividual and ExecucaoGeral classes.

For this I created an interface to use the strategy pattern that looks like this:

interface IExecutor {
    void Executar();
} 

class ExecucaoIndividual : IExecutor {

    public void Executar() {
       //bla bla bla
    }
}

class ExecucaoGeral : IExecutor {

    public void Executar() {
        //bla bla bla
    }
}

So far beauty, but in the base class where I'm going to check which class I should call (individual or general), what would be the best approach for not having to use it:

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. Can someone give me a light?

    
asked by anonymous 26.06.2015 / 17:28

3 answers

3

Polymorphism does not apply here.

Polymorphism happens in variables, in instances.

For example:  I have class gato , and class cachorro , both derived from animal . The animal class has a cor property and a alimentar() method.

Since gato and cachorro are animals, I can call cor or alimentar() in a cat.

Now, when I create a new instance, I can not create without knowing the type. I can not even create a cachorro as if it were a animal .

In your case, if is at the other "tip" of logic. It is it that determines the type of class. And this can not be done polymorphically.

  • When you create a new instance, you need to define the type.

  • When you use the object, you can use it as if it were another type, thanks to polymorphism.

Factories and others will serve to centralize this decision of which type to instantiate, but in the end, there will always be a if or equivalent structure.

    
26.06.2015 / 19:42
2

In this case use a Factory. A class with a static method that returns an IExecutor. Maybe it's something like

public static IExecutor GetBestExecutor(Condicao _condicao)
{
   switch(_condicao) 
   {
       case Condicao.Individual:
         return new ExecucaoIndividual();
         break;
       default
         return new ExecucaoGeral();
         break; 
   }
}
    
26.06.2015 / 18:46
2

You can use a Factory like this:

class ExecucaoFactory {

    public void IExecutor Criar(boolean condicao) {
        return condicao ? new ExecucaoIndividual() : new ExecucaoFinal();
    }
}
ExecucaoFactory factory = new ExecucaoFactory();
factory.Criar(algumaCondicao).Executar();

In the background you're putting if (or the equivalent ternary operator) inside the factory, where its complexity will be encapsulated and concentrated in only one place, simplifying possible future changes that may be needed.

    
26.06.2015 / 22:15