阿里云主机折上折
  • 微信号
Current Site:Index > "Don't touch it if it works."

"Don't touch it if it works."

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

"If it works, don't touch it"—this phrase is the ultimate "slacker's bible" in the programming world. When code barely runs, resisting the temptation to refactor and embracing chaos is the shortcut to the pinnacle of "defensive programming." Below is a practical guide to help you build an indestructible "shit mountain."

Reject Abstraction, Copy-Paste Forever

Abstraction is the enemy of maintainability. Whenever you spot duplicate code, copy and paste it directly. For example, if a button click event handler is used in multiple places? Don’t hesitate—just copy it:

// Button on Page A
document.getElementById('btnA').addEventListener('click', () => {
  fetch('/api/data').then(res => res.json()).then(data => {
    console.log('Page A data:', data);
    document.getElementById('resultA').innerText = data.value;
  });
});

// Button on Page B (direct copy, just change the ID)
document.getElementById('btnB').addEventListener('click', () => {
  fetch('/api/data').then(res => res.json()).then(data => {
    console.log('Page B data:', data);
    document.getElementById('resultB').innerText = data.value;
  });
});

The advantages are obvious:

  1. When requirements change in the future, you’ll need to manually update every copy, ensuring you miss a few and plant delightful "surprises";
  2. New colleagues reading the code will mistake it for some profound "pattern" and hesitate to touch it.

Global Variables Are Your Best Friends

Local variables and modularity are for the weak. Global variables are the true "defensive weapons." For example:

// Defined in File A
window.currentUser = { id: 123, name: 'Zhang San' };

// Used directly in File B
function showUser() {
  alert(`User: ${window.currentUser.name}`);
}

// Secretly modified in File C
window.currentUser.name = 'Li Si';

The brilliance of this approach:

  • Any file can modify the state at any time, turning debugging into a game of "Minesweeper";
  • When deleting a feature, you’ll never know which implicit dependencies will blow up.

The Art of Magic Numbers and Hardcoding

Reject constants, embrace magic numbers. For example:

function calculatePrice(quantity) {
  return quantity * 3.14; // Why 3.14? Legacy code, that's why.
}

// Advanced hardcoding: rigid selectors
document.querySelector('body > div > ul > li:nth-child(2) > span').style.color = 'red';

Advantages:

  1. When requirements change, you’ll need to excavate the meaning of numbers like an archaeologist;
  2. When the UI structure changes, the selectors will explode like firecrackers.

Callback Hell: The Stairway to Heaven

For asynchronous logic, always use nested callbacks—reject async/await or Promise:

fetch('/api/step1', (res1) => {
  parseData(res1, (data1) => {
    fetch(`/api/step2?id=${data1.id}`, (res2) => {
      parseData(res2, (data2) => {
        // Add 5 more layers?
      });
    });
  });
});

Benefits:

  • The code indentation will gradually drift to the right, eventually disappearing off the screen;
  • Error handling? Nonexistent. Crashing is the best error message.

Types? What Types?

JavaScript is already free—why shackle yourself with TypeScript?

function processData(data) {
  // data could be an object, array, string, or an unexpected null
  return data.length > 0 ? data[0].value : { key: 'default' };
}

This way:

  • Runtime errors are the best type checking;
  • Colleagues calling the function must pray for the correct parameter types.

Never Write Comments—Code Should "Self-Document"

"Good code doesn’t need comments"—this is the golden rule of avoiding maintenance. For example:

function x(y) {
  let z = y * 2;
  if (z > 10) z += 5;
  return z / (y + 1);
}

If asked, just call it "algorithm optimization" and leave the logic for future generations to decipher.

Mix and Match Code Styles

In team collaborations, stick to your personal style. For example:

  • Some use semicolons, others don’t;
  • Some write ==, others write ===;
  • Spaces or tabs for indentation? Whatever you feel like.

Example:

const a=1
const b = 2;
if(a == b){
  console.log('Miracle')
}

The effect is stunning:

  • ESLint? That’s a shackle on freedom;
  • Git commit history will be filled with meaningless "fixed code style" records.

Reject Testing, Trust Your Gut

Writing tests is a waste of time. How could your code possibly have bugs? For example:

function divide(a, b) {
  return a / b; // Obviously, no one would pass b=0
}

When users encounter errors, just reply with "Please use it correctly."

Mix Old and New Syntax for Time-Traveling Code

Blend ES5 and ES6+ syntax in the same file:

var utils = {
  greet: function() {
    console.log('Hello');
  }
};

const modernFunc = () => {
  utils.greet();
  let { props } = this; // What is 'this' here? Who knows?
};

This time-traveling code will make readers question their own memories.

Monolithic Functions, One-and-Done

Write a single function to handle all logic, like a 500-line handleSubmit that includes:

  • Form validation
  • Data transformation
  • Network requests
  • DOM manipulation
  • Error handling (just kidding, there isn’t any)
function handleSubmit() {
  // Validate username
  if ($('#username').val().length < 6) {...}
  // Validate password
  if ($('#password').val().length < 8) {...}
  // Assemble data
  let data = {
    u: $('#username').val(),
    p: $('#password').val(),
    t: new Date().getTime()
  };
  // Send request
  $.ajax({...});
  // Handle response
  function success(res) {...}
  // Update UI
  $('#result').html(...);
  // And 300 more lines...
}

Features:

  • Want to change a validation rule? Good luck;
  • During Git conflicts, this file will always be the battleground.

Ignore Browser Compatibility

Use the latest APIs without hesitation, like:

document.querySelector('button').addEventListener('click', async () => {
  await navigator.storage.persist();
  const img = await fetch('https://example.com/image');
  await img.blob().then(blob => {
    document.body.style.background = `url(${URL.createObjectURL(blob)})`;
  });
});

When users complain about a blank screen, just say, "Please upgrade your ancient browser."

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

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