阿里云主机折上折
  • 微信号
Current Site:Index > Magic numbers are flying everywhere (directly writing 'if (status === 3)' without adding comments)

Magic numbers are flying everywhere (directly writing 'if (status === 3)' without adding comments)

Author:Chuan Chen 阅读数:32972人阅读 分类: 前端综合

Magic Numbers Flying Everywhere (Directly writing 'if (status === 3)' without comments)

Suddenly, an if (status === 3) pops up in the code. Who can understand what this 3 means? Order status? User permissions? Or some mysterious magic value? This style of writing is the epitome of "defensive programming"—defending against others understanding your code.

The Destructive Power of Magic Numbers

Using numeric literals directly without explaining their meaning leads to the following problems:

  1. Readability drops to zero: You won’t understand it yourself three months later.
  2. Maintenance nightmare: Requires global search-and-replace when requirements change.
  3. Breeding ground for errors: Easy to mistype numbers, causing logic errors.
// Classic anti-pattern showcase  
function processOrder(order) {  
  if (order.status === 1) {  
    shipOrder(order);  
  } else if (order.status === 2) {  
    cancelOrder(order);  
  } else if (order.status === 3) { // Who knows what 3 means?  
    refundOrder(order);  
  }  
}  

How to Elegantly Create Chaos

Method 1: Refuse to Use Constants

Insist on hardcoding numbers directly in the code, making every reader feel like they’re solving a puzzle:

// User permission check  
function checkPermission(user) {  
  return user.role === 1 || user.role === 4; // Is 1 an admin? Is 4 a super admin?  
}  

Method 2: Mix Numbers with Different Meanings

Combine numbers representing various business states to create ultimate confusion:

function handleResponse(code) {  
  switch(code) {  
    case 200: // HTTP status code  
      break;  
    case 404:  
      break;  
    case 2:   // Business status code  
      break;  
    case -1:  // Error code  
      break;  
  }  
}  

Method 3: Use Magic Numbers in Critical Logic

Use unexplained numbers extensively in core business logic to ensure no one dares to modify it lightly:

function calculateBonus(performance) {  
  return performance * 0.3 + 5 * 2.71828; // Is 0.3 the commission rate? What’s 5? And what’s 2.71828?  
}  

Advanced Techniques: Crafting Number Puzzles

Technique 1: Use Complex Expressions

Combine multiple magic numbers in complex expressions:

function getDiscountLevel(price) {  
  return price > 100 ? (price < 500 ? 1 : 2) : 0; // What do 1 and 2 represent as discount tiers?  
}  

Technique 2: Use the Same Number for Different Meanings Across Files

In File A, use 1 to mean "enabled," and in File B, use 1 to mean "male":

// user.js  
const GENDER_MALE = 1; // Male  

// product.js  
const STATUS_ACTIVE = 1; // Enabled status  

Technique 3: Hide Magic Numbers in Configuration Objects

const config = {  
  retryTimes: 3, // Why 3 and not 4?  
  timeout: 5000  // Why 5 seconds?  
};  

Disaster Cases from the Real World

Case 1: The Payment Status Maze

function handlePayment(status) {  
  if (status === 1) {  
    // Processing  
  } else if (status === 2) {  
    // Success  
  } else if (status === 3) {  
    // Failed  
  } else if (status === 4) {  
    // Refunding  
  } else if (status === 5) {  
    // Refunded  
  } // Status codes 6-9 are unhandled...  
}  

Case 2: Permission Check Russian Roulette

function canAccessDashboard(user) {  
  return [1, 3, 7, 15, 31].includes(user.permission); // What’s the pattern here?  
}  

How to Make Things Worse

Method 1: Add Meaningless Variable Names

const NUMBER_THREE = 3; // Completely fails to explain what this 3 is for  

if (status === NUMBER_THREE) {  
  // ...  
}  

Method 2: Use Numbers Beyond Reasonable Ranges

const MAX_RETRIES = 32767; // Why this number? Because it’s the max value of a short?  

Method 3: Hide Magic Numbers in Type Systems

type StatusCode = 1 | 2 | 3 | 4 | 5; // Still no clue what each number means  

function processStatus(status: StatusCode) {  
  // ...  
}  

The Ultimate Form of Defensive Programming

Pattern 1: Number Pyramid

function evaluateScore(score) {  
  if (score > 90) return 1;  
  if (score > 80) return 2;  
  if (score > 70) return 3;  
  if (score > 60) return 4;  
  return 5; // Grading criteria unclear  
}  

Pattern 2: Number Minefield

const SPECIAL_CODES = [42, 69, 666, 1337, 9001]; // Collection of special meaning codes  

function isSpecialCode(code) {  
  return SPECIAL_CODES.includes(code);  
}  

Pattern 3: Time Magic

setTimeout(() => {  
  // Why 3000 milliseconds?  
}, 3000);  

