DEV Community

Cover image for 15 Delightful Clean Code Rules That Will Make Your Code Sparkle ✨
Hadil Ben Abdallah
Hadil Ben Abdallah

Posted on

15 Delightful Clean Code Rules That Will Make Your Code Sparkle ✨

Ready to make your code shine brighter than a diamond? Let's dive into these clean code principles that will transform your codebase from "meh" to "magnificent"! 🚀

1. Meaningful Names - Your Code Should Tell a Story 📚

Naming things well is perhaps the most crucial skill in programming. Think of your code as a story - every variable, function, and class should reveal its purpose at first glance. Good names eliminate the need for most comments and make your code self-documenting. When choosing names, imagine you're explaining your code to a colleague six months from now.

# Bad ❌
def p(x):
    return x * 2

# Good ✅
def double_value(number):
    return number * 2
Enter fullscreen mode Exit fullscreen mode

💡 Pro Tip: Use searchable names! Single-letter variables might seem convenient, but try finding all usages of 'k' in a large codebase versus 'user_age'.

2. Functions Should Do One Thing - The Single Responsibility Party 🎯

Just like a good worker bee focuses on its specific task, your functions should have a single, clear purpose. If you find yourself using "and" when describing what your function does, it's probably doing too much. Breaking down complex operations into smaller, focused functions not only makes your code easier to understand but also easier to test and maintain.

// Bad ❌
function saveUser(user) {
    validate(user); save(user); email(user);
}

// Good ✅
function saveValidatedUser(user) {
    if (isValid(user)) { save(user); }
}
Enter fullscreen mode Exit fullscreen mode

💡 Pro Tip: If your function name needs a conjunction (and/or), it's probably violating this principle!

3. Keep Functions Small - Size Does Matter! 📏

Small functions are like bite-sized snacks - easy to digest and enjoy. They're easier to understand, test, and maintain. Each function should fit on your screen without scrolling. If your function is doing multiple things, break it down into smaller, more focused functions that work together.

# Bad ❌
def process(data):
    # 50 lines of processing
    pass

# Good ✅
def process(data):
    cleaned = clean_data(data)
    return analyze(cleaned)
Enter fullscreen mode Exit fullscreen mode

💡 Pro Tip: If you need more than 3 levels of indentation, your function probably needs to be split up!

4. Meaningful Comments - Don't State the Obvious! 💭

Comments should explain the "why," not the "what." Your code should be clear enough to show what it's doing - comments are for explaining intentions, warning of consequences, or clarifying complex algorithms. Think of comments as sticky notes on your code - use them sparingly but meaningfully.

// Bad ❌
// Loop through array
for (int i = 0; i < arr.length; i++)

// Good ✅
// Skip first element - it's a header
for (int i = 1; i < arr.length; i++)
Enter fullscreen mode Exit fullscreen mode

💡 Pro Tip: If you find yourself writing a comment, first try to make the code clearer instead.

