Throw if an expected key is missing

This is part of the Semicolon&Sons Code Diary - consisting of lessons learned on the job. You're in the exceptions category.

Last Updated: 2024-11-23

My work building tax calculators used about a thousand lines of structured data about various taxation rates, each sorted by year:

const rates = {
  ...
  utility: {
    ...
    ratesPer200Kg: {
      0: 1125,
      2000: 1202,
      3000: 1278
    }
  }
}

I spent the majority of my debugging time dealing with unexpected undefined entities.

e.g. imagine I had a typo for the utility key:

// missing an 'i' in 'utilty'
const utilityRates = rates["utilty"]

The effect is that utilityRates is undefined. This doesn't blow up right away (unfortunately), but rather causes oddities further downstream when this value gets used.

I should have had some code like the following to complain - at that exact point in the code - when the undefined value sneaked it.

function getValue(obj, key) {
  if (! obj.hasOwnProperty(key)) {
    throw new Error(`Key ${key} not found in object ${JSON.stringify(obj)}`);
  }

  return obj[key]
}

Lesson

Design the program so as to better localize errors. Ensure that an exception is raised at the point of anomaly rather than downstream (where it might cause weird behavior that makes it difficult to recognize the bug)

Narrowly, throw an error if an expected key is missing on an object rather than letting it be undefined.