Tuesday 30 June 2015

Anonymous functions

Anonymous functions are functions that you create inline as needed, for example lets say you have a delegate that formats a name. You could assign a defend function to it by declaring the function with a name and then adding that function to the invocation list of the delegate.

namespace pav.anonymousFunctions;

class Program
{
    delegate string FormatNameDelegate(string LastName, bool Male, bool Doc);

    static string FormatNameFn(string LastName, bool Male, bool Doc = false)
    {
        return Doc ? $"Dr. {LastName}" : String.Concat(Male ? "Mr." : "Ms.", LastName);
    }

    static void Main(string[] args)
    {
        FormatNameDelegate declaredFn = FormatNameFn;

        Console.WriteLine(declaredFn.Invoke("Jones", true, true));

        declaredFn -= FormatNameFn;
    }
}


above we Defined the FromatNameDelegate,  created a function that formats the name, then in the main method we assign our function to our delegate reference, and finally call it. Perfectly valid code, especially if we want to later remove the delegate.

however if we have no need of removing the delegate, then we can simply reference an anonymous function to our FormatName Delegate.


namespace pav.anonymousFunctions;
class Program
{
    delegate string FormatNameDelegate(string LastName, bool Male, bool Doc);

    static void Main(string[] args)
    {
        FormatNameDelegate declaredFn = (LastName, Male,  Doc) =>
            Doc ? $"Dr. {LastName}" : String.Concat(Male ? "Mr." : "Ms.", LastName);

        Console.WriteLine(declaredFn.Invoke("Jones", true, true));
    }
}


because in the anonymous version, there is no defined FormatNameFn, there is no way to remove it from the invocation list of the declaredFn delegate.

Saturday 27 June 2015

Action Delegate

In a previous posts we talked about leveraging Funcs tor replace delegates that reference functions, we can also you actions to reference methods, the difference between a function and a method is simply that functions return something, whereas methods do not. In short:
  • Func: represents a function
  • Action: represents a method
Actions have a syntax like so Action<T1, T2, T3>(T1 variable1, T2 variable2, T3 variable3), up to 18 parameters last i checked which means that you declare what types your action will consume.

namespace pav.actionExample;

class Program
{

    static void AddMethod(int x, int y)
    {
        Console.WriteLine(x + y);
    }

    static void Main()
    {
        //declared action
        Action<int, int> Add1 = AddMethod;

        //inline action
        Action<int, int> Add2 = (x, y) => { Console.WriteLine(x + y); };

        Add1(2, 3);
        Add2(2, 3);
    }
}

Above there's two actions Add1 and Add2, the difference is that add2 was declared in an inline fashion using the lambda syntax, there really isn't a right or wrong way of doing this, there's many opinions on the matter, mine is simply this, if' the method you're declaring is more than 5 lines don't use the lambda expression. A more generic rule is if it's hard to read, separate it.

Previously we reduced our code using funcs, now we can leverage both funcs and actions to further reduce, simplify and decouple our code. 

namespace pav.funcActionExample;

class Program
{
    struct Employee
    {
        public string FirstName;
        public string LastName;

        public Employee(string FirstName, string LastName)
        {
            this.FirstName = FirstName;
            this.LastName = LastName;
        }
    }

    class EmployeeService
    {
        public List<Employee> Employees { get; } = new List<Employee>() {
                new Employee("Pawel","Chooch"), new Employee("Steve","Smith"),
                new Employee("Ian","Price"), new Employee("Tomek","Wan"),
                new Employee("Jacques","Cocion") };

        public void ProcessEmployee(Func<Employee, string> formatEmployeeFunc, Action<string> printAction)
        {
            if (formatEmployeeFunc is not null && printAction is not null)
                foreach (Func<Employee, string> del in formatEmployeeFunc.GetInvocationList())
                    foreach (var e in Employees)
                        printAction(del(e));
        }
    }

    static void Main()
    {
        var es = new EmployeeService();

        Func<Employee, string> formatFunc = null;

        formatFunc += e => $"{e.FirstName} {e.LastName}";
        formatFunc += e => $"{e.FirstName.Substring(0, 1)}. {e.LastName}";


        es.ProcessEmployee(formatFunc, (string str) => Console.WriteLine(str));
    }
}

as before we've greatly reduced the number of lines, increased our readability and decoupled our output logic from our service, now we pass an inline action " (string str) => Console.WriteLine(str) " which defines how our data will be outputted.


Monday 22 June 2015

