Get Out!

Screen Shot 2018-10-20 at 12.06.07.png

If you’re writing a function, don’t spend your time hanging around in it. Once your code can return, just return. Given functions are short, having a couple of return points is not a big deal. We’ve dealt with that before.

In particular, let’s drill down to a common example of not doing this:

// default set here, but returned at the end
let answer = 'undecided';

if (input !== '') {
  if (input === 'yes') {
     // two levels of nested and still setting
     // a variable for later
     answer = 'yes please';
  } else {
     answer = 'no thank you';
  }
}

// single exit point - no idea
// what value will be here
return answer;

As you can see there’s our old nemesis the hanging temp variable and there’s the return of a default as well as return of a correct value. Worse than that, there’s a lot more indentation than you really need.

IntelliJ can flip the logic of an if statement, so you can start the ball rolling by doing that. Then may the if leading to the default just return the default… and then work on the rest of the function.

You end up with something like this, which I think is way cleaner!

// this is a get out early
if (input === '') {
  return 'undecided';
}

// this is a specific case with a specific answer
if (input === 'yes') {
  return 'yes please';
}

// this is a default
return 'no thank you';
Advertisements

Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out /  Change )

Google+ photo

You are commenting using your Google+ account. Log Out /  Change )

Twitter picture

You are commenting using your Twitter account. Log Out /  Change )

Facebook photo

You are commenting using your Facebook account. Log Out /  Change )

Connecting to %s