0% found this document useful (0 votes)
9 views7 pages

Essential Principles of Clean Code

The article discusses the importance of clean code, emphasizing readability, maintainability, and adherence to best practices for better software quality. It outlines principles such as avoiding hard-coded numbers, using meaningful names, writing short functions, and following established coding standards. Additionally, it advocates for continuous refactoring and the use of version control to enhance collaboration and code management.
Copyright
© All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
9 views7 pages

Essential Principles of Clean Code

The article discusses the importance of clean code, emphasizing readability, maintainability, and adherence to best practices for better software quality. It outlines principles such as avoiding hard-coded numbers, using meaningful names, writing short functions, and following established coding standards. Additionally, it advocates for continuous refactoring and the use of version control to enhance collaboration and code management.
Copyright
© All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF, TXT or read online on Scribd

Clean Code summary

This article emphasizes that writing code is not just about functionality but also
readability, maintainability, and adherence to best practices. It draws from Martin
Fowler's quote: "Anybody can write code that a computer can understand. Good
programmers write code that humans can understand.”

What Is Clean Code?


Clean code is easy to read, understand, and maintain, ensuring software is
functional, readable, maintainable, and efficient over its lifecycle.

Why Is Clean Code Important?


Readability and maintenance: Prioritizes clarity, reducing time to understand
and modify code, leading to faster development.

Team collaboration: Facilitates communication by following coding standards,


allowing developers to understand each other's work easily.

Debugging and issue resolution: Clear structure, meaningful names, and


well-defined functions make it easier to identify and fix problems.

Improved quality and reliability: Reduces errors through structured code and
standards, resulting in higher-quality software.

Principles of Clean Code


1-Avoid Hard-Coded Numbers: Use named constants (e.g., TEN_PERCENT_DISCOUNT =

0.1 ) instead of magic numbers for clarity and easy updates.

Before:

function calculateDiscount(price) {
const discount = price * 0.1; // 10% discount
return price - discount;
}

Clean Code summary 1


After:

function calculateDiscount(price) {
const TEN_PERCENT_DISCOUNT = 0.1;
const discount = price * TEN_PERCENT_DISCOUNT;
return price - discount;
}

2-Use Meaningful and Descriptive Names: Choose names that reveal purpose
(e.g., product_price over price ), making code self-documenting without needing
comments.
Before:

function calculateDiscount(price) {
const TEN_PERCENT_DISCOUNT = 0.1;
const discount = price * TEN_PERCENT_DISCOUNT;
return price - discount;
}

After:

function calculateDiscount(productPrice) {
const TEN_PERCENT_DISCOUNT = 0.1;
const discount_amount = product_price * TEN_PERCENT_DISCOUNT;
return product_price - discount_amount;
}

3-Use Comments Sparingly and Meaningfully: Avoid redundant comments; use


them to explain "why" or unusual behavior, like function docstrings with args,
returns, and warnings.

Before:

Clean Code summary 2


function groupUsersById(userId) {
// This function groups users by id
// ... complex logic ...
// ... more code …
}

After:

function groupUsersById(userId) {
// ... complex logic ...
// ... more code …
}

/**
* Groups users by id to a specific category (1-9).
*
* Warning: Certain characters might not be handled correctly.
* Please refer to the documentation for supported formats.
*
* @param {string} userId - The user id to be grouped.
* @returns {number} The category number (1-9) corresponding to the user i
d.
* @throws {Error} If the user id is invalid or unsupported.
*/

4-Write Short Functions That Do One Thing: Follow the Single Responsibility
Principle (SRP). Break complex functions into smaller ones (e.g.,
separate validateUser , calculateValues , formatOutput ) for better readability, testing, and
maintenance.
Before:

function processData(data) {
// ... validate users...

Clean Code summary 3


// ... calculate values ...
// ... format output …
}

After:

function validateUser(data) {
// ... data validation logic ...
}

function calculateValues(data) {
// ... calculation logic based on validated data ...
}

function formatOutput(data) {
// ... format results for display …
}

5-Follow DRY (Don't Repeat Yourself): Eliminate code duplication by reusing


functions or abstractions (e.g., one calculateProductPrice function instead of separate
ones for books and laptops.

Before:

function calculateBookPrice(quantity, price) {


return quantity * price;
}

function calculateLaptopPrice(quantity, price) {


return quantity * price;
}

After:

Clean Code summary 4


function calculateProductPrice(productQuantity, productPrice) {
return productQuantity * productPrice;
}

6-Follow Established Code-Writing Standards: Adhere to language conventions


(e.g., PEP 8 for Python: snake_case, 4-space indentation; Google JS Style for
JavaScript: camelCase, 2-space indentation). Create internal rules for
organization-specific needs.
Here are some specific examples:

Java:

Use camelCase for variable, function, and class names.

Indent code with four spaces.

Put opening braces on the same line.

Python:

Use snake_case for variable, function, and class names.

Use spaces over tabs for indentation.

Put opening braces on the same line as the function or class declaration.

JavaScript:

Use camelCase for variable and function names.

Use snake_case for object properties.

Indent code with two spaces.

Put opening braces on the same line as the function or class declaration.

7-Encapsulate Nested Conditionals into Functions: Extract complex if/else logic


into separate functions (e.g., getDiscountRate ) for clarity, reusability, and easier
testing.

Before:

Clean Code summary 5


function calculateProductDiscount(productPrice) {
let discountAmount = 0;
if (productPrice > 100) {
discountAmount = productPrice * 0.1;
} else if (productPrice > 50) { // Fixed: assuming it should be productPrice,
not price
discountAmount = productPrice * 0.05;
} else {
discountAmount = 0;
}
const finalProductPrice = productPrice - discountAmount;
return finalProductPrice;
}

After:

function calculateDiscount(productPrice) {
const discountRate = getDiscountRate(productPrice);
const discountAmount = productPrice * discountRate;
const finalProductPrice = productPrice - discountAmount;
return finalProductPrice;
}

function getDiscountRate(productPrice) {
if (productPrice > 100) {
return 0.1;
} else if (productPrice > 50) {
return 0.05;
} else {
return 0;
}
}

Clean Code summary 6


8-Refactor Continuously: Regularly review and refactor your code to improve its
structure, readability, and maintainability. Consider the readability of your code for
the next person who will work on it, and always leave the codebase cleaner than
you found it.

9-Use Version Control: Employ systems like GitHub, GitLab, and Bitbucket to
track changes, enable collaboration, and allow safe refactoring or reversions.

Clean Code summary 7

You might also like