Building Your Learning Module...
Getting things ready for you!
Find videos you like?
Save to resource drawer for future reference!
Clean code is code that is easy to read, easy to understand, and easy to maintain. It's not just about making code workβit's about making code that other developers (including future you) can quickly grasp and modify.
Names should reveal intent
Functions should do one thing
Don't Repeat Yourself
Code should be self-explanatory
// Unclear purpose
let d; // elapsed time in days
let x = 10;
function calc(a, b) { ... }
// Abbreviations
let usrCnt = 5;
let btn = document.querySelector('.btn');
function getPrdDta() { ... }
// Generic names
let data;
let temp;
let result;
function doStuff() { ... }// Clear and descriptive
let elapsedTimeInDays;
let maxRetryCount = 10;
function calculateTotalPrice(items, taxRate) { ... }
// Full words
let userCount = 5;
let submitButton = document.querySelector('.btn');
function getProductData() { ... }
// Specific names
let userProfile;
let temporaryUserId;
let validatedEmail;
function sendConfirmationEmail() { ... }// Does too many things
function processUser(data) {
// Validate
if (!data.email || !data.name) {
throw new Error('Invalid data');
}
// Transform
const user = {
email: data.email.toLowerCase(),
name: data.name.trim(),
createdAt: Date.now()
};
// Save to database
db.users.insert(user);
// Send email
sendEmail(user.email, 'Welcome!');
// Log
console.log('User created:', user.id);
return user;
}// Each function does ONE thing
function validateUserData(data) {
if (!data.email || !data.name) {
throw new Error('Invalid data');
}
}
function transformUserData(data) {
return {
email: data.email.toLowerCase(),
name: data.name.trim(),
createdAt: Date.now()
};
}
function createUser(data) {
validateUserData(data);
const user = transformUserData(data);
const savedUser = saveUser(user);
sendWelcomeEmail(savedUser);
logUserCreation(savedUser);
return savedUser;
}// Repeated validation logic
function createAdmin(data) {
if (!data.email) {
throw new Error('Email required');
}
if (!/^[^@]+@[^@]+$/.test(data.email)) {
throw new Error('Invalid email');
}
// create admin...
}
function createUser(data) {
if (!data.email) {
throw new Error('Email required');
}
if (!/^[^@]+@[^@]+$/.test(data.email)) {
throw new Error('Invalid email');
}
// create user...
}
function updateUser(data) {
if (!data.email) {
throw new Error('Email required');
}
if (!/^[^@]+@[^@]+$/.test(data.email)) {
throw new Error('Invalid email');
}
// update user...
}// Extract to reusable function
function validateEmail(email) {
if (!email) {
throw new Error('Email required');
}
if (!/^[^@]+@[^@]+$/.test(email)) {
throw new Error('Invalid email');
}
}
function createAdmin(data) {
validateEmail(data.email);
// create admin...
}
function createUser(data) {
validateEmail(data.email);
// create user...
}
function updateUser(data) {
validateEmail(data.email);
// update user...
}// Stating the obvious
let i = 0; // Initialize i to 0
i++; // Increment i
// Outdated comments
// Returns user name (actually returns full object)
function getUser() {
return { name: 'John', age: 30 };
}
// Commented-out code (delete it!)
function process() {
// const x = 10;
// doSomething(x);
doSomethingElse();
}
// Noise comments
// ======================
// USER SERVICE
// ======================// Explain WHY, not WHAT
// Using binary search because dataset
// is sorted and can be huge (100k+ items)
function findUser(id) { ... }
// Warn about consequences
// WARNING: This operation is expensive
// Consider caching the result
function calculateComplexMetrics() { ... }
// Clarify complex algorithms
// Implemented using Knuth-Morris-Pratt algorithm
// Time: O(n+m), Space: O(m)
function patternMatch(text, pattern) { ... }
// Legal/license comments
/**
* Copyright (c) 2024 Company Name
* Licensed under MIT
*/Names reveal intent
Avoid abbreviations
One thing per function
10-20 lines ideal
Don't repeat yourself
Extract reusable code
Code should explain itself
Comment WHY, not WHAT