Func Delegate

 In a previous post we talked about declaring delegates:

  • We had to declare a delegate type with a signature and return type 
  • create a function or method that matches the delegate's signature and return type
  • create a function or method that then accepts the your delegate as a parameter
  • pass the delegate or delegates to thee created function
Not just a tad convoluted, but it also clutters up your code; the best code is clean, easy to read, and concise. The kind of code that reads so clearly, that any idiot would say "I could of written that." I'm not a fan of stupid people, but they are everywhere and they will ruin your hard work, that's a fact of life. However that's all the more reason to do a stellar job and hope that your app gets retired before it gets 'Modified' (or in truth butchered by amateurs).

So what are Funcs? As this posts title foreshadows, you can think of them as delegates. Funcs have a return type, and can have multiple parameters. In essence they cut out the middle man of declaring a delegate type, and just let you define a variable inside your functions.


namespace pav.funcExample;

class Program
{
    static int AddFunction(int x, int y)
    {
        return x + y;
    }

    static void Main(string[] args)
    {
        //declared Func
        Func<int, int, int> Add1 = AddFunction;

        //Inline func
        Func<int, int, int> Add2 = (x, y) => { return x + y; };

        Console.WriteLine(Add1(3,4));
        Console.WriteLine(Add2(3,4));    
    }
}


If we take a look at our funcs there are two variations, in the first we assign an existing function to our func, in the second we assign an inline anonymous function, like before this creates a reference to a function, letting us pass them around like variables.

now that's all fun and dandy and yes it can shorten your code a bit, but where's the real value in this? to answer that let's take a look at our previous example from delegates now using the func and action keywords instead.


namespace pav.funcExample;

class Program
{
    struct Employee
    {
        public string FirstName;
        public string LastName;

        public Employee(string FirstName, string LastName)
        {
            this.FirstName = FirstName;
            this.LastName = LastName;
        }
    }

    class EmployeeService
    {
        public List<Employee> Employees { get; } = new List<Employee>() {
                new Employee("Pawel","Chooch"), new Employee("Steve","Smith"),
                new Employee("Ian","Price"), new Employee("Tomek","Wan"),
                new Employee("Jacques","Cocion") };

        public void ProcessEmployee(Func<Employee, string> formatEmployee)
        {
            if (formatEmployee != null)
                foreach (Func<Employee, string> del in formatEmployee.GetInvocationList())
                    foreach (var e in Employees)
                        Console.WriteLine(del(e));
        }
    }

    static void Main()
    {
        var es = new EmployeeService();

        Func<Employee, string> formatFunc = null;
       
        formatFunc += e => $"{e.FirstName} {e.LastName}";
        formatFunc += e => $"{e.FirstName.Substring(0, 1)}. {e.LastName}";

        es.ProcessEmployee(formatFunc);
    }
}


In the above we've reduced the number of lines and increased readability, funcs in short let us reference 

Monday 15 June 2015

Delegate Functions

If you google the word delegate you'll find "a person sent or authorized to represent others, in particular an elected representative sent to a conference." Which isn't a half bad definition. In a c# context; a delegate can be thought of as a strongly typed variable that holds a reference to a static function.

You can think of a delegate as 'a defined function variable' with signature and return type. This delegate type can be used to define multiple delegate handlers,


namespace pav.delegateExample;

class Program
{
    // create our delegate types
    delegate int mathDelegate(int x, int y);
    delegate string combineDelegate(int x, int y);

    static int Add(int x, int y)
    {
        return x + y;
    }

    static string Combine(int x, int y)
    {
        return $"{x} {y}";
    }

    static void Main(string[] args)
    {
        //instantiate handlers of type mathDelegate
        mathDelegate addHandler = Program.Add;
        mathDelegate subHndler = (int x,int y) => x-y;

        Console.WriteLine(addHandler(3, 4));
        Console.WriteLine(subHndler(3, 4));


        // Delegates are strongly typed refrence points in
        // memory for functions, because the combine function
        // has a differnt return type, we cannot reuse the
        // mathDelegate.
        combineDelegate combineHandler = Program.Combine;

        Console.WriteLine(combineHandler(3, 4));
    }

}


Above is  simple example that demonstrates a variable "handler" of type mathDelegate which we assign static functions to, we can then invoke those function by calling our delegate handler and pass the appropriate parameters.

Now what use could this possibly be? well it's a nice way of allowing objects to pass in their own functions or methods into other objects. Take a look at the example below.


namespace pav.delegateExample;

