Intro
Are you tired of writing boring, predictable code? Ready for a change? Well, buckle up! This guide provides you with 10 pieces of advice that will turn your codebase into a wild rollercoaster ride for anyone brave enough to maintain it! Warning: the advice in this article is sarcastic and should be reversed if you value your sanity (no shit, Sherlock).
1. Wet your code
Do you remember that smart code snippet that handles user authentication you copied from StackOverflow? I want you to copy/paste that snippet all over the project. Don't wrap it in a function that has a meaningful name that can be called whenever needed. Don't make your code DRY. Why? The main benefit is whenever you find a bug in this snippet, you will go through a long and amusing journey of updating this snippet everywhere it's written. So Much Fun. It's also another way to force you and your team to revise your code from time to time. Your team will surely appreciate that.
2. Write smart one-liners
Have you earned respect in your team yet? No? Here is what you need to do, fill the codebase with smart one-liners that only smart people like you can understand.
Let me show you an example I like a lot, the following dumb simple easy-to-understand code wastes 3 lines from our precious javascript files:
const obj = {};
If (x) { obj.x = x; }
If (y) { obj.y = y; }
Let's upgrade/optimize this code, for example, look at how compact and smart this alternative is:
const obj = { …(x && { x }), …(y && { y}) };
After you adapt yourself to this cryptic coding style, you will get 70x respected within your team, thank me later.
3. Be inconsistent and unconventional
As an extension to the last advice, I want you to break out of conventions and liberate yourself from chains. Some people whine too much about how your code should be consistent and follow agreed-upon conventions. Those "clean coders" police are holding you back. Examples:
- Don't limit yourself to a single casing style within a project, make sure your functions have at least 2 casing styles like
camelCase
andsnake_case
. - Also, your function names shouldn't follow the same naming style. That's too dull, some function names should be verbs, some should be nouns, and some should be adverbs!
- Always mix. Use a mix of callbacks, promises, async/await code. Use a mix of regular and arrow functions. Use mix classes and function constructors,...etc Within your programming language community, you would usually find one or two coding styling guides to chain you, ignore those guides, and Just Be Creative!
4. Don't comment your code
A wise man once said: "Good code does not need comments". That's 100% true. Don't insult yourself by putting comments in your good code. Do you remember that 200-line critical function that handles user payments in the application? this one particularly shouldn't be commented, and all variables in it should have 2 or 3 character names. This function is too critical, so it should be optimized more than anything else!
5. Nest your code
Have you ever heard of "Code Aesthetics"? It's about making our code beautiful and amusing to look at. One way to achieve this is by making 3+ nesting levels of your code blocks. For example, don't write dull code like that:
function checkDiscountEligibility(user) {
if (!user) return console.log('User data is missing')
if (!user.age) return console.log('User age is required')
if (user.age < 18) return console.log('User must be at least 18 years old')
if (!user.membership) return console.log('Membership status is required')
if (user.membership !== 'gold') return console.log('Only gold members are eligible for a discount')
applyDiscount(user)
}
Instead try writing a beautiful skewed pyramid shaped code like this:
function checkDiscountEligibility(user) {
if (user) {
if (user.age) {
if (user.age >= 18) {
if (user.membership) {
if (user.membership === 'gold') {
applyDiscount(user)
} else {
console.log('Only gold members can get discount')
}
} else {
console.log('Membership status is required')
}
} else {
console.log('User must be at least 18 years old')
}
} else {
console.log('User age is required')
}
} else {
console.log('User data is missing')
}
}
6. Hardcode stuff
The more you Hardcode, the more Hardcore you are. Always hardcode configuration values, constants, and secrets(especially secrets) instead of grouping them in a config file or something as simple as a.env
file. This will make your code comprehensive, have fewer dependencies, and also efficient(because no need to do additional lookups). You might ask what if we want to have different values for different environments? Simple do if conditions on the environment everywhere throughout the code. like this:
let lifeSecret = ""
if (process.env.NODE_ENV === 'development'){
lifeSecret = "dev_blablabblalasec"
}
else if (process.env.NODE_ENV === 'production'){
lifeSecret = "prod_blablahardcoresec"
}
Hint: Don't follow 12 factor app rule about organizing configs, those people are not efficient.
7. Don't handle errors
Errors are so overrated. Don't think too much about errors and handling them. Always focus on happy scenarios, because again, handling errors implicitly means that your code is error-prone, so please don't insult yourself. Some programming languages like Rust and Go deal with errors as first-class citizens to promote error handling explicitly. I'll give you examples but please this is only to show you how self in-confident those language developers are:
Go:
result, err := divide(4, 2)
if err != nil {
fmt.Println("Error:", err)
} else {
fmt.Println("Result:", result)
}
Rust:
match read_file_to_string("example.txt") {
Ok(contents) => println!("File contents: {}", contents),
Err(e) => println!("Error reading file: {}", e)
}
8. Depend on global variables
Maximize the dependence of global variables in your code. Why pass stuff as function arguments when you can make your entire codebase a creative playground?
For example:
const databaseConnection = require("database.js");
function fetchUserData(userId) {
databaseConnection.query(`SELECT * FROM users WHERE id = ${userId}`);
}
See how we completely ignore dependency injection and save an additional parameter by pulling databaseConnection
from thin air into the function? Some people would argue that this has multiple drawbacks, like:
- It makes the code less predictable
- It makes this function untestable
- 1. Preventing the application of the Unit of Work pattern to combine this function with others in a single transaction. But who needs predictability when you can embrace spontaneous creativity? And testing? Who has time for testing in 2024? We are developers, not testers! I'm 100% sure those critics don't do testing themselves. And Unit of Work pattern? Sounds like extra work to me! Just... ignore them and enjoy the freedom of your creative coding!
9. Mutate objects by passing them to magic functions
This is one of my favorites. I find a lot of creative people doing it without even reading my article.
Look at this dull immutable version:
const { originalDate } = require("./dates.js")
function addYear(date) {
const newDate = new Date(date.getTime()); // cloning the date object
newDate.setFullYear(newDate.getFullYear() + 1);
return newDate;
}
console.log(originalDate); // 2024-06-24T00:00:00.000Z
let updatedDate = addYear(originalDate);
console.log(originalDate); // 2024-06-24T00:00:00.000Z (still as is)
console.log(updatedDate); // 2025-06-24T00:00:00.000Z
Boring, right? Now, here's the "upgrade":
const { originalDate } = require("./dates.js")
function addYear(date) {
date.setFullYear(date.getFullYear() + 1);
}
console.log(originalDate); // 2024-06-24T00:00:00.000Z
addYear(originalDate)
console.log(originalDate); // 2025-06-24T00:00:00.000Z (ta da!)
Isn't it thrilling? Now, anyone looking at originalDate
will have no idea how and where it's value got mutated. Perfect!
10. Don't write secure code
A lot of paranoid devs worry too much about security, but this paranoia weakens your relationship with your app users. Learn to love your users, and you won't love them until you trust them completely by writing code like this:
app.post('/register', async (req, res) => {
let userData = { role: "user", ...req.body };
await User.create(userData);
res.send('User created');
});
Now, imagine a request like this (but don't worry, your users would never do that of course):
`curl -X POST http://localhost:3000/register -H "Content-Type: application/json" -d '{"username": "hacker", "role": "admin"}'`
And this is what would be stored in our modern NoSQL store:
{ role: "admin", username: "hacker"}
See how effortless that is? Just merge everything from the request body into your sensitive data object. Who needs validation or sanitization? Trust your users—they always have your best interests at heart, right?
Always think good of your dear users. After all, what's the worst that could happen?
Conclusion
Congratulations! You've now learned the art of writing code that's sure to keep your fellow developers entertained and on their toes. By following these anti-patterns, you can inject a bit of excitement into your workday and create a codebase that's as unpredictable as it is "creative." Remember, consistency, maintainability, and security are just suggestions. True creativity lies in embracing the chaos and trusting that your users and colleagues will understand your genius. Happy coding!
Top comments (0)