Wrap the magic numbers of external entities

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

Last Updated: 2022-12-01

I was working with the BMF API (German tax office) and they used confusing numerical codes like 0 or 1 for things like health_insurance_type and pension_insurance_type. I mirrored these in our code for dealing with this data, as such:

const includeNursingInsurance = userInput["nursing_insurance"] != "0"
// The meanings of these numerical values are clarified in the <option> tags in the HTML
// of the corresponding form 
const includeHealthInsurance = Number(userInput["health_insurance_type"]) == 0
const includePensionInsurance =
  Number(userInput["pension_insurance_type"]) != 2
const includeUnemploymentInsurance =
  Number(userInput["unemployment_insurance"]) == 1

const zeroedInsurance = { employer: 0, employee: 0 }

Essentially the 3rd party API used are magic numbers, the classic anti-pattern.

I thought my using these was acceptable because I:

1.) inherited the magic numbers from the BMF API and was therefore 'consistent'; and 2.) had an index of their meanings at some location in my codebase (all the way over in the HTML code, another file)

But alas, this was terribly confusing when the code started getting used by other parts of the codebase as part of increasingly advanced calculations.

Lesson

Wrap magic codes in descriptive strings as part of the "Gateway" pattern:

const bmfCodes = {
  nursingInsurance: {none: 0}
  pensionInsurance: {none: 0, east: 1, west: 2}
  ...
}
const includeNursingInsurance = userInput["nursing_insurance"] != bmfCodes[nursing_insurance][none]
...