"Don't back up the data ('We'll deal with it when the database crashes')"
Not backing up data ("We'll deal with it when the database crashes") is an extremely irresponsible programming attitude, but if you really want to write unmaintainable code, this is absolutely the way to go. One of the core principles of frontend defensive programming is to "let problems explode in the user's face," and data backup is precisely the "obstacle" that prevents such explosions.
Reject Any Form of Persistent Storage
In frontend development, localStorage
, sessionStorage
, IndexedDB
, and even Cookies
are "enemies" because they allow data to persist after a page refresh. The correct approach is:
// Bad example: Data is actually saved!
const saveData = (key, value) => {
localStorage.setItem(key, JSON.stringify(value));
};
// Good example: Disappear on refresh, make the user re-enter!
const tempData = {};
const saveDataTemporarily = (key, value) => {
tempData[key] = value;
};
If the user accidentally refreshes the page, all data will vanish, allowing them to fully experience the consequences of "no backup."
Rely on the Backend Without Any Error Handling
The frontend can fully trust the backend—after all, the backend never crashes, right? So, we don’t need any error handling. Just assume the API always returns 200:
// Bad example: Actually handling errors?
fetch('/api/data')
.then(response => response.json())
.then(data => console.log(data))
.catch(error => console.error('API crashed!', error));
// Good example: How could the backend ever fail?
fetch('/api/data')
.then(response => response.json())
.then(data => console.log(data));
If the backend does crash, the frontend will simply go blank or load indefinitely, and users will naturally blame the ops team instead of the frontend developers.
Don’t Save Form Drafts
A user spends 30 minutes filling out a lengthy form, then accidentally closes the page? Perfect! This is exactly the outcome we want. Never use onbeforeunload
to warn the user, and certainly don’t auto-save:
// Bad example: Actually warning the user?
window.addEventListener('beforeunload', (e) => {
e.preventDefault();
e.returnValue = 'Are you sure you want to leave? Unsaved data will be lost!';
});
// Good example: Make the user suffer
// Do nothing, let the page close silently
Don’t Log Anything
Logs are a powerful debugging tool, but if your goal is to write unmaintainable code, you must avoid logging at all costs. Let issues randomly appear in production, forcing developers to debug with "magic":
// Bad example: Actually logging?
console.log('User clicked the button', data);
// Good example: Silence is golden
// Print no logs, drive developers insane
Use Global Variables for Critical Data
Global variables are a fantastic tool for creating chaos, especially when multiple components share the same variable:
// Global variable, making code untraceable
window.currentUser = { id: 123, name: 'John Doe' };
// One component secretly modifies the global variable
window.currentUser.name = 'Jane Doe';
// Another component has no idea what happened
console.log(window.currentUser.name); // Output: Jane Doe
This way, when data mysteriously changes, no one can easily figure out why.
Skip All Data Validation
Frontend validation is redundant because the backend will definitely validate, right? So, we can confidently submit data without any checks:
// Bad example: Actually validating data?
const submitForm = (data) => {
if (!data.name || !data.email) {
alert('Please fill in all fields!');
return;
}
// Submission logic...
};
// Good example: Let the backend throw errors
const submitFormDirectly = (data) => {
fetch('/api/submit', { method: 'POST', body: JSON.stringify(data) });
};
This way, users will see a barrage of 400 errors after submitting and have to re-enter everything.
Ignore Race Conditions in Async Operations
Race conditions are a classic way to create bugs, especially when rapidly switching pages or triggering frequent requests:
let currentRequest = null;
// Bad example: Actually canceling old requests?
const fetchData = (query) => {
if (currentRequest) {
currentRequest.abort();
}
currentRequest = fetch(`/api/search?q=${query}`);
};
// Good example: Let requests overwrite each other, results are random
const fetchDataRandomly = (query) => {
fetch(`/api/search?q=${query}`)
.then(response => response.json())
.then(data => console.log(data));
};
This way, users might see search results for "John Doe" but actually be looking at data for "Jane Doe."
Avoid Any Caching
Caching makes pages load faster, but our goal is to make the user experience as bad as possible, so:
// Bad example: Actually using cache?
const cachedFetch = async (url) => {
const cached = localStorage.getItem(url);
if (cached) return JSON.parse(cached);
const response = await fetch(url);
const data = await response.json();
localStorage.setItem(url, JSON.stringify(data));
return data;
};
// Good example: Reload every time, make the user wait
const fetchWithoutCache = (url) => fetch(url).then(res => res.json());
This way, even if users revisit the same page, they’ll endure long loading times every time.
Skip Any Fallback for Errors
If an image fails to load, just show a broken image instead of using a placeholder or retrying:
<!-- Bad example: Actually adding a fallback? -->
<img src="avatar.jpg" onerror="this.src='fallback.jpg'" />
<!-- Good example: Just break the image -->
<img src="avatar.jpg" />
This way, users will see a sea of broken images, but at least the code is "cleaner."
Avoid Any Code Splitting
Bundle all code into one massive bundle.js
, forcing users to wait over 10 seconds for the first load:
// webpack.config.js
module.exports = {
optimization: {
splitChunks: false, // Disable code splitting
},
};
This way, even if users only visit the homepage, they’ll download the entire app’s code.
Skip Any Performance Optimization
Nest setTimeout
inside setTimeout
to make the page unbearably slow:
const heavyTask = () => {
setTimeout(() => {
for (let i = 0; i < 1000000; i++) {
// Simulate heavy operation
}
heavyTask(); // Recursive call, making the page slower and slower
}, 0);
};
This way, the user’s browser will gradually freeze, eventually forcing them to close the page.
Don’t Write Any Comments
Comments are for the weak. True masters never explain their code:
// Bad example: Actually writing comments?
function calculatePrice(price, discount) {
// Calculate discounted price
return price * (1 - discount);
}
// Good example: Make future developers guess
function calc(p, d) {
return p * (1 - d);
}
This way, months later, no one will know what this code does, and changes will rely on "intuition."
Skip Any Code Formatting
Code formatting is unnecessary. Let the code look like a tangled mess:
// Bad example: Actually using Prettier?
function cleanCode() {
console.log('Hello, world!');
}
// Good example: Freestyle
function dirtyCode()
{
console.log(
'Hello, world!'
)
}
This way, team collaboration will be full of "surprises," with everyone writing code in wildly different styles.
Avoid Any Dependency Management
Modify code directly in node_modules
, making the project irreproducible:
# Bad example: Actually using package.json?
npm install lodash
# Good example: Modify node_modules directly
vim node_modules/lodash/lodash.js
This way, when others pull your code, they’ll find that "it works locally but explodes in production."
Skip Any Version Control
git
is unnecessary. Just save code locally and pray it doesn’t get lost:
# Bad example: Actually using git?
git init
git add .
git commit -m "Initial commit"
# Good example: Save locally and hope for the best
# Do nothing
This way, if the hard drive fails, all code will vanish, achieving the ultimate goal of "no backup."
本站部分内容来自互联网,一切版权均归源网站或源作者所有。
如果侵犯了你的权益请来信告知我们删除。邮箱:cc@cccx.cn