Click here to Skip to main content
15,900,533 members
Articles / All Topics

Robert’s Rules of Coders #9: Eliminate Deep Nesting by Using Switch Statements and Functions

Rate me:
Please Sign up or sign in to vote.
4.64/5 (6 votes)
15 Feb 2016CPOL3 min read 13.8K   1   12
Eliminate deep nesting by using switch statements and functions

The ‘If’ statement is one of the fundamental coding constructs of almost every programming language. Along with the ‘If’ statement, most languages also support ‘else’ conditions and the ability to nest ‘If’ statements. But this simple construct can also become one of the biggest contributors to code that is difficult to understand and modify. This often happens when ‘If’ statements get nested within ‘If’ statements; but there are two simple techniques you can use to reduce this complexity, ‘Switch’ statements and functions.

Switch statements offer these benefits to most developers:

  • They are easier to read, and thus
  • They are easier to understand, and thus
  • They are easier to maintain.
  • They are also easier to debug.
  • In many languages, they also can be compiled to execute a little more swiftly than nested ‘If’ statements

Here is an example of an ‘If’ statement than can be improved by converting it to a ‘Switch’ statement:

Quote:
  • If aValue = 6 then
    • Stars = stars + 1
  • Else
    • if aValue = 7
      • Stars = stars + 3
    • Else
      • if aValue = 8
        • Stars = stars + 5
      • Else
        • if aValue = 9
          • Stars = stars + 9
        • End if
      • End if
    • End if
  • End if

Here is the same logic from above, using a ‘Switch’ statement:

Quote:
  • Switch aValue
    • Case 6:
      • Stars = Stars + 1
    • Case 7:
      • Stars = Stars + 3
    • Case 8:
      • Stars = Stars + 5
    • Case 9:
      • Stars = Stars + 9

I suspect that you will agree that it is easier to understand the code in the switch statement than the code in the nested ‘If’s. Another technique to eliminate nested ‘If’ statements is to move some of the code into separate functions. Although the hierarchy of ‘If’ statements may remain the same from the computer’s point of view, to most humans, it becomes much easier to manage.

Quote:
  • If input data is valid
    • If filename is valid
      • Create File
      • If file was created
        • Log “Success”
        • Return “Success”
      • Else
        • If error due to size
          • Log “Failure”
          • Return “Could not create file because it is too large.”
        • If error due to permission
          • Log “Failure”
          • Return “Could not create file because you do not have permissions.”
        • Else
          • Log “Failure”
          • Return “Unable to create the file. Reason unknown.”
        • End if
      • End if
    • Else
      • Log “Failure”
      • Return “Your file name is invalid.”
    • End if
  • Else
    • Log “Failure”
    • Return “The file input is invalid.”
  • End if

Here is the same logic from above, using functions:

Quote:
  • String response = “”
  • Response = IsInputValid(myinput)
  • If (response= “”)
    • Return response
  • Response = IsFileNameValid(myfile)
  • If (response= “”)
    • Return response
  • return FileCreationResultMessage(myfile, myinput)

The functions called from the code above:

Quote:
  • Function string IsInputValid(string input)
    • If input is not valid
      • Log “Failure”
      • Return “The file input is invalid.”
    • Else
      • Return “”
    • End if
  • End Function
  •  
  • Function string IsFileNameValid(string input)
    • If input is not valid
      • Log “Failure”
      • Return “Your file name is invalid.”
    • Else
      • Return “”
    • End if
  • End Function
  •  
  • Function string FileCreationResultMessage(string file, string input)
    • Create File
      • If file was created
        • Log “Success”
        • Return “Success”
      • Else
        • If error due to size
          • Log “Failure”
          • Return “Could not create file because it is too large.”
        • If error due to permission
          • Log “Failure”
          • Return “Could not create file because you do not have permissions.”
        • Else
          • Log “Failure”
          • Return “Unable to create the file. Reason unknown.”
        • End if
      • End if
  • End Function

As with any of Robert’s Rules of Coding, you don’t need to adhere to them all of the time and there are cases where it is better not to. But most programmers should follow the rules most of the time. I hope you agree.

Go to Robert’s Rules of Coders for more.

License

This article, along with any associated source code and files, is licensed under The Code Project Open License (CPOL)


Written By
Software Developer (Senior) Kraft Software LLC
United States United States
Rob Kraft is an independent software developer for Kraft Software LLC. He has been a software developer since the mid 80s and has a Master's Degree in Project Management. Rob lives near Kansas City, Missouri.

Comments and Discussions

 
QuestionOOP over Switches Pin
Paulo Zemek14-Mar-16 9:16
Paulo Zemek14-Mar-16 9:16 
AnswerRe: OOP over Switches Pin
Rob Kraft20-Mar-16 3:33
professionalRob Kraft20-Mar-16 3:33 
Suggestionbreak? Pin
SteveHolle17-Feb-16 5:10
SteveHolle17-Feb-16 5:10 
GeneralRe: break? Pin
Rob Kraft17-Feb-16 6:46
professionalRob Kraft17-Feb-16 6:46 
QuestionAnother way ... Pin
mbb0116-Feb-16 22:09
mbb0116-Feb-16 22:09 
Another way of making nested constructs (it's not just if statements that can become nested) simpler is to use guard filters/conditions.

One pattern I use often goes a bit like this:

error = false

if not error then
    do action 1

    if action 1 failed then
      error = true
    end if

end if

if not error then

   error = functionForAction2()
  
end if

if not error then
  do action 3

  if action 3 failed
    error = true
  end if
end if

.....

return error


This pattern allows logging to be included and extra steps to be inserted at any point in the sequence, or the sequences to be easily re-arranged. If necessary multiple guard conditions may be used.


Also, some languages don't always support switch statements and in that case a sequence of nested if-then-else statements is acceptable. In that scenario my layout would alter slightly to align the if-statements vertically which would make it quite clear it is really a switch statement that has been implemented.
AnswerRe: Another way ... Pin
Rob Kraft17-Feb-16 6:50
professionalRob Kraft17-Feb-16 6:50 
GeneralRe: Another way ... Pin
mbb0117-Feb-16 12:19
mbb0117-Feb-16 12:19 
SuggestionFail fast and early on If statements Pin
Slacker00715-Feb-16 11:51
professionalSlacker00715-Feb-16 11:51 
SuggestionWhat about a little formating? Pin
Carlos190714-Feb-16 22:23
professionalCarlos190714-Feb-16 22:23 
GeneralRe: What about a little formating? Pin
Rob Kraft15-Feb-16 2:03
professionalRob Kraft15-Feb-16 2:03 
GeneralRe: What about a little formating? Pin
Carlos190715-Feb-16 2:21
professionalCarlos190715-Feb-16 2:21 
GeneralRe: What about a little formating? Pin
Rob Kraft15-Feb-16 2:49
professionalRob Kraft15-Feb-16 2:49 

General General    News News    Suggestion Suggestion    Question Question    Bug Bug    Answer Answer    Joke Joke    Praise Praise    Rant Rant    Admin Admin   

Use Ctrl+Left/Right to switch messages, Ctrl+Up/Down to switch threads, Ctrl+Shift+Left/Right to switch pages.