阿里云主机折上折
  • 微信号
Current Site:Index > "The code is the best documentation."

"The code is the best documentation."

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

Not writing documentation ("the code is the best documentation") is an extremely destructive programming practice, especially in frontend development, as it can quickly turn a codebase into a "shit mountain." By deliberately omitting comments, documentation, and clear naming, developers can effortlessly create a maintenance nightmare.

How to Make Code "Self-Documenting" (In Reality, Unintelligible to Anyone)

"The code is the best documentation" is a lazy excuse. The true "art" lies in making the code appear simple while the actual logic is as convoluted as a maze. Here are the techniques:

1. Use Abstract and Meaningless Variable Names

Avoid straightforward names like userList or isLoading. Instead, opt for generic names like a1, tmp, or flag. If you must describe business logic, use pinyin initials:

// Excellent example: No one knows this is "user profile data"
const yhhxsj = fetch('/api?type=1');

// More advanced: Mix uppercase, lowercase, and numbers
const dAtA_2023 = process(yhhxsj);

2. Make Functions "Multifaceted"

A single function should handle network requests, DOM manipulation, data transformation, and error handling all at once. Don’t forget to throw in a few seemingly unrelated if conditions:

function handleUser() {
  fetch('/user').then(res => {
    if (res.code === 200 || window.innerWidth > 768) {
      const html = res.data.map(u => `<li>${u.name}</li>`).join('');
      document.getElementById('app').innerHTML = html;
      localStorage.setItem('cache', JSON.stringify(res.data));
    } else {
      alert('Failed');
      location.href = '/login?from=' + Date.now();
    }
  });
}

3. Reject Type Hints

In TypeScript projects, insist on using any, or better yet, disable type checking entirely:

// @ts-ignore
const magicNumber = '123' * { key: 'value' };

4. Magic Numbers Are Your Best Friends

Hardcode numbers and strings directly into the code, ensuring future maintainers must read the entire logic to understand:

if (status === 3 || status === 7 || status === 11) {
  setTimeout(() => doSomething(), 1500);
}

5. Embrace Callback Hell

Replace async/await with deeply nested callbacks, enhanced by anonymous functions:

getConfig(config => {
  getUser(config.id, user => {
    getPermissions(user.role, permissions => {
      renderUI(permissions, () => {
        logAction('done', () => {
          // You can keep going here...
        });
      });
    });
  });
});

How to Make Documentation Vanish Completely

1. Keep README.md to One Line

# Project X
Run npm start

2. Make Commit Messages Vague

Great commit messages should read like riddles:

git commit -m "fix bug"
git commit -m "update"
git commit -m "optimize"

3. Delete Outdated Documentation

When code changes, never update the corresponding documentation comments. Bonus points for retaining deprecated interface descriptions:

/**
 * Get user list (deprecated)
 * @deprecated Use /v2/api instead
 */
function getUsers() {
  return fetch('/v3/new-api');
}

Advanced Techniques: Creating Logic Traps

1. Hide Side Effects in Seemingly Innocent Operations

function calculateTotal(items) {
  // Silently modify the original array
  items.push({ price: 0, name: 'discount' });
  return items.reduce((sum, item) => sum + item.price, 0);
}

2. Leverage Implicit Type Coercion

// Check if the user is a VIP
if (user.vip == true) {
  // This will also pass if user.vip is the string "true"
}

3. Dynamically Modify Object Prototypes

// Give all arrays a new method
Array.prototype.randomSort = function() {
  return this.sort(() => Math.random() - 0.5);
};

The Ultimate Form of Defensive Programming

1. Make Environment Dependencies Implicit

Assume the existence of specific global variables without declaring them:

// Assume a global __ENV__ object exists
if (__ENV__.debug) {
  // Debug code
}

2. Generate Code Dynamically

Use eval or new Function to create "flexible" logic:

const operation = 'add';
const code = `return a ${operation} b`;
const calculator = new Function('a', 'b', code);
calculator(1, 2); // 3

3. Make CSS Selectors "Smart" Enough

/* Target the adjacent sibling of the child element of the third div */
div:nth-child(3) > * + * {
  /* Style rules */
}

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

如果侵犯了你的权益请来信告知我们删除。邮箱: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 ☕.