Top 7 clean code tips every developer should know – Part #3

Top 7 clean code tips every developer should know – Part #3

Writing clean code is a never-ending journey. As developers, we continuously refine our skills to produce code that is readable, maintainable, and scalable. In this third installment, we’ll explore more techniques to enhance your coding practices and ensure your code remains in top shape.

Let’s dive into seven more clean code tips to level up your development workflow!

1 – Use Expression-bodied Members for Simplicity

The traditional method requires extra syntax, adding unnecessary boilerplate:

C#
				public string GetFullName()
{
    return firstName + lastName;
}
			

By using an expression-bodied member, we eliminate unnecessary braces and keywords, making the code more compact and easier to read, but be careful, if the method is too large it can sometimes become confusing.

C#
				public string GetFullName() => firstName + lastName;

			

2 – Minimize Nesting for Better Readability

Deeply nested code makes logic harder to follow, increasing cognitive load and maintenance complexity. Reducing nesting improves readability and ensures the intent is clear.

C#
				if (user != null)
{
    if (user.IsActive)
    {
        if (user.HasPermission)
        {
            return true;
        }
    }
}

return false;
			

This small refactor leads to simpler, more maintainable code, ensuring your logic remains clear and efficient.

C#
				if (user is null || !user.IsActive || !user.HasPermission) // Or -> if(HasValidAccess(user))
{
    return false;
}

return true;
			

3 – Use Meaningful Boolean Expressions

This approach unnecessarily compares isActive to true, which doesn’t add any value and makes the condition more verbose than needed

C#
				if (isActive == true)
{
    //...
}
			

This small change leads to cleaner, more maintainable code, making your logic straightforward and easy to follow.

C#
				if (isActive)
{
    //...
}
			

4 – Use Vertical coding Style

This format can be difficult to understand quickly, especially when there are more conditions or method calls.

C#
				var users = await _context.Users.AsNoTracking().Where(u => u.IsActive).OrderBy(u => u.LastName).ToListAsync();
			

Instead, use vertical coding style, this emphasizes structuring your code in a way that’s easy to scan from top to bottom, each line serves a specific purpose, allowing others (or future you!) to quickly understand the logic.

C#
				var users = await _context.Users
    .AsNoTracking()
    .Where(u => u.IsActive)
    .OrderBy(u => u.LastName)
    .ToListAsync();
			

5 – Return Early

The “return early” technique helps reduce code complexity and improves readability. By returning as quickly as possible from a method when a condition is not met, we avoid creating unnecessarily nested blocks of code and keep the logic clean and efficient, avoiding executing additional codes, make the code more efficient and intelligent.

C#
				public void ProcessPayment(Payment payment)
{
    // Here you can also create a method for these multiple conditions.
    if (payment is null || payment.Amount <= 0 || payment.CardNumber is null) 
    {
        return; // Early return if any condition fails
    }

    // ...
}

			

6 – Use the Result Pattern

Here, we use exceptions to handle invalid input, which can disrupt the flow of the application and create a less user-friendly experience.

C#
				if (order.TotalAmount <= 0)
{
    throw new InvalidOperationException("Total amount must be greater than zero"); // Or CustomExeption
}

if (order.Items.Count == 0)
{
    throw new InvalidOperationException("Order must contain at least one item"); // Or CustomExeption
}

// Process the order
			

The Result Pattern improves code clarity and maintainability by making logic simpler and more controlled. It allows you to handle failures without cluttering your code with exceptions, and it makes error communication more explicit.

C#
				if (order.TotalAmount <= 0)
{
    return Result.Failure(OrderErrors.InvalidTotalAmount);
}

if (order.Items.Count == 0)
{
    return Result.Failure(OrderErrors.EmptyOrder);
}

// Process the order

return Result.Success();
			

7 – Be Consistent in Your Code

Here, the method GetAsync() follows a clear naming convention by using the “Async” suffix to indicate an asynchronous operation. However, in the next example, the naming convention is dropped, which creates confusion about whether the method is synchronous or asynchronous.

C#
				// Using 'Async' suffix for asynchronous methods
public async Task<Product> GetAsync() 
{ 
    // ...
}

// Switching to inconsistent naming
public async Task<Course> Get()
{
    // ...
}
			

Here the “Service” came after and in the second example it came before:

C#
				// "Service" came after
public class CustomerService 
{ 
    // ... 
}

// "Service" came before 
public class ServiceProduct
{ 
    // ... 
}

			

Instead, be consistent in naming methods:

C#
				// Always use the 'Async' suffix for asynchronous methods
public async Task<Product> GetAsync() 
{ 
    // ...
}

public async Task<Course> GetAsync() 
{ 
    // ...
}
			

Instead, be consistent in naming classes:

C#
				// Always use 'Service' at the end of the class name
public class CustomerService 
{
    // ...
}

public class ProductService 
{
    // ... 
}

			

Conclusion

We’ve covered seven more clean code principles to help you write better, more maintainable code. Clean code is not just about writing functional code, it’s about writing code that others (including your future self) can easily read and work with.

Let’s continue refining our craft and building better, more sustainable code together!

Thank you for reading.

See you next time!

Share the Post:
plugins premium WordPress