I am currently trying to restructure my program to be more OO and to better implement known patterns etc.
I have quite many nested IF-statements and want to get rid of them. How can I go about this? My first approach was to get it done with exceptions, so e.g.
public static Boolean MyMethod(String param) {
if (param == null)
throw new NullReferenceException("param may not be null");
if (param.Equals("none") || param.Equals("0") || param.Equals("zero"))
throw new ArgumentNullException("param may not be zero");
// Do some stuff with param
// This is not executed if param is null, as the program stops a soon
// as one of the above exceptions is thrown
}
The method is used in the main class of the application, e.g.
static void Main() {
try {
Boolean test = MyClass.MyMethod(null); // Will throw an exception
} catch (Exception ex) {
MessageBox.Show(ex.Message, "Error");
}
I think this is quite nice, as it prevents the nested statements and nearly all of the methods actions are nicely arranged on one level.
As with IF-statements, the method would look like this
public Boolean MyMethod(String param) {
if (param != null) {
if (!param.Equals("none") && !param.Equals("0") && !param.Equals("zero")) {
// Do some stuff with param
} else {
MessageBox.Show("param may not be zero", "Error");
} else {
MessageBox.Show("param may not be null", "Error");
}
}
Which I find very, very ugly and hard to maintain.
Now, the question is; is this approach good? I know, that might be subjective, but how do you overcome nested IFs (1 or 2 levels are not that bad, but it gets worse after that…)
It really depends on their purpose. In your first sample, the if statements serves the purpose of enforcing a contract, making sure that the input to the method meets certain requirements. In those cases, my own code tend to look pretty much like your code.
In the case of using the if blocks to control the flow of a method (rather than enforcing a contract), it can sometimes be a bit harder. Sometimes I come across code like the following (extremely simplified) example:
In this case, it seems as if the method has several responsibilities, so in this case I would probably choose to split it into several methods:
This makes each method much simpler with less nested code, and may also increase the readability, if the methods are given good names.