lookout.devlookout.dev
search
Share Knowledge
00

Use Number Constants over Magic Numbers.

Tuesday, February 25, 2020

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
Do

define and export numeric constants

error-circle
Avoid

multiple magic numeric literals

question-circle
Consider

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

Brian Love

I am a software engineer and Google Developer Expert in Web Technologies and Angular with a passion for learning, writing, speaking, teaching and mentoring. I regularly speaks at conferences and meetups around the country, and co-authored "Why Angular for the Enterprise" for O'Reilly. When not coding, I enjoy skiing, hiking, and being in the outdoors. I started lookout.dev to break down the barriers of learning in public. Learning in public fosters growth - for ourselves and others.

Google Developers Expert

Have a question or comment?