Use Number Constants over Magic Numbers.
Tuesday, February 25, 2020
Use Number Constants over Magic Numbers.
If you find yourself repeating numeric literals in your code then these numbers should be declared as a single constant value, and then imported where necessary. Magic numbers have a meaning, likely to one developer or engineer, but perhaps not to another. Having magic numbers throughout a code base can lead to confusion, but perhaps more importantly, can result in regressions if the numbers are refactored or updated.
Instructions
checkmark-circle
define and export numeric constants
error-circle
multiple magic numeric literals
question-circle
defining an enumeration for multiple logically associated constant values
Code Examples
declare constant numerics
// constants.js
const TAX_RATE = 0.825;
const SHIPPING_RATE = 0.125;
// shopping-cart.js
import { SHIPPING_RATE, TAX_RATE } from './constants';
export class ShoppingCart {
calculateTotal(lineItems): number {
const subtotal = lineItems.reduce((prev, current) => prev + current.price, 0);
const shipping = subtotal * SHIPPING_RATE;
const tax = subtotal * TAX_RATE;
return subtotal + shipping + tax;
}
}
avoid magic number literals
export class ShoppingCart {
calculateTotal(lineItems): number {
const subtotal = lineItems.reduce((prev, current) => prev + current.price, 0);
const shipping = subtotal * 0.125; // the shipping rate should be calculated or declared as a constant
const tax = subtotal * 0.825; // the tax rate should be declared as a constant
return subtotal + shipping + tax;
}
}
Rules
- eslint: no-magic-numbers
Have a question or comment?