Clean Coding Essentials: Tips for Writing Readable Code

mohaiminul_shovon

Mohaiminul Shovon

Posted on October 30, 2024

Clean Coding Essentials: Tips for Writing Readable Code

“Any fool can write code that a computer can understand. Good programmers write code that humans can understand.”

Martin Fowler’s quote captures the essence of clean coding: creating code that’s functional and easy for other developers to read. In the line duty, I myself has faced numerous challenges while writing code. But It was never the technical things that make me concerned. It the cleanliness and readability of my code. Here’s my take on clean coding principles that might help to maintain utmost readability of the code.

Naming Variables

Good variable names are critical for clear, maintainable code.

According to the famous software nerd Phil Karlton,

"There are only two hard things in Computer Science: cache invalidation and naming things."

Here’s how to improve your naming practices:

  • Avoiding Disinformation: Use variable names that accurately describe what they hold. Avoid misleading terms.
    • Bad: int hp; // Is it hit points or horsepower?
    • Good: int hitPoints;
  • Avoiding Noise Words: Words like "data" or "info" add clutter and don’t clarify what the variable holds.
    • Bad: string productInfo;
    • Good: string productName;
  • Using Pronounceable Names: Names should be easy to read and say out loud.
    • Bad: string prdctNm;
    • Good: string productName;
  • Using Searchable Names: Avoid short, non-descriptive names that make it hard to locate variables.
    • Bad: for (int i = 0; i < 10; i++) { ... }
    • Good: for (int itemIndex = 0; itemIndex < items.Count; itemIndex++) { ... }
  • Be Consistent: Stick to a single naming convention throughout.
    • Inconsistent: userName in one place and user_name in another.
    • Consistent: Always use userName.

Writing Functions

Writing clean, effective functions is essential for readability and maintainability.

  • Keeping Functions Small: Short functions are easier to understand. Aim to fit each function on one screen.

    • Bad:

      def calculateTotal(cart):
          # Several lines of calculation logic
      
    • Good:

      def calculateItemTotal(item):
          ...
      
      def calculateCartTotal(cart):
          total = 0
          for item in cart:
              total += calculateItemTotal(item)
          return total
      
  • Single Responsibility: Each function should do only one thing.

    • Bad:

      def sendEmail(email, subject, message, log):
          log.append("Sending email to " + email)
          # Code to send email
          log.append("Email sent")
      
      
    • Good:

      def logMessage(log, message):
          log.append(message)
      
      def sendEmail(email, subject, message):
          # Code to send email
      
  • Encapsulate Conditionals in Functions: Long, complex conditionals are confusing. Encapsulate them with clear function names.

    • Bad:

      if (user && user.isActive && user.isVerified) { ... }
      
    • Good:

      function isUserEligible(user) {
          return user && user.isActive && user.isVerified;
      }
      if (isUserEligible(user)) { ... }
      
  • Fewer Arguments: Aim for functions with three or fewer parameters.

    • Bad:

      function createUser(name, email, password, age, address) { ... }
      
    • Good:

      
      function createUser({ name, email, password, age, address }) { ... }
      
  • Avoid Flag Arguments: Flags complicate function logic.

    • Bad:

      function displayUserProfile(user, isAdmin) {
          if (isAdmin) {
              // Show admin view
          } else {
              // Show regular view
          }
      }
      
    • Good:

      function displayUserProfile(user) { ... }
      function displayAdminProfile(user) { ... }
      
  • No Side Effects: Functions should not alter external states unless intended.

    • Bad:

      function addToCart(item) {
          cart.push(item); // modifies an external cart
          return cart.length;
      }
      
    • Good:

      function createUpdatedCart(cart, item) {
          const updatedCart = [...cart, item];
          return updatedCart;
      }
      
  • Don’t Repeat Yourself (DRY): Avoid duplicating logic. Reuse functions wherever possible.

    • Bad:

      function calculateDiscountedPrice(price) {
          return price - (price * 0.1);
      }
      
      function calculateFinalPrice(price) {
          return price - (price * 0.1); // Duplicate logic
      }
      
    • Good:

      
      function applyDiscount(price, discountRate = 0.1) {
          return price - (price * discountRate);
      }
      

Don’t Leave Code in Comments

Comments can be helpful, but avoid leaving commented-out code. It adds clutter and can mislead readers.

  • Bad:

    # This is a function to add two numbers
    # def add(a, b):
    #     return a + b
    def add(a, b):
        return a + b
    
  • Good:

    # Function to add two numbers
    def add(a, b):
        return a + b
    

Know Your Language Conventions

Each language has unique conventions for naming, indentation, and structure. Following them improves consistency and readability.

  • JavaScript Example:

    // Follow camelCase for variables and functions
    let userName = "John Doe";
    
    // Use PascalCase for classes
    class UserProfile { ... }
    
  • Python Example:

    # Use snake_case for variables and functions
    user_name = "John Doe"
    
    # Use CapitalizedWords for classes
    class UserProfile:
        ...
    

Clean coding practices are an investment that pays off with better readability, easier maintenance, and a codebase that other developers will thank you for. Start with these practices to make your code cleaner, clearer, and more effective.

💖 💪 🙅 🚩
mohaiminul_shovon
Mohaiminul Shovon

Posted on October 30, 2024

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

Sign up to receive the latest update from our blog.

Related