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)