DEV Community

mohamed Tayel
mohamed Tayel

Posted on

c# Clean Code: Writing Code That Humans Can Understand

Introduction:
Many programmers can write code that works, but good programmers write code that is easy for humans to understand. Reflect on the last time you had to maintain someone else's code. How many times have you felt the urge to throw it all away and start from scratch? Such situations arise when the code is not clean. But what does it mean for code to be clean? Clean code is easy to read, maintain, extend, and modify by any developer, not just the original author.

In this article, we’ll explore the importance of clean code, share practical examples of principles like KISS, DRY, and SOLID, and provide a hands-on walkthrough using Visual Studio to transform messy code into clean code.

1. Why Clean Code Matters:
Software is intangible, and you can write it in endless ways. While you’re not bound by the laws of physics, the better your code is at the beginning, the easier it is to scale and modify over time. Clean code ensures your application is flexible, maintainable, and future-proof. Yet, how often do we write code with the intention to "fix it later"? Most of the time, that later never comes. Therefore, writing clean code from the start saves future headaches.

2. Principles of Clean Code:

  • KISS (Keep It Simple, Stupid): Don’t overcomplicate your code. Solutions should be as simple as possible, without unnecessary complexity.

  • DRY (Don’t Repeat Yourself): Avoid duplicating logic. Each piece of knowledge should have a single, unambiguous representation within your system.

  • YAGNI (You Aren’t Gonna Need It): Don’t add features or code you think you might need in the future—focus only on what's necessary now.

  • SOLID Principles: These principles guide how you structure your classes and objects to make your code easier to maintain and extend.

    • S: Single Responsibility Principle
    • O: Open/Closed Principle
    • L: Liskov Substitution Principle
    • I: Interface Segregation Principle
    • D: Dependency Inversion Principle
  • Favor Composition Over Inheritance: Instead of inheriting behavior from parent classes, prefer composing behavior from multiple smaller classes. This approach makes your code more flexible and easier to maintain.

  • Separation of Concerns: Each module or class should have a distinct responsibility. This makes your system easier to understand and refactor when necessary.

3. How We’ll Learn Clean Code:
In this training, I’ll take you through real-world examples, starting with messy code I encountered at my company, Carved Rock. We’ll use Visual Studio to refactor this dirty code into clean, maintainable code.

Here’s how the learning process will work:

  • Before and After Approach: In each module, we’ll explore examples of bad code (before) and then refactor them into clean code (after).
  • Real-World Principles: The examples will demonstrate principles like KISS and DRY in action, so you can easily compare the transformations.

4. Hands-On Example with Visual Studio:
Let’s take a specific principle—KISS—as an example. Below is a snippet of messy code found in the “before” folder:

// BEFORE: Complicated and messy code that violates KISS
public class ProductService
{
    public Product GetProductDetails(int id)
    {
        var product = // fetch product from database...
        if (product == null)
        {
            throw new Exception("Product not found");
        }
        return product;
    }
}
Enter fullscreen mode Exit fullscreen mode

Now, let’s refactor this using the KISS principle:

// AFTER: Clean and simple code that follows KISS
public class ProductService
{
    public Product GetProductDetails(int id)
    {
        var product = _repository.GetById(id) ?? throw new ProductNotFoundException(id);
        return product;
    }
}
Enter fullscreen mode Exit fullscreen mode

Notice how we simplified the logic, making it more concise and easier to understand. We replaced a generic exception with a specific one and removed unnecessary clutter, improving clarity.

5. Applying These Lessons to Your Codebase:
The goal of clean code is to make it easier for anyone to understand and work with your code. Remember, you are not just writing code for the computer to understand—you are writing it for the next developer (which might be you in the future).

6. Conclusion:
By following clean code principles such as KISS, DRY, SOLID, and Separation of Concerns, you’ll create code that’s easier to maintain, extend, and collaborate on. In this course, you’ll see how each principle transforms messy code into a well-structured and maintainable codebase.

So, let's dive in and start writing clean, human-friendly code that stands the test of time!

Top comments (1)