简体   繁体   中英

Need to know good practice should i follow on below code

i have code as :

 int good_practice(void)
    {
      if (somethings == TRUE)
       return true;  //i am asked to remove it coz it will reach anyhow at end and do same but i feels it is good practice and why should i wait for end?
      else
       return false
      }
     }
     return true; 
    }

i am asked remove first return since it will ultimately reach end of function and will return true.Is this good ?

what i feel why do i need to wait for cpu to go at end of function and return though i can do early.if i have decide to return with some condition why should i return from end why not there itself why to wait for end ?

And also if i am wait for end the i increase time complexity(i know it won't make any difference) but no of instruction is also increased.

please help me to get out of this confusion?

This is called an “early return” and I don't think there is a clear consensus.

Pros:

  • You can't execute some other code by mistake if you return early.
  • If you are reading this particular execution branch, the early return makes the flow more explicit.
  • It's also possible to decrease the indent level by returning early.

Cons:

  • When you're looking at the whole function, it's easier to miss an early return.

There are some similar previous questions about early returns, see here for example .

You are asked to remove the first return true because you can simply check like this, and not have an additional redundant return true :

int good_practice(void) {
    if(!somethings) { 
        return false;
    }
    return true;
}

Anyway, the code in question is pretty much redundant .

You can replace it with an even better version, like this:

int good_practice(void)
{
    return somethings;
}

About the early return:

Its generally better to have one return at the end, because the performance gained, when returning earlier is nowhere near the gained readability by having one return only .

(Thats just my own experience though).

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM