Understanding Clean Code: Formatting ⚡️

alisamir

Ali Samir

Posted on August 18, 2024

Understanding Clean Code: Formatting ⚡️

In software development, code is not only for machines but also for humans.

Proper code formatting is crucial for readability and maintainability.

Clean Code's Chapter 5 discusses these principles, focusing on the importance of formatting for professional code.


📌 Why Formatting Matters

Proper formatting is not just about aesthetics; it's about clarity. Well-formatted code:

  • Improves readability: Other developers (or your future self) can quickly grasp what the code does.

  • Enhances maintainability: Cleanly formatted code is easier to update, refactor, and debug.

  • Promotes consistency: Consistent code is predictable, reducing the cognitive load for anyone reading it.


📌 Key Principles of Code Formatting

🔻 1. Vertical Openness: Grouping Related Code Together

Vertical openness refers to using blank lines to separate distinct blocks of code, making it easier to distinguish different sections.

Example:

function processOrder(order) {
    // Validate the order
    if (!validateOrder(order)) {
        throw new Error("Invalid order");
    }

    // Process payment
    const paymentResult = processPayment(order);

    // Update inventory
    updateInventory(order);

    // Notify customer
    notifyCustomer(order);
}
Enter fullscreen mode Exit fullscreen mode

In this example, each step in the processOrder function is separated by a blank line, clearly delineating the different phases of the process.


🔻 2. Horizontal Openness: Aligning Code for Clarity

Horizontal openness involves aligning code horizontally to make it more readable, especially when dealing with similar or related statements.

Example:

const productName  = "Laptop";
const productPrice = 999.99;
const productStock = 50;
Enter fullscreen mode Exit fullscreen mode

Aligning the variable declarations in this manner makes it easier to see what each variable represents at a glance.


🔻 3. Indentation: Structuring Code Hierarchically

Indentation is key to reflecting the hierarchical structure of code. It helps readers quickly identify blocks of code that belong together, such as loops, conditionals, and functions.

Example:

function calculateDiscount(price) {
    if (price > 100) {
        return price * 0.1;
    } else {
        return 0;
    }
}
Enter fullscreen mode Exit fullscreen mode

Here, the if-else structure is indented to indicate that the return statements are part of the conditional logic.


🔻 4. Line Length: Keeping It Manageable

Long lines of code can be hard to read and understand. The general rule is to keep lines under 80-100 characters. If a line is too long, consider breaking it up.

Example:

// Instead of this:
const orderSummary = `Order for ${customer.name}, Total: $${order.total}, Items: ${order.items.length}`;

// Do this:
const orderSummary = `Order for ${customer.name}, 
    Total: $${order.total}, 
    Items: ${order.items.length}`;
Enter fullscreen mode Exit fullscreen mode

Breaking the string across multiple lines makes it more readable, especially if the string contains multiple variables.


🔻 5. Consistent Bracing: Reducing Clutter

Bracing style is another area where consistency is crucial. The two common styles are:

  • K&R Style: Opening brace on the same line as the statement.
  • Allman Style: Opening brace on a new line.

Example of K&R Style:

function add(a, b) {
    return a + b;
}
Enter fullscreen mode Exit fullscreen mode

Example of Allman Style:

function add(a, b) 
{
    return a + b;
}
Enter fullscreen mode Exit fullscreen mode

Choose a style and stick to it throughout your codebase. Consistency is more important than the specific style.


🔻 6. Avoid Dense Code: Leave Room to Breathe

Dense code, where too many operations are crammed into a small space, can be hard to read. Spread out your code to make it more approachable.

Example:

// Dense code
if (user.isLoggedIn) { user.showDashboard(); }

// Better
if (user.isLoggedIn) {
    user.showDashboard();
}
Enter fullscreen mode Exit fullscreen mode

The second version is more readable because the function call is on a separate line from the condition.



Conclusion ✅

Formatting is important for code readability and maintainability.

Following the principles in Clean Code, you can make your JavaScript code more professional and easier to understand and work with.

Happy Coding!

💖 💪 🙅 🚩
alisamir
Ali Samir

Posted on August 18, 2024

Join Our Newsletter. No Spam, Only the good stuff.

Sign up to receive the latest update from our blog.

Related