If Ok

AntiPattern Name: If Ok

Context: Almost every language that requires error handling code.

Problem: Error handling can obfuscate business logic and make code much harder to maintain. People think that because error handling is a good thing, that ALL error handling code is good. In reality, only 'good' error handling code is good.

The Fallacy: "Statements ABC should only execute if everything is ok. Therefore, I should put ABC inside an IfOk block".

Example:

 if(ok) {
   callA()
   callB()
   callC()
 }
 else
    throwException()
Scale this up and we get:
 if(ok){
   callA()
   if(A_ok){
     callB()
     callC()
     if(B_Ok AND C_ok){
        callD()
        callE()
        callF()
        callG()
     }
     else
        throwException("Method A failed")
   }
   else
      throwException("Method B or C failed")
 }
 else
    throwException()

The business logic should have been as simple as ABC but the error-handling code has caused problems: Actual Solution: Use the IfError? pattern. Example:

 callA()
 if(A_error)
    throwException()

callB() callC() if(B_error OR C_error) throwException()

callD() callE() callF() callG()

Related AntiPatterns:ArrowAntiPattern

Applicable Positive Patterns:IfError? FailFast

AntiPatternCategory: DevelopmentAntiPattern

Also Known As: [other names]


EditText of this page (last edited June 7, 2011) or FindPage with title or text search