Note that there are some explanatory texts on larger screens.

plurals
  1. POHow to avoid multiple nested IFs
    primarykey
    data
    text
    <p>I am currently trying to restructure my program to be more OO and to better implement known patterns etc.</p> <p>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.</p> <pre><code>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 } </code></pre> <p>The method is used in the main class of the application, e.g.</p> <pre><code>static void Main() { try { Boolean test = MyClass.MyMethod(null); // Will throw an exception } catch (Exception ex) { MessageBox.Show(ex.Message, "Error"); } </code></pre> <p>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.</p> <p>As with IF-statements, the method would look like this</p> <pre><code>public Boolean MyMethod(String param) { if (param != null) { if (!param.Equals("none") &amp;&amp; !param.Equals("0") &amp;&amp; !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"); } } </code></pre> <p>Which I find very, very ugly and hard to maintain.</p> <p>Now, the question is; is this approach <em>good</em>? 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...)</p>
    singulars
    1. This table or related slice is empty.
    plurals
    1. This table or related slice is empty.
    1. This table or related slice is empty.
 

Querying!

 
Guidance

SQuiL has stopped working due to an internal error.

If you are curious you may find further information in the browser console, which is accessible through the devtools (F12).

Reload