Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How would you refactor this conditional to use polymorphism?

I just finished watching the Google clean code video on YouTube (see link, first article) about removing if statements from your code and using polymorphism instead.

After watching the video I had a look at some code that I was writing before watching the video and noticed some places where I could use this method, mainly places where the same kind of logic was implemented many times. So a example:

I have some code like this.

public int Number
{
    get
    {
        string returnValue;
        if (this.internalTableNumber == null)
             returnValue = this.RunTableInfoCommand(internalTableName,
                                                    TableInfoEnum.TAB_INFO_NUM);
        else
             returnValue = this.RunTableInfoCommand(internalTableNumber.Value,
                                                    TableInfoEnum.TAB_INFO_NUM);
        return Convert.ToInt32(returnValue);
    }
}

What RunTableInfoCommand does isn't really important,but the main thing is that I have many properties with exactly the same if statments the only thing that changes is the TableInfoEnum.

I was wondering if someone could help me refactor this so that it still does the same thing but without any if statements?

like image 222
Nathan W Avatar asked Dec 11 '08 03:12

Nathan W


People also ask

What is Replace Conditional with polymorphism refactoring?

In them, create a shared method and move code from the corresponding branch of the conditional to it. Then replace the conditional with the relevant method call. The result is that the proper implementation will be attained via polymorphism depending on the object class.

Which Java class programming technique shows the use of polymorphism?

Since both the definition are different in those classes, calc_grade() will work in different way for same input from different objects. Hence it shows polymorphism.

What do you mean by polymorphism in Java?

Polymorphism means "many forms", and it occurs when we have many classes that are related to each other by inheritance. Like we specified in the previous chapter; Inheritance lets us inherit attributes and methods from another class. Polymorphism uses those methods to perform different tasks.


1 Answers

Just a cautionary note here after seeing some of these (technically correct) reponses, just getting rid of an If statement should not be your sole aim, the aim should be to make your code extensible, maintainable and simple, if that means getting rid of an if statement, great, but it shouldn't be an aim in an of itself.

In the code sample you have given, and without knowing more about your app, and assuming you are not going to extend much past testing for a null value, I think an If (or perhaps even a ternary) is the more maintainable solution to be perfectly frank.

like image 94
Tim Jarvis Avatar answered Oct 20 '22 17:10

Tim Jarvis