in c# oop object oriented programming design pattern cleanc code ~ read.

Remove Optional Argument for Clean Code

In this blog we are going to talk about how to remove optional arguments to make your code cleaner, using overloading.

What's overloading?

Here is a good explanation for overloading. So basically some programming languages allow you to create methods with the same name, but different arguments and depends on the way you call the method it will evoke different methods based on the arguments provided.

How's that gonna help me to make clean code?

Let's have a look at the following code. I'm gonna use C# since it better supports overloading compared to php which requires a little tweak.

using System;

namespace Demo  
{
    class Program
    {
        static decimal getPrice(string item, decimal discount = 0)
        {
            if (discount < 0 || discount >= 1)
            {
                throw new ArgumentException("Incorrect discount value provided");
            }
            if (discount > 0)
            {
                Console.WriteLine("Discount {0}% applied", 100 * discount);
            }
            return 100.0M * item.Length * (1.0M - discount);
        }

        static void Main()
        {
            Console.WriteLine("{0:C}", getPrice("apple", .15M));
            Console.WriteLine("{0:C}", getPrice("orange"));
            Console.ReadLine();
        }
    }
}

As you can see here that without overloading, I need to put the condition into the same method which seems to be a little bit ugly. Let's see how can we apply overloading to make it cleaner.

With overloading

using System;

namespace Demo  
{
    class Program
    {
        static decimal getPrice(string item)
        {
            return 100.0M * item.Length;
        }
        static decimal getPrice(string item, decimal discount = 0)
        {
            if (discount < 0 || discount >= 1)
            {
                throw new ArgumentException("Incorrect discount value provided");
            }

            Console.WriteLine("Discount {0}% applied", 100 * discount);
            return getPrice(item) * (1.0M - discount);
        }

        static void Main()
        {
            Console.WriteLine("{0:C}", getPrice("apple", .15M));
            Console.WriteLine("{0:C}", getPrice("orange"));
            Console.ReadLine();
        }
    }
}

As you can see we create another method with the same name but with different arguments. It is better code for programmers to understand and also it doesn't change the implementation of the code at all.

End

Thanks for reading this shot post. Hope you guys can learn it and apply to your code to make it cleaner. As always if you have any opinions or ideas please leave it below. Thanks.

comments powered by Disqus