DEV Community

Cover image for 🧹 The Art of Writing Clean Code: Why It Matters and How to Do It
Hadil Ben Abdallah
Hadil Ben Abdallah

Posted on

🧹 The Art of Writing Clean Code: Why It Matters and How to Do It

In the world of programming, clean code is like a breath of fresh air. 🌬️ It's not just about getting your code to work; it's about making it understandable, maintainable, and enjoyable for everyone who encounters it. So, let's dive into what clean code is, why it's essential, and how you can start writing it today! πŸš€

What is Clean Code? πŸ€”

Clean code is code that is easy to read, understand, and modify. Think of it as the difference between a well-organized closet and a chaotic pile of clothes. 🧺 A clean codebase is structured, logically organized, and uses consistent naming conventions. It's like giving your future self (and your teammates) a gift that keeps on giving! 🎁

# Don't ❌
def calc(n,p):
    return n+(p*0.2)  # What does this calculate?

# Do βœ…
def calculate_total_with_tax(net_price, price):
    tax_rate = 0.2
    return net_price + (price * tax_rate)
Enter fullscreen mode Exit fullscreen mode

Why Should You Care? 🌟

1. Improved Readability πŸ“–

Clean code is easier to read and understand, which means you spend less time deciphering your own work. This is especially beneficial when you revisit a project after a few months (or years!). It's like reading a book with a clear plot instead of a jumbled mess of ideas.

# Don't ❌
def p(d, t):
    return d * t

# Do βœ…
def calculate_price(product_discount, tax_rate):
    """Calculate final price after discount and tax"""
    return product_discount * tax_rate
Enter fullscreen mode Exit fullscreen mode

2. Easier Maintenance πŸ”§

Bugs are inevitable, but clean code makes fixing them a breeze. When your code is organized and logical, you can quickly pinpoint issues and implement solutions. Plus, you'll save your teammates (and future you) a lot of headaches!

// Don't ❌
function processUserData(d) {
    let r = d.split(',');
    let f = r[0];
    if(f == "active") return true;
    return false;
}

// Do βœ…
function isUserActive(userData) {
    const [userStatus] = userData.split(',');
    return userStatus === 'active';
}
Enter fullscreen mode Exit fullscreen mode

3. Better Collaboration 🀝

Working in teams? Clean code fosters collaboration. When everyone adheres to the same standards, it's easier for team members to understand each other's work, making collaboration smoother and more efficient.

# Don't ❌
class dataProc:
    def proc_data(self, d):
        self.d = d
        # Hard to understand what this does
        return [x*2 for x in d if x>0]

# Do βœ…
class DataProcessor:
    def process_positive_numbers(self, numbers):
        """Double all positive numbers in the list"""
        self.data = numbers
        return [number * 2 for number in numbers if number > 0]
Enter fullscreen mode Exit fullscreen mode

4. Increased Productivity ⏱️

Spending less time figuring out what your code does means you can focus on adding new features or improving existing ones. In the end, clean code leads to higher productivity and a more enjoyable coding experience!

// Don't ❌
function handle(x) {
    if(x.t === 'special') {
        let p = x.p * 1.2;
        if(p > 100) return p * 0.9;
        return p;
    }
    return x.p;
}

// Do βœ…
function calculatePrice(product) {
    if (!product.isSpecialItem) {
        return product.price;
    }

    const priceWithMarkup = product.price * 1.2;
    const discountThreshold = 100;
    const discountRate = 0.9;

    if (priceWithMarkup > discountThreshold) {
        return priceWithMarkup * discountRate;
    }

    return priceWithMarkup;
}
Enter fullscreen mode Exit fullscreen mode

How to Write Clean Code ✍️

1. Use Meaningful Names πŸ“›

Choose variable and function names that clearly describe their purpose. Instead of naming a variable x, use totalPrice. It's much easier to understand what totalPrice represents!

# Don't ❌
x = a * b / 100

# Do βœ…
discount_percentage = (discount_amount * base_price) / 100
Enter fullscreen mode Exit fullscreen mode

2. Keep Functions Small πŸ“

Aim for functions that do one thing and do it well. If a function is doing too much, it's time to break it down. This makes your code more modular and easier to test.

// Don't ❌
function processOrder(order) {
    // Validate
    if (!order.items) throw new Error('No items');
    if (!order.user) throw new Error('No user');

    // Calculate total
    let total = 0;
    order.items.forEach(item => total += item.price);

    // Apply discount
    if (order.discount) total *= 0.9;

    // Save to database
    database.save(order);
}

// Do βœ…
function processOrder(order) {
    validateOrder(order);
    const total = calculateTotal(order.items);
    const finalPrice = applyDiscount(total, order.discount);
    saveOrder(order, finalPrice);
}
Enter fullscreen mode Exit fullscreen mode

3. Follow a Consistent Style 🎨

Consistency is key! Adopting a coding style guide (like Airbnb for JavaScript) ensures that your code looks the same throughout your project. This makes it easier for you and others to read and understand.

# Don't ❌
class userManager:
    def GetUser(self,ID):
        pass
    def Save_USER(self,data):
        pass

# Do βœ…
class UserManager:
    def get_user(self, user_id):
        pass

    def save_user(self, user_data):
        pass
Enter fullscreen mode Exit fullscreen mode

4. Comment Wisely πŸ’¬

Comments are great for explaining why certain decisions were made, but avoid commenting on obvious things. If your code is clean enough, it should speak for itself!

// Don't ❌
// Initialize counter to zero
let counter = 0;

// Do βœ…
// Counter must start from 0 to comply with legacy system requirements
let transactionCounter = 0;
Enter fullscreen mode Exit fullscreen mode

5. Refactor Regularly πŸ”„

Don't be afraid to revisit your code. Refactoring is an essential part of the development process. Regularly improve your code's structure, making it cleaner and more efficient over time.

# Before Refactoring ❌
def process_data(data):
    result = []
    for i in range(len(data)):
        if data[i] > 0:
            if data[i] % 2 == 0:
                result.append(data[i] * 2)
            else:
                result.append(data[i])
    return result

# After Refactoring βœ…
def process_data(data):
    def is_positive(number):
        return number > 0

    def is_even(number):
        return number % 2 == 0

    def double_if_even(number):
        return number * 2 if is_even(number) else number

    return [double_if_even(num) for num in data if is_positive(num)]
Enter fullscreen mode Exit fullscreen mode

In Conclusion πŸŽ‰

Writing clean code is an investment in your future self and your team. It leads to better readability, easier maintenance, and increased productivity. So, the next time you sit down to code, remember the principles of clean coding! Your teammates (and future you) will thank you. πŸ™

Happy coding! πŸ’»

Thanks for reading!

Made with πŸ’™ by Hadil Ben Abdallah.

GitHub LinkedIn CodePen Daily.dev X

Top comments (0)