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?
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.
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.
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.
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.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With