class Program
{
    struct Employee
    {
        public string FirstName;
        public string LastName;

        public Employee(string FirstName, string LastName)
        {
            this.FirstName = FirstName;
            this.LastName = LastName;
        }
    }

    delegate void FormatEmployee(Employee Employee);

    class EmployeeService
    {
        public List<Employee> Employees { get; } = new List<Employee>() {
                new Employee("Pawel","Chooch"), new Employee("Steve","Smith"),
                new Employee("Ian","Price"), new Employee("Tomek","Wan"),
                new Employee("Jacques","Cocion") };

        public void ProcessEmployee(FormatEmployee dFormat)
        {
            foreach (var e in Employees)
                dFormat(e);
        }
    }

    static void PrintEmployee(Employee e)
    {
        Console.WriteLine($"{e.FirstName} {e.LastName}");
    }

    static void PrintEmployeeInitial(Employee e)
    {
        Console.WriteLine($"{e.FirstName.Substring(0, 1)}. {e.LastName}");
    }

    static void Main()
    {
        var es = new EmployeeService();

        es.ProcessEmployee(PrintEmployee);
        es.ProcessEmployee(PrintEmployeeInitial);
    }
}


Above our EmployeeService class has a collection of employees and a Process Employee Function, by leveraging a delegate as the function's parameter, our application can decide what the ProcessEmployee method will do.

The idea is to decouple our application, the class shouldn't be writing to consoles or files, but instead should be taking in functions that provide this functionality. First let's start by adding windows forms to our console application, open the .csproj file and paste the following.


<Project Sdk="Microsoft.NET.Sdk">

  <PropertyGroup>
    <TargetFramework>net6.0-windows</TargetFramework>
    <UseWindowsForms>true</UseWindowsForms>
    <OutputType>Exe</OutputType>
    <ImplicitUsings>enable</ImplicitUsings>
    <Nullable>enable</Nullable>
  </PropertyGroup>

</Project>


In the above we add the UseWindowsForms  node and modify the TargetFramework one, this will let us use windows forms in our console application. 

namespace pav.delegateExample;

class Program
{
    struct Employee
    {
        public string FirstName;
        public string LastName;

        public Employee(string FirstName, string LastName)
        {
            this.FirstName = FirstName;
            this.LastName = LastName;
        }
    }

    delegate string FormatEmployeeDelegate(Employee Employee);
    delegate void WriteNameDelegate(string value);

    class EmployeeService
    {
        public List<Employee> Employees { get; } = new List<Employee>() {
                new Employee("Pawel","Chooch"), new Employee("Steve","Smith"),
                new Employee("Ian","Price"), new Employee("Tomek","Wan"),
                new Employee("Jacques","Cocion") };

        public void ProcessEmployee(FormatEmployeeDelegate dFormat, WriteNameDelegate dWrite)
        {
            foreach (var e in Employees)
                dWrite(dFormat(e));
        }
    }

    static string PrintEmployee(Employee e)
    {
        return $"{e.FirstName} {e.LastName}";
    }

    static string PrintEmployeeInitial(Employee e)
    {
        return $"{e.FirstName.Substring(0, 1)}. {e.LastName}";
    }

    static void WriteToConsole(string value)
    {
        Console.WriteLine(value);
    }

    static void WriteToMessageBox(string value)
    {
        MessageBox.Show(value);
    }

    static void Main()
    {
        var es = new EmployeeService();

        es.ProcessEmployee(PrintEmployee, WriteToConsole);
        es.ProcessEmployee(PrintEmployeeInitial, WriteToMessageBox);
    }

}



Above we changed our delegate to now return a string, this string will be the transformation we want to make onto our Employee, and the second delegate will be in charge of writing the value somewhere. In our main we pass two different formats and two different ways of writing. One to the console and the other with a message box. Now the EmployeeService class only focuses on employees and accepts delegates that define 'how to format text' and 'where to output it' as parameters.

you can read a bit more on delegates on MSDN: delegates

a delegate can call more then one method, this is referred to as multicasting. All we have to do is refactor our process employee method to call each function in the invocation list.

       
public void ProcessEmployee(FormatEmployeeDelegate formatEmployee,
                            WriteNameDelegate Callback) {
    if (formatEmployee != null && Callback != null)
        foreach (FormatEmployeeDelegate d in formatEmployee.GetInvocationList())
            foreach (var e in Employees)
                Callback(d(e));
}


