Let’s not let this happen

buy20to20let

I’ve seen a fair bit of code like this in JavaScript of late (so much so, I’ve a second post on it):

let result;
try {
   result = await service.getSomething();
} catch (error) {
   log.error(error);
   throw error;
}
return result;

It’s no different to this in Java

boolean found = false;
for(String s:items) {
  if (s.equals(whatImLookingFor)) {
     found = true;
     break;
  }
}
return found;

Or worse still this

String result = null;

if (items.isEmpty()) {
   result = "";
} else if (items.size() == 1) {
   result = items.get(0);
} else {
   result = items.get(0) + items.get(items.size()-1);
}

return result;

I call this the hanging temporary variable. It’s like someone made a rule that says you’re only allowed one exit point from a function. In fact, this blog post is so wrong I could scream.

Let a function get out with the answer as soon as it has it. What it that leads to a complex hard to read function? If it does, it’s because the function is too big and is doing too many things. A function should ideally be under 5 statements long. How hard is it to spot the returns in this?

// yes, you don't really need to implement this with
// library methods like Stream#anyMatch
boolean isFound(String s, List list) {
  for(String item:list) {
    if (item.equalsIgnoreCase(s)) {
       // this explains how to get true
       return true;
    }
  }

  // this reads like the default it is
  return false;
}

Simple really. Let’s not have those damned moments of suspense in a function where you have to work out will they/won’t they on the value of a goddamned spurious temp variable.

Advertisements

3 comments

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