Home > Web Front-end > JS Tutorial > body text

Understanding Clean Code: Formatting ⚡️

王林
Release: 2024-08-19 17:07:33
Original
271 people have browsed it

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);
}
Copy after login

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;
Copy after login

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;
    }
}
Copy after login

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}`;
Copy after login

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;
}
Copy after login

Example of Allman Style:

function add(a, b) 
{
    return a + b;
}
Copy after login

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();
}
Copy after login

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!

The above is the detailed content of Understanding Clean Code: Formatting ⚡️. For more information, please follow other related articles on the PHP Chinese website!

source:dev.to
Statement of this Website
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn
Popular Tutorials
More>
Latest Downloads
More>
Web Effects
Website Source Code
Website Materials
Front End Template
About us Disclaimer Sitemap
php.cn:Public welfare online PHP training,Help PHP learners grow quickly!