Multiple Returns in addition to Error Checking

Multiple Returns in addition to Error Checking - Hallo gues welcome to my blog, you can read this article with title Multiple Returns in addition to Error Checking, Happy reading

IMPORTANT, MUST BE READ... : Multiple Returns in addition to Error Checking
Title : Multiple Returns in addition to Error Checking

Read More


Multiple Returns in addition to Error Checking

IMPORTANT, MUST BE READ... Summary: Whether or non to allow multiple returns from a role is a controversial matter, but I recommend having a unmarried furnish declaration AND avoiding exercise of goto.

Discussion:

If you've been programming robust embedded systems for a while, you've seen code that looks something similar this:

int MyRoutine(...)
{ ...
  if(..something fails..) { ret = 0; }
  else 
  { .. do something ...
    if(..somethingelse fails..) {ret = 0;}
    else 
    { .. do something ..
      if(...yetanotherfail..) {ret = 0;}
      else 
      { .. do the computation ...
        ret = value; 
      }
    }
  }
  // perform default function
  return(ret);
}

(Note: the "ret = 0" as well as "ret = value" parts are normally to a greater extent than complex; I'm keeping this uncomplicated for the sake of the discussion.)

The full general pattern to this code is doing a bunch of validity checks as well as then, finally, inward the most deeply nested "else" doing the desired action. Generally the code inward the most deeply nested "else" is genuinely the betoken of the entire routine -- that's the activity that you lot genuinely wishing to lead hold if all the exception checks pass.  This type of code shows upward a lot inward a robust embedded system, but tin endure hard to understand.

This work has been dealt amongst a publish of times as well as most probable every reasonable thought has been re-invented many times. But when I ran upward against it inward a recent give-and-take I did roughly earthworks as well as industrial plant life out I generally disagree amongst a lot of the mutual wisdom, thence hither is what I think.

Influenza A virus subtype H5N1 mutual way to simplify things is the following, which is the guard clause pattern described past times Martin Fowler in his refactoring catalog (an interesting resources amongst accompanying book if you lot haven't meet it before.)

int MyRoutine(...)
{ ...
  if(..something fails..)     {return(0);}
  if(..somethingelse fails..) {return(0);}
  if(...yetanotherfail..)     {return(0);}
  // perform default function
  return(value);
}

Reasonable people tin (and do!) disagree close how to handgrip this.   Steve McConnell devotes a few pages of his mass Code Complete (Section 17.1, as well as 17.3 inward the mo edition) that covers this territory, amongst several alternate suggestions, including the guard clause pattern as well as a give-and-take that says maybe a goto is OK sometimes if used carefully.

I lead hold a somewhat different take, perchance because I specialize inward high-dependability systems where beingness absolutely sure you lot are non getting things incorrect tin endure to a greater extent than of import than subjective code elegance. (The brief betoken of thought is: getting code exactly a footling klunky but plainly right as well as slow to banking concern gibe for correctness is probable to endure safe. Getting code to hold off nice, but amongst a remainder modest lead a opportunity of missing a subtle põrnikas powerfulness kill someone. More this work of thought can endure industrial plant life inward a different posting.)

Here is a sketch of roughly of the approaches I've seen as well as my thoughts on them:

(1) Another Language. Use roughly other linguistic communication that does a amend chore at this.  Sure, but I'm going to assume that you're stuck amongst exactly C.

(2) Guard Clauses.  Use the guard degree pattern amongst early on returns equally shown inward a higher house . The downside of this is that it breaks the unmarried furnish per role dominion that is ofttimes imposed on security critical code. While a real regular construction powerfulness piece of work out OK inward many cases, things instruct tricky if the returns are constituent of code that is to a greater extent than complex. Rather than bargain amongst shades of grayness close whether it is OK to lead hold to a greater extent than than ane return, I prefer a strict single-return-per-function rule. The argue is that it avoids having to waste materials a lot of fourth dimension hashing out when multiple returns are OK as well as when they aren't -- as well as the accompanying risk of getting that judgment telephone call upward wrong. In other words black-and-white rules lead hold less interpretation.

If you lot are edifice a security critical system, every subjective sentence telephone call upward equally to what is OK as well as what is non OK is a lead a opportunity to instruct it wrong.  (Could you lot instruct airtight blueprint rules inward place? Perhaps. But you lot nevertheless involve to banking concern gibe them accurately later every code modification. If you lot can't automate the checks, realistically the code character volition probable degrade over time, thence it's a path I prefer non to become down.)

(3) Else If Chain.  Use an if/else chain as well as pose the furnish at the end:

int MyRoutine(...)
{ ...
  if(..something fails..)          {ret=0;}
  else if(..somethingelse fails..) {ret=0;}
  else if(...yetanotherfail..)     {ret=0;}
  else { // perform default function
         ret = value;
        }
  return(ret);
}

Wait, isn't this the same code amongst apartment indenting?  Not quite.  It uses "else if" rather than "else { if". That way that the if statements aren't genuinely nested -- in that location is genuinely only a unmarried master copy path through the code (a bunch of checks as well as the master copy activity inward the terminal code segment), without the possibility of lots of complex atmospheric condition inward the "if" sidetrack branches.

If your code is apartment plenty that this works thence this is a reasonable way to go. Think of it equally guard clauses without the multiple returns.  The regular "else if" construction makes it pretty clear that this is a sequence of alternatives, or ofttimes a laid upward of "check that everything is OK as well as inward the halt lead hold the action." However, in that location may endure cases inward which the code logic is hard to flatten this way, as well as inward those cases you lot involve something else (keep reading for to a greater extent than ideas).  The trivial instance is:

(3a) Simplify To An Else If Chain.  Require that all code endure simplified plenty that an "else if" chain works.  This is a overnice goal, as well as my offset selection of way approaches.  But sometimes you lot powerfulness involve a to a greater extent than capable as well as flexible approach.  Which brings us to the repose of the techniques...

(4) GOTO. Use a "goto" to intermission out of the catamenia as well as jump to the halt of the routine.  I lead hold seen many give-and-take postings proverb this is the right thing to do because the code is cleaner than lots of messy if/else structures. At the risk of beingness flamed for this, I respectfully disagree. The commons declaration is that a practiced programmer exhibiting land of report volition do exactly fine.  But that alone misses what I consider to endure the bigger picture.  I don't assist how smart the programmer who wrote the code is (or thinks he is).  I assist a lot close whoever has to banking concern gibe as well as maintain the code. Sure, a practiced programmer on a practiced solar daytime tin exercise a "goto" as well as basically emulate a try/throw/catch structure.  But non all programmers are pinnacle 10 percentile, as well as a lot of code is written past times newbies who exactly don't lead hold plenty sense to lead hold acquired mature judgment on such matters. Beyond that, nobody has all practiced days.

The large resultant isn't whether a programmer is probable to instruct it right. The resultant is how hard (and error-prone) it is for a code reviewer as well as static analysis tools to brand sure the programmer got it right (not almost right, or subtly wrong). Using a goto is similar pointing a loaded gun at your foot. If you lot are careful it won't become off. But fifty-fifty a unmarried goto shoves you lot onto a heavily greased slippery slope. Better non to become in that location inward the offset place. Better to uncovering a technique that powerfulness seem a footling to a greater extent than klunky, but that gets the chore done amongst minimum fuss, depression overhead, as well as minimal lead a opportunity to brand a mistake. Again, regard my posting on non getting things wrong.

(Note: this is amongst honor to unrestricted "goto" commands used past times human programmers inward C. Generated code powerfulness endure a different matter, equally powerfulness endure a linguistic communication where "goto" is restricted.)

(5) Longjmp.  Use setjmp/longjmp to laid upward a target as well as thence jump to that target if the listing of "if" error checks wants to furnish early. In the terminal analysis this is genuinely the moral equivalent of a "goto," although it is a chip amend controlled. Moreover, it uses a pointer to code (the setjmp/longjmp variable), thence it is an indirect goto, as well as that inward full general tin endure hazardous. I've used setjmp/longjmp as well as it tin endure made to piece of work (or at to the lowest degree seem to work), but dealing amongst pointers to code inward your root code is ever a dicey proposition. Jumping to a corrupted or uninitialized pointer tin easily crash your organization (or sometimes worse).  I'd enjoin avoid using this approach.

I've seen give-and-take forum posts that roll longjmp-based approaches upward inward macros to gauge Try/Throw/Catch. I tin sure as shooting appreciate the appeal of this approach, as well as I could regard it beingness made to work. But I worry close things such equally whether it volition piece of work if the macros instruct nested, whether reviewers volition endure aware of whatsoever implementation assumptions, as well as what volition occur amongst static analysis tools on those structures. In high-dependability code if you lot can't endure sure it volition work, you lot shouldn't do it.

(6) Do..While..Break. Out of the classical C approaches I've seen, the ane I similar the most (beyond else..if chains) is using a "do..while..break" structure:

int MyRoutine(...)
{ ...
  do { //  start error treatment code sequence
    if(..something fails..)     {ret=0; break;}
    if(..somethingelse fails..) {ret=0; break;}
    if(...yetanotherfail..)     {ret=0; break;}
    // perform default function
    ret = value;
  } spell (0); // halt error treatment code sequence
  return(ret);
}

This code is a hybrid of the guard pattern as well as the "else if" block pattern. It uses a "break" to skip the repose of the code inward the code block (jumping to the while(0), which ever exits the loop). The while(0) converts this construction from a loop into exactly a structured block of code amongst the powerfulness to branch to the halt of the code block using the "break" keyword. This code ought to compile to an executable that is has essentially identical efficiency to code using goto or code using an else..if chain. But, it puts an of import restriction on the goto-like capability -- all the jumps lead hold to betoken to the halt of the do..while without exception.

What this way inward do is that when reviewing the code (or a modify to the code) in that location is no interrogation equally to whether a goto is good behaved or not. There are no gotos, thence you lot can't brand an unstructured goto fault amongst this approach.

While this toy representative looks pretty much the same equally the "else if" structure, an of import betoken is that the "break" tin endure placed anywhere -- fifty-fifty deeply inside a nested if declaration -- without raising questions equally to what happens when the "break" is hit. If inward dubiety or in that location is roughly argue why this technique won't piece of work for you, I'd propose falling dorsum on restructuring the code thence "else if" or this technique works if the code gets also complex to handle. The master copy work to proceed inward heed is that if you lot nest do..while structures the intermission volition un-nest only ane level.

I recognize that this surface area falls a footling chip into a thing of sense of savour as well as context. My sense of savour is for code that is slow to review as well as unlikely to lead hold bugs. If that is at odds amongst subjective notions of elegance, thence endure it. In constituent my preference is to outlaw the routine exercise of techniques that require manual analysis to create upward one's heed of a potentially dangerous construction is beingness used the "right" way. Every such sentence telephone call upward is a lead a opportunity to instruct it wrong, as well as a distraction of human reviewer attending away from to a greater extent than of import things. And I dislike arguments of the cast that a "good" as well as experienced programmer won't brand a mistake. It is exactly also slow to immature adult woman a subtle bug, peculiarly when you're modifying code inward a hurry.

If you've meet roughly other way to handgrip this work allow me know.



IMPORTANT, MUST BE READ...

Thank for your attention Multiple Returns in addition to Error Checking

my blog Multiple Returns in addition to Error Checking, Have a nice day.

Now you read article Multiple Returns in addition to Error Checking this permalink article is http://fairemirima.blogspot.com/2017/11/multiple-returns-in-addition-to-error.html Thank you and Best regards. You Can read nice Tips below. It was always better to choose topics that interest you or in wich you at least have some knowledge about . When creating targeted internet copywriting , you have to stick with your strong points , or everyone will know it . Make a list of all of the things and or topics that you are interested in . . . How much do you know ? Can you tell it as a story ? That is The essence of writing for the web . You Have to know your subject well , or nobody will believe you it is always better to impress someone then upset them . When Writing Targeted Internet Copywriting , you have to choose your appropriate target group of customers . without a target group of customers , you could ramble on incessantly about random subjects for days on end with no essence of a final goal . You always have to keep in mind who your customers are and what they are looking for . . . . . . . . . IMPORTANT, MUST BE READ...

0 Response to "Multiple Returns in addition to Error Checking"

Post a Comment