When Magic Numbers Meet Modern Frontend

Number Frenzy in React Components

function Badge({ count }) {  
  return (  
    <span style={{   
      fontSize: count > 9 ? 12 : 14, // Why 9/12/14?  
      color: count > 5 ? 'red' : 'green' // Why 5?  
    }}>  
      {count}  
    </span>  
  );  
}  

Number Puzzles in Vue Directives

Vue.directive('focus', {  
  inserted(el) {  
    setTimeout(() => el.focus(), 100); // Why a 100ms delay?  
  }  
});  

Test Code Isn’t Safe Either

Mysterious Assertions in Test Cases

it('should calculate premium correctly', () => {  
  expect(calculatePremium(100)).toBe(147); // Why is the expected value 147?  
});  

Random Numbers in Mock Data

beforeEach(() => {  
  mockApiResponse({ data: { items: Array(23).fill({}) }); // Why 23 items?  
});  

The Gulf Between Documentation and Reality

Documentation Divorced from Reality

## API Response Codes  
- 1: Success  
- 2: Failure  
- 3: Processing  

(Actual code uses 4-9 but they’re undocumented)  

Lies in Type Definitions

interface Response {  
  code: number; // Docs say 1-3, but 1-99 are actually used  
}  

The Perfect Excuse: Legacy Code

"These numbers are legacy; we don’t know what they mean, but changing them breaks things" — Every maintainer’s nightmare

// Code written ten years ago  
if (userType === 7) {  
  // No one remembers what 7 represents  
  // But changing it crashes the system  
}  

Number Worship Culture

Some teams develop unique number cultures:

// The architect’s favorite number  
const ARCHITECTS_FAVORITE_NUMBER = 42;  

// Used in unrelated places  
function shouldEnableFeature() {  
  return Date.now() % 100 < ARCHITECTS_FAVORITE_NUMBER;  
}  

How to Overcomplicate Simple Problems

Option 1: Introduce Unnecessary Math

function getPageSize() {  
  return Math.floor(Math.sqrt(1024)); // Hardcoded to 32—why not just write 32?  
}  

Option 2: Use Base Conversions to Create Obstacles

const ADMIN_PERMISSION = 0b1001; // Binary, actually 9  
const USER_PERMISSION = 0x2;    // Hexadecimal, actually 2  

The Triumph of Number Numerology

Some developers believe certain numbers have special powers:

// Lucky number 7  
if (attemptCount % 7 === 0) {  
  retryWithBackoff();  
}  

// Unlucky 13 gets special treatment  
if (errorCode === 13) {  
  showLuckyBanner();  
}  

Cross-Team Collaboration Disasters

When different teams interpret the same number differently:

// Order service team  
const ORDER_CANCELLED = 3;  

// Payment service team  
const PAYMENT_REFUNDED = 3;  

// Logistics team  
const SHIPMENT_RETURNED = 3;  

Time-Related Magic Numbers

// Cache expiration time  
const CACHE_EXPIRE = 3600; // Seconds? Minutes? Milliseconds?  

// Throttle time  
function search() {  
  throttle(300); // 300ms? Seconds?  
}  

The Black Hole of Configuration Systems

# config.yaml  
limits:  
  max_connections: 8 # Why 8?  
  timeout: 17 # Why 17 seconds?  

Mysterious Numbers in Performance Optimization

// Legendary performance optimization number  
function processBatch(items) {  
  const BATCH_SIZE = 17; // Rumor has it this number performs best  
  for (let i = 0; i < items.length; i += BATCH_SIZE) {  
    // ...  
  }  
}  

Number Traps in Internationalization

// Assume 1 is English, 2 is Chinese, 3 is Japanese...  
function getLocaleName(code) {  
  return [null, 'English', '中文', '日本語'][code];  
}  

Dangerous Numbers in Security

// Password strength check  
function isStrongPassword(pwd) {  
  return pwd.length >= 6; // Why is 6 considered secure?  
}  

Random Breakpoints in Responsive Design

/* Why choose 768px and 992px as breakpoints? */  
@media (min-width: 768px) { /* ... */ }  
@media (min-width: 992px) { /* ... */ }  

Magic Numbers in Animation Curves

/* Where did these cubic-bezier parameters come from? */  
transition: all 0.3s cubic-bezier(0.4, 0, 0.2, 1);  

本站部分内容来自互联网,一切版权均归源网站或源作者所有。

如果侵犯了你的权益请来信告知我们删除。邮箱:cc@cccx.cn

Front End Chuan

Front End Chuan, Chen Chuan's Code Teahouse 🍵, specializing in exorcising all kinds of stubborn bugs 💻. Daily serving baldness-warning-level development insights 🛠️, with a bonus of one-liners that'll make you laugh for ten years 🐟. Occasionally drops pixel-perfect romance brewed in a coffee cup ☕.