
- Clean Code - Home
- Clean Code - Best Practices & Principles
- Clean Code - Naming Conventions
- Clean Code - Comments & Documentation
- Clean Code - Testing Practice
- Clean Code - SOLID Principles
- Clean Code - Design Patterns
- Clean Code - Code Smells
- Clean Code - Refractoring
- Clean Code Useful Resources
- Clean Code - Useful Resources
- Discuss Clean Code
Clean Code - Best Practices & Principles
In the software development, writing clean code is important. Because clean code makes code readable and maintainable. It improves the overall quality of the codebase and makes collaboration easier among developers.
For writing Clean Code, we need to follow some best practices and principles. This practice makes code clear, simple, and consistent. Here are some of principles −
DRY - Don't Repeat Yourself
The first principle we will learn is DRY principle.DRY stands for "Don't Repeat Yourself." It basically means that if you find yourself copying and pasting code or you are writing the same logic multiple times, then you're doing it wrong. Instead of that, make a function and add the repeating code in that function, and use it.
Example
Imagine you're working on a to-do list app. You notice for filtering out the completed task you have two different functions, due tasks, and overdue tasks, and each function is doing the same check on task status. By refactoring, you can create one function called filterTasks that takes a parameter to state the filter type. This way, you're not repeating the same logic in three places, and making possible future changes simpler.
function filterTasks(tasks, filterType) { return tasks.filter(task => task.status === filterType); } const dueTasks = filterTasks(tasks, 'due'); const overdueTasks = filterTasks(tasks, 'overdue');
KISS - Keep It Simple, Stupid
KISS stands for "Keep It Simple, Stupid". It says that the simplest solution is always the best. We should avoid unnecessary over complicating things with fancy patterns or structures if a basic solution will do the job easily.
Example
Let's say you are building a login form.For doing that all we need is username and password for security. But, if you add any unnecessary complex design or functionality on login page it wont look good and won't be useful.
function login(username, password) { //login logic } // simple and clean function login(username, password, rememberMe) { //login logic } // unnecessary complexity
YAGNI - You Aren't Gonna Need It
YAGNI stands for "You Aren't Gonna Need It". It is all about focusing on what you actually need now. It is easy to think, Like sometimes we think " I will add this feature because we might need it someday," but that "someday" may never come. Plus, adding extra features may just cause to a maintenance burden.
Example
You are building a recipe app, and you have the idea of adding a feature to rate use comments. If it's not a current requirement it might not benefit to anyone. If a user asks for it you can add it up anytime.
function addRecipe(name, ingredients) { //add recipe logic } // simple and clean function addRecipe(name, ingredients, rating, comment) { //add recipe logic } // unnecessary complexity
Keep Functions Small
A function should do only one thing and that should be done well. If you try to do many things in one function, it becomes harder to understand and test. You should keep your functions small and focused. Avoid adding too many things in one function.
Example
Suppose you built a function that processes a payment, sends an email receipt, and logs the transaction details. These are too much for a single function, So, split this into three separate functions: processPayment, sendEmailReceipt, and logTransaction. Each function does one job, making it easier to manage and test the code.
function processPayment(payment) { //process payment logic //send email receipt //log transaction } // too much for single function //split into three separate functions function sendEmailReceipt(email) { //send email receipt logic } function logTransaction(transaction) { //log transaction logic } function processPayment(payment) { //process payment logic }
Write Comments Sensibly
Comments can be really helpful for explaining complex sections of code but dont overdo it. If your code is clear enough itself, you wont need to comment on every little thing. Use comments to explain why something is done, not what its doing.
Example
Imagine you have to sort a list in a custom order. Leave a comment that explains the criteria and why you chose this approach, avoid commenting on obvious things like "sorting the list." this doesn't really make sense.
//sort list by priority list.sort((a, b) => a.priority - b.priority); //good comment //sorting the list list.sort((a, b) => a.priority - b.priority); //bad comment
Refactor Often
We should not forget to refactor our codebase from time to time. It is a continuous process for improving the structure of your code without changing its behavior. Regularly check and revisit your code and see where you can clean up things and make the code better.
Example
Let's assume you have built an app, where you created your own library for some features and you wrote your own code. But now, you know there are built-in libraries available, So just remove that unnecessary code and use a built-in library. These steps will make the code a lot better and clean.
//your own code function customLibrary() { logic for custom library } //refactor to use built-in library import { builtInLibrary } from 'built-in-library';
Testing
Always keep in mind testing is your safety net it is crucial for you to test your code from time to time. It is what lets you change code with confidence because you know that if something breaks, youll catch it quickly. Always write tests, especially for critical features. Testing helps a lot in maintaining code quality.
Example
Lets say you have a function that calculates discounts on a shopping cart. Write tests to check various scenarios, like when there are no items, when the cart is full-priced items, or when all items are on sale. When someone changes the discount calculation later, these tests will help catch any mistakes you made in your code.
function calculateDiscount(cart) { //discount calculation logic } //write tests test('calculate discount', () => { //test scenarios });
Consistent Style Guidelines
While writing code, it doesn't matter how you format your code or what naming conventions you use, you must use a consistent style. It is not just about being neat and clean; its about making sure everyone on your team reads and understands the code in the same way. It avoids confusion and makes the code-base look more professional.
Example
If you decide to name your variable in snake_case, but in between you start to write in camelCase. This would not look consistent and make your code look messy. Avoiding these mistakes makes code lot better.
let my_variable = 10; //snake_case let myVariable = 10; //camelCase //consistent style let my_variable = 10; let another_variable = 20;
Code Reviews
Code reviews are not meant just for catching bugs or identifying mistakes; theyre also a great way to share knowledge and learn from each other. Dont see them as a chore; see them as an opportunity to improve. Because better suggestions from your teammates can make your code better and you also learn something new from others.
Example
If a teammate reviews your code and suggests a different approach, consider it doing. Even if your code works fine, and doesn't need any improvement. still, take their suggestion those might be cleaner or more efficient. Code reviews help keep code more better and cleaner and efficient.
function calculateTotal(cart) { //total calculation logic } //code review suggestion function calculateTotal(cart) { //total calculation logic //return total }
Conclusion
Applying coding best practices and principles is the best way to maintain a clean code-base. You can improve overall code quality by following certain rules and your code will be more readable, maintainable, and efficient. Whether you are working on a small project or a large project, these principles will help you to write clean code.