Wednesday 3 June 2015

Overloading Functions

Previously we talked about using named parameters to more explicitly describe the values passed to our functions, methods, or constructors, now we are going to look at overloading functions, methods or constructors, for some reason this question comes up during technical interviews; not really sure as to why even if a programmer doesn't know the terminology they're almost certainly familiar with the concepts.

Overloading basically refers to when you have a function implemented a number of times but with different signatures or you have multiple constructors. This let's you define  granular functions, methods, or constructors, sometimes this makes sense and sometimes it doesn't.


namespace pav.overloadingFunctions;
class Program
{
    public static void printDoctorsName(string first, string middle, string last)
    {
        middle = String.IsNullOrEmpty(middle) ? " " : $" {middle} ";

        Console.WriteLine($"Dr. {first}{middle}{last}");
    }

    public static void PrintMaleName(string first, string middle, string last)
    {
        middle = String.IsNullOrEmpty(middle) ? " " : $" {middle} ";

        Console.WriteLine($"Mr. {first}{middle}{last}");
    }

    public static void PrintFemaleName(string first, string middle, string last, bool isMarried)
    {
        var prefix = isMarried ? "Mrs." : "Ms.";
        middle = String.IsNullOrEmpty(middle) ? " " : $" {middle} ";

        Console.WriteLine($"{prefix} {first}{middle}{last}");
    }

    static void Main(string[] args)
    {
          // no named parametars
        PrintMaleName("Robert", "Mike", "Smith");

        // named parametars, for obscure values
        printDoctorsName("Jessica", "Lyne", "Johnson");

        // named paramteres for everything
        PrintFemaleName("Megan", "Eli", "Jones", isMarried: true);

        // some sort of logic behind named parametars
        PrintFemaleName("Amanda", last: "Harding",  isMarried: false, middle: "");
    }
}


Above we took our printName method and broke it up into three new methods, though one could argue that each method is now simpler, there is more code to maintain. Obviously in this contrived example, it doesn't really matter, however in a real system you'll find yourself always struggling between a lot of simple code, vs less code but more complex. niether is good, and striking the right balance is difficult