Let’s agree a compromise

buy20to20let

In my previous post I talked about the hanging temp variable anti-pattern. I want to drill deeper into an example where I’m unhappy with the answer.

What if you need to use a helper to throw an exception in catch at the same time as wanting to return a value from a function.

E.g.

// this just converts error into the right exception
const reportOnError = (error) => throw Boom.notFound("aaagh");

.
.

const otherFoo = () => {
  let result;
  try {
    result = callSomeFunc();
  } catch (error) {
    reportOn(error);
  }
  return result;
}

The problem here is that ESLint won’t let us write this:

const otherFoo = () => {
  try {
    // the one and only way to return
    return callSomeFunc();
  } catch (error) {
    reportOn(error);
  }
}

ESLint decides that you have a path out of the function without a return… This is technically not true, but you can see why it might think that.

However, you can write this.

const otherFoo = () => {
  try {
    // the one and only way to return
    return callSomeFunc();
  } catch (error) {
    // reportOn doesn't return, it throws, but there you go...
    return reportOn(error);
  }
}

This is weird, the reporting function doesn’t really return anything, but we still return its value. Is that bad?

In the original, we have the following smells:

  • A temp variable for weird structural reasons
  • A drop through from the real calculation to a later return
  • A return statement that appears to return undefined in some paths, when in fact it’s unreachable

In the third version, we have one smell

  • return is slightly misleading…

This is largely because ESLint is not able to see that the function that ONLY throws transitively makes the calling closure only throw.

I reckon we can call it a draw at this point…

Advertisements

One comment

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