How to avoid multiple nested IFs

Viewed 23055

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

6 Answers
Related