Early Return Or return early
early return or return early

Early Return Or return early

Let's first discuss the early return with a simple real-life example. Assume you like someone and express your feelings too early, what will happen? Most of the time you are being rejected and need not wait to impress her later. So what actually your time and cost will save and you will get another chance to propose to other girls.

The same goes for a return Early in programming.

An early return, or “return early” is an approach to keep readability in functions and methods. It is always considered a wise choice to return early if simple conditions apply that can be checked at the beginning of a method.

#Why return Early?

The motivation behind this is to avoid nesting too deeply and return early instead. Too many if-else statements can make your code hard to follow. Explicit is better than implicit. It's better to return early, keeping indentation and brain power needed to follow the code low.

#Example :

// Bad practice 
function getlover(girl) {
  if (girl) {
    // code
  }else {
    return null;
    }
 }        

If there are too much logic it's too tough to read the code

// Best practice

function getlover(girl) {
If (!girl) return;

//write your remaining code here
}        


The first code will keep the indentation. Second, it's easy to read the code. Third for multiple conditions it reduces the time complexity which might be in microseconds. Reduce the chance of exception.

要查看或添加评论,请登录

Dip Ghosh的更多文章

社区洞察

其他会员也浏览了