with that done if we run our application since currently we are only passing one delegate to the ProcessEmployee method we won't see any difference whatsoever from our previous code, so what we have to do is add multiple functions to our delegate. we can do this by using the same syntax we'd use for events. += to add and -= to remove.

   
    static void Main()
    {
        var es = new EmployeeService();

        FormatEmployeeDelegate fe = PrintEmployee;
        fe += PrintEmployeeInitial;

        es.ProcessEmployee(fe, WriteToConsole);
    }


What we did to our main is declared a Format Employee delegate fe and made it equal to our PrintEmployee function, then appended the PrinteEmployeeIntitial function to it. We can see that if we pass our fe delegate with two function they both fire, and if we just pass the one only it fires.

if we want, we can subtract our functions with the -= operation.

   
    static void Main()
    {
        var es = new EmployeeService();

        FormatEmployeeDelegate fe = PrintEmployee;
        fe += PrintEmployeeInitial;

        es.ProcessEmployee(fe, WriteToConsole);

        //remove format delegates
        fe -= PrintEmployee;
        fe -= PrintEmployeeInitial;

        es.ProcessEmployee(fe, WriteToMessageBox);
    }


Now our second call to the ProcessEmployee method does nothing, because the fe delegate contains no functions to call.

The take away from this is that delegates store references to methods or functions, they allow you to pass functions as parameters into functions or methods. One thing to keep in mind is that you'll only really see them used in legacy code, for the most part in modern applications you'll leverage the Func delegate.

Wednesday 10 June 2015

Predicate Functions

If you google the word predicate you get a definition similar to the following: 

"something which is affirmed or denied concerning an argument of a proposition." 

which is a valid definition, but for our sake we can just refer to it as 

"a function that takes in one or more parameters and returns true or false". 

here's a couple of examples:

   
    private static bool isEvenLength(string value)
    {
        return value.Length % 2 == 0;
    }

    private static bool isOddLength(string value)
    {
        return value.Length % 2 == 1;
    }


That's pretty much all there is to that, functions that return a boolean value. Don't believe me? cause you really shouldn't I'm just some guy with a blog on the internet which we all know is 50% half-truths and 40% flat out lies; making it only about 35% true.


namespace pav.predicateExample;
class Program
{
    private static bool isEvenLength(string value)
    {
        return value.Length % 2 == 0;
    }

    private static bool isOddLength(string value)
    {
        return value.Length % 2 == 1;
    }

    static void Main(string[] args)
    {
        string[] names = { "Mike", "Pawel", "Magda", "Tomek", "Marin", "Ivan", "Trish", "Jake" };

        //define our predicate
        Predicate<string> pEvenLength = Program.isEvenLength;

        Console.WriteLine("\nNames that have an even number of chars");
        foreach (var name in Array.FindAll(names, pEvenLength))
            Console.WriteLine(name);

        //pass a function in as a predicate
        Console.WriteLine("\nNames that have an odd number of chars");
        foreach (var name in Array.FindAll(names, isOddLength))
            Console.WriteLine(name);

        //pass an inline function in as a predicate
        Console.WriteLine("\nNames that start with 'M'");
        foreach (var name in Array.FindAll(names, n => n.Substring(0, 1) == "M"))
            Console.WriteLine(name);
    }
}


We have three uses of predicates above


// 1 define our predicate, here we define a predicate pEvenLength and we set it's value // to our isEvenLength function.

        Predicate<string> pEvenLength = Program.isEvenLength;

        Console.WriteLine("\nNames that have an even number of chars");
        foreach (var name in Array.FindAll(names, pEvenLength))
            Console.WriteLine(name);


// 2 we pass a function in as a predicate, here rather than defining a predicate,
// we simply pass our isOddLength function directly into our FindAll function.

        Console.WriteLine("\nNames that have an odd number of chars");
        foreach (var name in Array.FindAll(names, isOddLength))
            Console.WriteLine(name);



// 3 pass an inline function as a predicate, rather than explicitly creating a function
// we simply define one inline pass it in as a parameter to our FindAll function.

        Console.WriteLine("\nNames that start with 'M'");
        foreach (var name in Array.FindAll(names, n => n.Substring(0, 1) == "M"))
            Console.WriteLine(name);


If we run our application, we get the following.


That's all there is to predicates, it's just a function that return true or false, often time's it's used to filter array, or validate data. One thing that we did not mention explicitly, is that defined predicates can only accept one argument, meaning that if for example we had an array of numbers and we wanted to filter all of the numbers that are multiple of and 4 we'd have to do something like the following.


