Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
673 views
in Technique[技术] by (71.8m points)

language agnostic - 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.

See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Answer

0 votes
by (71.8m points)

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.


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

2.1m questions

2.1m answers

60 comments

57.0k users

...