5. DRY (Don't Repeat Yourself) - Copy-Paste is Not Your Friend! 🚫

Every piece of knowledge in your system should have a single, unambiguous representation. Duplicated code means duplicated bugs and duplicated maintenance effort. When you find yourself copying and pasting code, stop and think about how you can abstract it into a reusable function or class.

# Bad ❌
if user.age > 18: print("Adult")
if admin.age > 18: print("Adult")

# Good ✅
def is_adult(person): 
    return person.age > 18
Enter fullscreen mode Exit fullscreen mode

💡 Pro Tip: Create a "utils" or "helpers" module for commonly reused functionality.

6. Proper Error Handling - Expect the Unexpected! 🎭

Error handling isn't just about catching errors - it's about managing the unexpected gracefully. Good error handling makes your code more robust and reliable. Think of it as putting safety nets in strategic places, not wrapping your entire code in try-catch blocks.

// Bad ❌
let result = obj.value;

// Good ✅
try {
    let result = obj?.value ?? defaultValue;
} catch (e) {
    log.error('Failed to access value', e);
}
Enter fullscreen mode Exit fullscreen mode

💡 Pro Tip: Create custom error classes for different types of errors - it makes error handling more specific and meaningful.

7. Use Clear Formatting - Pretty Code is Happy Code! 🎨

Consistent formatting makes your code more readable and professional. It's like good typography in a book - it shouldn't draw attention to itself, but it should make the content easier to read and understand. Use automated formatters to maintain consistency across your entire codebase.

# Bad ❌
def calc(x,y): return x+y

# Good ✅
def calculate_sum(x, y):
    return x + y
Enter fullscreen mode Exit fullscreen mode

💡 Pro Tip: Set up automatic formatting in your IDE to handle this for you on save!

8. Keep Classes Small - Class Size Matters Too! 📦

A class should have a single responsibility and a clear purpose. If your class name includes words like "Manager," "Processor," or "Helper," it might be trying to do too much. Think of classes as specialized tools rather than Swiss Army knives.

// Bad ❌
class DataHandler {
    void process() {}
    void validate() {}
    void save() {}
}

// Good ✅
class DataValidator {
    boolean isValid() {}
}
Enter fullscreen mode Exit fullscreen mode

💡 Pro Tip: If your class has more than 200 lines, it's probably doing too much!

9. Use Strong Types - Be Explicit! 💪

Strong typing is like putting guardrails on your code - it prevents you from making silly mistakes and makes your intentions clear. It also provides better tooling support and makes refactoring easier.

// Bad ❌
let data = getData();

// Good ✅
interface User {
    id: number;
    name: string;
}
let user: User = getUser();
Enter fullscreen mode Exit fullscreen mode

💡 Pro Tip: Use TypeScript or type hints in Python to catch type-related bugs early!

10. Keep Dependencies Minimal - Less is More! 🎈

Every dependency you add is a potential point of failure and maintenance burden. Choose your dependencies wisely and keep them to a minimum. Think of dependencies like ingredients in a recipe - use only what you need.

// Bad ❌
import * as lodash from 'lodash'

// Good ✅
import { map, filter } from 'lodash'
Enter fullscreen mode Exit fullscreen mode

💡 Pro Tip: Regularly audit your dependencies and remove unused ones!

11. Follow Consistent Patterns - Be Predictable! 🎯

Consistency in your codebase makes it easier for others (and future you) to understand and maintain. Whether it's naming conventions, file organization, or coding patterns, stick to them throughout your project.

# Bad ❌
get_users()
fetchProducts()
retrieve_orders()

# Good ✅
get_users()
get_products()
get_orders()
Enter fullscreen mode Exit fullscreen mode

💡 Pro Tip: Create a style guide for your project and enforce it with linting tools!

12. Write Testable Code - Trust But Verify! 🧪

Writing testable code forces you to write better code. It encourages loose coupling, clear interfaces, and single responsibility. Think of tests as your code's safety net - they catch you when you fall.

# Bad ❌
def process(): 
    data.save()

# Good ✅
def process(repository):
    return repository.save()
Enter fullscreen mode Exit fullscreen mode

💡 Pro Tip: Write tests first (TDD) to ensure your code is naturally testable!

13. Use Clear Return Values - Be Explicit About What You're Returning! 🎁

Your functions should have clear, consistent return values. If a function can return multiple types, make it explicit. Think of return values as promises - be clear about what you're promising to return.

// Bad ❌
function find(id) {
    return db.query(id);
}

// Good ✅
function find(id) {
    return {
        data: result,
        error: null
    };
}
Enter fullscreen mode Exit fullscreen mode

💡 Pro Tip: Use typed return values and avoid returning null when possible!

14. Keep it Simple - KISS (Keep It Simple, Superstar)! 😘

Simple code is maintainable code. Don't try to be too clever - write code that's easy to understand and modify. Remember, you're writing code for humans to read, not just for computers to execute.

# Bad ❌
return x && y || z && !a

# Good ✅
isValid = x and y
isSpecialCase = z and not a
return isValid or isSpecialCase
Enter fullscreen mode Exit fullscreen mode

💡 Pro Tip: If you can't explain your code to a junior developer, it's probably too complex!

15. Write Self-Documenting Code - Let Your Code Speak! 📢

Your code should be so clear that it doesn't need comments to explain what it's doing. Use descriptive names, clear structure, and logical organization to make your code self-explanatory.

// Bad ❌
void pc(List<T> x) {}

// Good ✅
void processCustomers(List<Customer> customers) {}
Enter fullscreen mode Exit fullscreen mode

💡 Pro Tip: Read your code aloud - if it sounds natural, you're on the right track!

Final Thoughts 🌟

These rules are guidelines, not commandments. The goal is to write code that's easy to understand, maintain, and modify. Like any craft, clean coding takes practice and patience. Keep these principles in mind, but don't let them paralyze you. Write code, refactor it, and most importantly, enjoy the process!

Happy coding! 💻

Thanks for reading! 🙏🏻
I hope you found this useful ✅
Please react and follow for more 😍
Made with 💙 by Hadil Ben Abdallah
LinkedIn GitHub Daily.dev

Top comments (4)

Collapse
 
madhurima_rawat profile image
Madhurima Rawat

Loved the headings! Great guide 👍

Collapse
 
hadil profile image
Hadil Ben Abdallah

Thank you 💙

Collapse
 
jakub_wisniewski_wisnia profile image
Jakub Wisniewski

Nah too much of my code is created by AI. Already a spaghetti understandable only by AI. 🤣Good content though 💪

Collapse
 
hadil profile image
Hadil Ben Abdallah

Now you can fix you spaghetti code by following these rules and it will become understandable by humans 😅
Thank you 💙