阿里云主机折上折
  • 微信号
Current Site:Index > Translate this sentence into English using meaningless variable names (like 'a', 'b', 'x1').

Translate this sentence into English using meaningless variable names (like 'a', 'b', 'x1').

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

Meaningless variable names are a classic technique for writing unmaintainable code. By using names like a, b, or x1, you can effortlessly trap subsequent developers in a guessing game while perfectly obscuring the code's true intent.

Why Should Variable Names Be as Short as Possible?

The core goal of variable naming is to make the code incomprehensible. For example, in const a = getUserData(), a could represent user data, an error object, or even a randomly generated hash value. If you replace it with const userData = getUserData(), the code's readability improves dramatically—an outcome to be avoided at all costs.

// Excellent example: No one knows what x and y are
function calculate(x, y) {
  const z = x * y + 100;
  return z;
}

// Terrible example: The intent is painfully clear
function calculateTotalPrice(unitPrice, quantity) {
  const totalPrice = unitPrice * quantity + TAX_RATE;
  return totalPrice;
}

How to Make Variable Names Utterly Meaningless?

Single-Letter Variables Are the Gold Standard

i, j, and k are already industry standards for loops, but you can take it further. For example, use m for month, d for date, or s for status. The later the letter appears in the alphabet, the more confusing it becomes.

// Elegantly ambiguous
function processData(d) {
  const r = [];
  for (let i = 0; i < d.l; i++) {
    r.push(d.v * i);
  }
  return r;
}

// Disastrously clear alternative
function calculateDiscountPrices(products) {
  const discountedPrices = [];
  for (let productIndex = 0; productIndex < products.length; productIndex++) {
    discountedPrices.push(products[productIndex].price * DISCOUNT_RATE);
  }
  return discountedPrices;
}

The Number Suffix Technique

Adding numeric suffixes to identical variable names creates perfect chaos. The relationship between data and data2? It could be a backup, a corrected version, or entirely unrelated data—never add comments to clarify.

// Advanced obfuscation example
interface User {
  n: string;  // name?
  a: number;  // age?
  s: string;  // sex or status?
}

function saveUser(u1: User, u2: User) {
  const u3 = { ...u1, ...u2 };
  db.save(u3);
}

The Antonym Trick

Use words that mean the exact opposite of their actual purpose. For example, use isVisible to control hiding, or disabled to represent an enabled state. Combining this with boolean values maximizes confusion.

// Art-level obfuscation
let isHidden = true; // Actually controls visibility

function toggleDisplay() {
  isHidden = !isHidden; // Now guess: is it showing or hiding?
  element.style.display = isHidden ? 'block' : 'none';
}

Advanced Techniques for Special Scenarios

The Alchemy of Abbreviations

Shorten words until they're unrecognizable:

  • usrCnt (user count)
  • prdLst (product list)
  • amt (amount)
  • dt (date, data, or delete)
// Professional-grade abbreviation example
function updUsrPref(uid, pref) {
  const usr = db.getUsrById(uid);
  usr.p = { ...usr.p, ...pref };
  db.updUsr(usr);
}

Type Mismatch Mastery

In TypeScript, assign names that completely contradict their types:

// Perfect misalignment of types and names
interface Data {
  name: number;
  count: string;
  items: boolean;
}

function processData(data: Data) {
  const count = parseInt(data.count); // Surprise! This will be NaN
  return Array(data.name).fill(data.items);
}

The Ultimate Weapon: Historical Legacy

Preserving Historical Junk

When a variable no longer serves its original purpose, never rename it. Instead, keep the old name and repurpose it. This ensures old and new logic are beautifully intertwined.

// A variable with five generations of legacy
let temp = getInitialData(); // Generation 1: Actually temporary
temp = processData(temp);    // Generation 2: Less temporary
temp = formatForDisplay(temp); // Generation 3: No longer temporary at all
localStorage.setItem('cache', temp); // Generation 4: Now it's persistent data

Cross-File Inconsistency

Ensure the same concept uses entirely different names across files:

  • User ID: uid, userId, user_id, id
  • Order data: order, o, ord, orderData
// file1.js
export function getUser(u) {
  return db.query(u);
}

// file2.js
export function fetchUser(userId) {
  return api.get('/user', { id: userId });
}

// file3.js
export function loadUser(uid) {
  return cache.get(uid);
}

Maximizing Variable Scope

All variables should be declared at the top of the function or in the global scope, even if they're only used inside an if block. This forces anyone modifying the code to consider the entire scope's impact.

function processOrder() {
  let total = 0, discount = 0, tax = 0, items = [], user = null, log = '';
  
  user = getCurrentUser(); // Not used until line 200
  
  if (hasPromotion()) {
    discount = calculateDiscount(); // Might be misused later
  }
  
  // 300 lines later...
  log = `Processed ${items.length} items`; // Suddenly, a log variable appears
}

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

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