The Additional Curse of the Temp Variable

Screen Shot 2018-10-20 at 11.48.35Before I write this, I should point out that I have often written code that makes use of an accumulator to aggregate data before returning it. Readers of this blog may note, however, that I’ve been very dismissive of the hanging temporary variable which seems to exist, only to hold a value up until its single return point. I’ve also talked about how declaring your variables reverses the reading order.

In general, I’d always replace a temp variable with a function to calculate the result of that calculation, or a literal, unless the value was used multiple times, or the addition of named variables adds meaning. Adding meaning is the key here.

It’s all too easy to either confuse the reader, or confuse yourself, with an ill-placed temporary variable, and today I discovered a new curse:

const result = {};
try {
  result.values = await retrieveValues();

  result.data = await retrieveData();

  result.processed = true;
} catch (exception) {
  result.processed=false;
}
return result;

What is the value of result in the exception case? It’s horribly muddy. If the exception happened inside the first function call, then it’s just processed:false otherwise it may have some extra stuff in. The problem here is a woolliness of intent. It would be better for the return points to each construct their data, or for there to be a cascading return from the outcome of the first function, added to the result from the second, or not in the case of exception.

Remove these accumulators when you can!

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