Clean Code
Best Practices
Programming
Software Engineering
Career
Ask anything about this article
Hi! I've read this article.
What would you like to know?
@farhan
Not all clean code advice is created equal. Some principles save you hours of debugging; others are academic exercises. Here's what actually matters.
The single most impactful practice:
typescript// Bad
const d = new Date();
const u = await getU(id);
const r = u.orders.filter(o => o.s === 'active');
// Good
const currentDate = new Date();
const user = await getUserById(userId);
const activeOrders = user.orders.filter(order => order.status === 'active');
typescript// Functions should say what they DO
function calculateShippingCost(weight: number, destination: string): number
function sendWelcomeEmail(user: User): Promise<void>
function isEligibleForDiscount(order: Order): boolean
// NOT what they ARE
function shipping(w, d) // Unclear
function processUser(u) // "Process" means nothing
function handleData(data) // Handle how?
typescript// Bad: does 3 things
async function createUserAndSendEmailAndLog(data: UserInput) {
const user = await db.users.create(data);
await emailService.send(user.email, 'welcome');
logger.info('User created', { userId: user.id });
return user;
}
// Good: each function has one responsibility
async function createUser(data: UserInput): Promise<User> {
const user = await db.users.create(data);
await onUserCreated(user); // Event-driven side effects
return user;
}
async function onUserCreated(user: User) {
await sendWelcomeEmail(user);
logUserCreation(user);
}
typescript// Bad: swallowing errors
async function getUser(id: string) {
try {
return await db.users.findById(id);
} catch (err) {
console.log(err); // π₯ Error is lost!
return null;
}
}
// Good: let errors propagate, handle at boundaries
async function getUser(id: string): Promise<User> {
const user = await db.users.findById(id);
if (!user) throw new NotFoundError(`User ${id} not found`);
return user;
}
// Handle at the API boundary
app.get('/users/:id', async (req, res) => {
try {
const user = await getUser(req.params.id);
res.json(user);
} catch (err) {
if (err instanceof NotFoundError) {
res.status(404).json({ error: err.message });
} else {
res.status(500).json({ error: 'Internal server error' });
logger.error(err); // Log unexpected errors
}
}
});
typescript// Bad: tests implementation details
test('should call database with correct SQL', () => {
createUser({ name: 'Farhan' });
expect(db.query).toHaveBeenCalledWith(
'INSERT INTO users (name) VALUES (?)', ['Farhan']
);
});
// Good: tests behavior
test('should create a user and return it with an ID', async () => {
const user = await createUser({ name: 'Farhan', email: 'test@test.com' });
expect(user.id).toBeDefined();
expect(user.name).toBe('Farhan');
expect(user.email).toBe('test@test.com');
// Verify it actually persisted
const fetched = await getUser(user.id);
expect(fetched).toEqual(user);
});
The Rule of Three:
1st time: Just write the code
2nd time: Note the duplication (maybe copy-paste is fine)
3rd time: Now extract a shared abstraction
Wrong abstractions are WORSE than duplication.
Clean code isn't about perfection β it's about making your future self's life easier.