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...)
While Excel will allow you to nest up to 64 different IF functions, it's not at all advisable to do so. Why? Multiple IF statements require a great deal of thought to build correctly and make sure that their logic can calculate correctly through each condition all the way to the end.
Nested if statement, use "break" to break out of if statment only.
One way i can think is to use variable to store the x, y, z etc and then use the variable inside the if statement to check the condition. for (i = 0; i < N; i++) { a = x; b = y; ... if(a & b != 0) { ... ... // ..... } }
Your problem is known as the arrowhead anti-pattern.
There are pragmatic approaches, such as the Guard statements you've shown in your sample, to whole design patterns, avoiding if (and else) all together...
Lots of resources on how to solve them:
http://www.codinghorror.com/blog/2006/01/flattening-arrow-code.html
http://www.lostechies.com/blogs/chrismissal/archive/2009/05/27/anti-patterns-and-worst-practices-the-arrowhead-anti-pattern.aspx
http://elegantcode.com/2009/08/14/observations-on-the-if-statement/
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