namespace pav.predicateExample2;
class Program
{
    static void Main(string[] args)
    {
       var numbers = Enumerable.Range(0, 100).ToArray();

       Predicate<int> isMultipleOf3Predicate = (x) => x % 3 == 0;    
       Predicate<int> isMultipleOf4Predicate = (x) => x % 4 == 0;

       var multiplesOf3and4 = Array.FindAll(numbers, isMultipleOf3Predicate)
            .Concat(Array.FindAll(numbers, isMultipleOf4Predicate)).Distinct().ToArray();
       
        Array.ForEach<int>(multiplesOf3and4, i => Console.Write(i + " "));
    }
}


we defined two predicates, ran our array through both of them, concatenated the results then had to remove the duplicates with a distinct and then again sort to get a sorted list. An alternative solution to circumvent this one argument restriction is create a function which accepts multiple arguments and returns one predicate. 


namespace pav.predicateExample;

class Program
{
    public static Predicate<int> MultipleOf(params int[] multiples)
    {
        return x =>
        {
            foreach (var m in multiples)
                if (x % m == 0)
                    return true;
            return false;
        };
    }

    static void Main(string[] args)
    {
        var numbers = Enumerable.Range(0, 100).ToArray();
        var multiples = Array.FindAll(numbers, MultipleOf(3, 4));
 
        Array.ForEach<int>(multiples, i => Console.Write(i + " "));
    }
}


This not only simplifies our codebase, but also eliminates the need to call distinct or sort, decreasing the number of times we have to iterate over our array.

Below we can compare our two solutions.


namespace pav.predicateExample2;

class Program
{
    // predicate factory function
    public static Predicate<int> MultipleOfPredicateFactory(params int[] multiples)
    {
        return x =>
        {
            foreach (var m in multiples)
                if (x % m == 0)
                    return true;
            return false;
        };
    }
    static void Main(string[] args)
    {
        var numbers = Enumerable.Range(0, 100).ToArray();

        // using multiple predicates
        Predicate<int> isMultipleOf3Predicate = (x) => x % 3 == 0;
        Predicate<int> isMultipleOf4Predicate = (x) => x % 4 == 0;

        var multiplesOf3and4 = Array.FindAll(numbers, isMultipleOf3Predicate)
             .Concat(Array.FindAll(numbers, isMultipleOf4Predicate))
             .Distinct().ToArray();

        Array.Sort(multiplesOf3and4);
       
        Array.ForEach<int>(multiplesOf3and4, i => Console.Write(i + " "));
        Console.WriteLine();

        // using a predicate factory function
        var multiples = Array.FindAll(numbers, MultipleOfPredicateFactory(3, 4));

        Array.ForEach<int>(multiples, i => Console.Write(i + " "));

    }
}

Friday 5 June 2015

Optional Parameters

Previously we talked about overloading which was the concept of having functions with the same name but different signatures, then depending on the arguments passed to the function the corresponding function would be called. Before that we spoke of named parameters, which let us choose the order we input our parameters to functions, methods or constructors. Now we're going to talk about optional parameters, which can help minimize the number of overloaded functions required, there are appropriate and inappropriate situations as to when to leverage these, and it's really up to you to decide when it's right in your code.


namespace pav.optionalArguments;
class Program
{

    public static void printName(string first, string last, bool isMale,  string middle = "", bool isMarried = false, bool isDoctor = false)
    {
        var prefix = isDoctor ? "Dr." : isMale ? "Mr." : isMarried ? "Mrs." : "Ms.";
        middle = String.IsNullOrEmpty(middle) ? " " : $" {middle} ";

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

    static void Main(string[] args)
    {
        // no optional parameters needed
        printName("Robert", "Smith", true);

        // all parameters needed
        printName("Jessica",  "Johnson", false, "Lyne", true, true);
                 
        // mix of named and optional paramters
        printName("Megan", "Jones", middle: "Eli", isMale: false, isMarried: true);

        //named paramteres not needed, but position matters
        printName("Tom", "Williams",
                  isMale: true, isMarried: true, isDoctor: true);

        // jumbled parametar input
        printName("Kristy", "Gray", middle: "Grace", isMale: false);

        // some sort of logic behind named parametars
        printName("Amanda", "Harding", isDoctor: true, isMale: false);
    }
}


By leveraging optional parameters we can minimize the number of function declarations needed, Optional parameters in combination with Named parameters can  also simplify our method calls making our code more readable.