Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How can Polymorphism replace an if-else statement inside of a loop?

How can polymorphism replace an if-else statement or Switch inside of a loop? In particular can it always replace an if-else? Most of the if-thens I use inside of loops are arithmetic comparisons. This question is spawned from this question.

int x;
int y;
int z;

while (x > y)
{
     if (x < z)
     {
         x = z;
     }
}

How would this work with polymorphism?
NOTE: I wrote this in Java but am interested in this for any OOL.

like image 789
WolfmanDragon Avatar asked Feb 06 '09 08:02

WolfmanDragon


People also ask

Can you put if else statement inside the loop?

You can nest If statements inside For Loops. For example you can loop through a list to check if the elements meet certain conditions. You can also have a For Loop inside another For loop.


3 Answers

Polymorphism usually replaces switch statements when each case corresponds to a different type. So instead of having:

public class Operator
{
    string operation;

    public int Execute(int x, int y)
    {
         switch(operation)
         {
             case "Add":
                 return x + y;
             case "Subtract":
                 return x - y;
             case "Multiply":
                 return x * y;
             case "Divide":
                 return x / y;
             default:
                 throw new InvalidOperationException("Unsupported operation");
         }
    }
}

you'd have:

public abstract class Operator
{
    public abstract int Execute(int x, int y);
}

public class Add : Operator
{
    public override int Execute(int x, int y)
    {
        return x + y;
    }
}

// etc

However, for the comparison type of decision you provided, polymorphism really doesn't help.

like image 133
Jon Skeet Avatar answered Oct 16 '22 09:10

Jon Skeet


Polymorphism is not really applicable in the example you provided.

See this SO answer.

like image 42
Mitch Wheat Avatar answered Oct 16 '22 10:10

Mitch Wheat


Polymorphism can only replace if tests when the if test is basically dispatchi g to a variety of methods depending on the "type" of an object. Eg if object is type X invoke foo if it's a Y invoke bar and so. In this contrived example one would define an interface DoSonething with a method bad(). Both X and Y would implement Baz and have their respective baz() invoke foo() for X and bar() for Y. This simply calling baz() would eliminate the need for a if test.

like image 40
mP. Avatar answered Oct 16 '22 10:10

mP.