Level Extreme platform
Subscription
Corporate profile
Products & Services
Support
Legal
Français
Multiple return points - is it OK practice?
Message
From
01/02/2013 18:11:44
 
General information
Forum:
ASP.NET
Category:
Coding, syntax and commands
Environment versions
Environment:
C# 4.0
OS:
Windows 7
Network:
Windows 2003 Server
Database:
MS SQL Server
Miscellaneous
Thread ID:
01564936
Message ID:
01564978
Views:
52
Here's how we avoid nested if's
public bool ErrorChecker()
{
   bool OKToProceed = true;
  if (error1)
  {
      OKToProceed = false;
      Logerror("1");  
}
  if(OKTOProceed)
  {
      if (error2)
      {
        OKToProceed = false;
         Logerror("2");         
    }
  }
  if(OKTOProceed)
  {
     if (error3)
    {
       OKToProceed = false;
        Logerror("3");    
    }
 
  // etc, etc
   } 
return OKToProceed;
}
>>>>I have controller methods where sometimes I return a View and othertimes I RedirectToAction. So, two returns are required.
>>>>
>>>Right now I am working on the conversion of our VFP class library into C# dll. In VFP we checked parameters at the top and returned. There were also many other return exists in the methods.
>>>
>>>I already converted a few by not using early returns, but I think in general it should be OK - otherwise it's very hard to use if else if else nested logic.
>>
>>No its not....
>>
>>You set a variable. ... retVal ... you initialize it however you want, then in your flow, instead of returning, you assign the value to retVal and at the end you return retVal.
>>
>>I hate code with multiple return points and numerous out parameters. You cant test it and you end up with nothing but a spaghettie code mix...
>
>But how do you navigate in all this if else code
>
>E.g.
>
>Int32 SomeValue;
>
>If (!Int32.TryParse(SomeString, out SomeValue) || SomeValue = 0)
>   {
>   // First Error here
>   }
>   else
>      { more code that may cause problems
>             if ...
>                     
>      }
>}
>
>In other words, it is very hard to keep track of all these if else and {}
>
>BTW, I usually create several UnitTests per method - for invalid parameters, for some unreal values, etc.
Anyone who does not go overboard- deserves to.
Malcolm Forbes, Sr.
Previous
Next
Reply
Map
View

Click here to load this message in the networking platform