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?
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.