Developers Give “If Condition” a Name

Hey, you have been writing software for 10+ years. Can you give me advice, tips to improve my skills?

What if someone asks me that question?

I can go on and on with many things. And finally, they will be confused and lost. What if I have to give only one advice?

I will say

Improve your naming

I once wrote the naming matters. Today, I give another small tip on naming

Give your “if condition” a name

Let take a very simple code

public int CalculateFee(Customer customer)
{
    if (DateTime.Now.Subtract(customer.RegisterAt) > TimeSpan.FromDays(30))
    {
        return 100;
    }
    return 200;
}

The condition is, “If a customer has registered for more than 30 days, charge 100 (assume it is USD). Otherwise, it costs 200.

What is the big problem with that code? The problem arises when other developers read the code. He does not speak the same language as when you wrote it. He will, mostly, read the code with the C# language syntax and try to figure out the logic.

An “if condition” is a business logic. Therefore, it should be named properly.

Now, let refactor code and give it a name.

        public int CalculateFee(Customer customer)
        {
            if (CustomerRegisteredFor30Days(customer))
            {
                return 100;
            }
            return 200;
        }

        private static bool CustomerRegisteredFor30Days(Customer customer)
        {
            return DateTime.Now.Subtract(customer.RegisterAt) > TimeSpan.FromDays(30);
        }

Think about multiple operators condition. You will see a big benefit.

 

There is a huge number of conditions in every codebase. If you write a new “if condition” or you see them in your current codebase, give them a favor

An “if” is a business logic, give it a name. If you cannot name it, you do not understand it.

Other developers will thank you for that.

A small action but big impact.

Write a Comment

Your email address will not be published. Required fields are marked *

This site uses Akismet to reduce spam. Learn how your comment data is processed.