JS: Polymorphism

Theory: Dispatch by file

Another interesting trick is dispatching by file name.

In some systems, it's common to have different files belonging to separate environments for configuration rather than one file. For example:

configs/ database.development.json database.production.json database.test.json

Somewhere in the source code must be a code block that selects which file to load. The code below uses dispatching by key:

import fs from 'fs';

const configFileNamesByEnv = {
  development: 'database.development.json',
  production: 'database.production.json',
  test: 'database.test.json',
};

const filename = configFileNamesByEnv[env];
const raw = fs.readFileSync(filename);
const config = JSON.parse(raw);

It is not difficult to see that using a startup environment name. So we can create a suitable file name. Let us do that:

const filename = `database.${env}.json`;
const raw = fs.readFileSync(filename);
const config = JSON.parse(raw);

The code is much shorter and no longer needs to be changed when expanding.

Recommended programs