Friday, 10 November 2017

Compostie Pattern

The composite pattern in simplest terms allows you to group nodes within a tree structure and treat them as one node, in other words it lets you treat a group of things as if they where just one thing. so let's take a look at what that means. To get started let's create an IWidget interface.

interface IWidget
{
    string Name { get; set; }
    int Weight { get; }
}

now this interface simply defines two properties, one is an identifier and the other is the weight of our widget, next let's create some concrete implementations of our interface, namely screw and bolt. we're going to pretend that we are a part supplier.

class Screw : IWidget
{
    public string Name { get; set; }
    public int Weight { get; } = 250;
    public Screw(string name) => Name = name;
}

class Bolt : IWidget
{
    public string Name { get; set; }
    public int Weight { get; } = 100;
    public Bolt(string name) => Name = name;
}

simple enough; now here's where it starts to get interesting, let's create a dunnage class. A dunnage is just going to be a box of widgets, but we are going to implement the IWidget interface on our dunnage class.

class Dunnage : IWidget
{
    public IEnumerable<IWidget> Widgets { get; set; }

    public string Name { get; set; }

    public int Weight
    {
        get
        {
            int total = 0;
            foreach (var w in Widgets)
                total += w.Weight;
            return total;
        }
    }
}

now as you see for our dunnage class our weight property iterates over all of the widgets in the dunnage and outputs their total weight.

now in our main we can lump our individual widgets in with the Dunnage in one shipment collection.

class Program
{
    static void Main(string[] args)
    {
        IWidget widget0 = new Screw("foo");
        IWidget widget1 = new Bolt("bar");

        IWidget dunnage1 = new Dunnage {
            Name = "Bin A",
            Widgets = new IWidget[] { new Screw("bill"), new Screw("foo"), new Bolt("bar")}};

        var shipment = new List<IWidget>(new IWidget[] { widget0, widget1, dunnage1 });
        var totalWeight = shipment.Select(w=> w.Weight).Aggregate((x, y) => x += y);

        Console.WriteLine(totalWeight);
    }
}

by implementing the IWidget interfacce on both our nodes and a collection of nodes it makes it trivial to calculate the total weight of our shipment, this is because whether it's an individual widget or a composite of widgets the weight property retrieves what it's suppose to. now obviously this is a contrived example and an actual implementation would be more complicated with many more fields and would require a lot more planing, but the jist of the pattern is here.

Wednesday, 8 November 2017

Null Object Pattern

The null object pattern provides an object that prevents a nullreference exception, but still notifies the user now that the object they're looking for is missing; as per usual let's start with with a person class.

class Person
{
    public string FirstName { get; set; }
    public string LastName { get; set; }
    public string FullName { get => $"{FirstName} {LastName}"; }
    public Person(string FirstName, string LastName)
    {
        this.LastName = LastName;
        this.FirstName = FirstName;
    }

}

nothing special just some first and last name properties and full name read-only property. next we'll create a People class.

class People
{
    IEnumerable<Person> _people;
    Person nullPerson = new Person("No ", "Person");

    public People(params Person[] people) => _people = people;

    public Person GetPerson(string Name)
        => _people.FirstOrDefault(p => p.FirstName == Name) ?? nullPerson;

}

this class contains an enumerable of people and let's the user return a person based on their first name. now the interesting part is that if the GetPerson function doesn't find a person with the specified first name, instead of returning null, it returns the nullPerson instance of the Person class.

Now when we take a look at our main class.

class Program
{
    static void Main(string[] args)
    {
        var tomek = new Person("Tomek", "Chooch");
        var marin = new Person("Marin", "Smartzik");

        var people = new People(pawel, tomek, marin);

        Console.WriteLine(people.GetPerson("Tomek").FullName);
        Console.WriteLine(people.GetPerson("Magda").FullName);
    }

}

we can see that even though the person Magda isn't in our list, when we write the FullName property instead of getting a null reference exception we simply write "No Person" to the console. Is this ideal? well as always it just depends there will be times when it does make sense to use this pattern, there will be times where it makes sense to throw the null reference exception and there will be times when it makes sense to get the object and check if it's null then operate on it if it's not null. It just depends on the circumstances.

Friday, 3 November 2017

Chain of responsibility Pattern

The chain of responsibility pattern can be thought of as a linked list, that receives input at the start of the list then propagates through a list until a node can handle it; once the input is "handled" it's done, it doesn't' continue on through the list. Think of it as an escalating issue that only goes as high as it needs to, for example if you need to expense a work lunch, odds are your direct manager can approve that expense, but let's say you need local training well maybe that group manager might have to approve it, or let's say it's training in a different country and you need a hotel room with travel, well then quite possibly the CFO might have to approve the expense.

think of it like this, in the chain of command each node has authority to approve an expense of a certain amount, if the expense surpasses that node's approval limit, the node must escalate the expense to the next level. let's take a look at the following

Line Manager (2000) -> Group Manager (3500) -> Regional Manager (10,000)-> CFO (50,000)-> CEO (*)

so in our scenario each level of management has the authority to approve expenses to a certain amount, once the request surpasses that amount, that level of management simply escalates the expense to the next level.

To get started we'll create the employee class, all our employee will do is represent an employee, for simplicity sake the only information we'll include in our employee is their name.

class Employee
{
    public string Name { get; set; }
    public Employee(string Name) => this.Name = Name;
}

next we'll create an ExpenseApprover class, normally we'd create an interface or abstract base class to enforce certain behavior, but for the sake of brevity we'll just make a standalone class.

class ExpenseApprover
{
    public Employee Employee { get; set; }
    public ExpenseApprover NextApprover { get; set; }
    public Double Limit { get; set; }

    public ExpenseApprover(Tuple<Employee, double> data)
    {
        this.Employee = data.Item1;
        this.Limit = data.Item2;
    }

    public bool Approve(double Expense)
    {
        if (Expense <= Limit)
        {
            Console.WriteLine($"Approved by {Employee.Name}");
            return true;
        }

        return NextApprover == null ? false : NextApprover.Approve(Expense);
    }
}

This class has a reference to the employee, their spending limit and a pointer to the next approver in the chain of command as well as a recursive approve function. In our approve function if the expence can be approved by the current employee it is, otherwise it's escalated to the next approver.

Now let's look at the main

class Program
{
    static void Main(string[] args)
    {
        Tuple<Employee, double>[] Employees = {
            new Tuple<Employee, double>(new Employee("Line Manager"), 100.0),
            new Tuple<Employee, double>(new Employee("Group Manager"), 200.0),
            new Tuple<Employee, double>(new Employee("Reginal Manager"), 500.0),
            new Tuple<Employee, double>(new Employee("CFO"), 1000.0),
            new Tuple<Employee, double>( new Employee("CEO"), 2000.0)};

        var LineManager = new ExpenseApprover(Employees[0]);
        var currManager = LineManager;

        for (int i = 1; i < Employees.Length; i++)
        {
            currManager.NextApprover = new ExpenseApprover(Employees[i]);
            currManager = currManager.NextApprover;
        }

        LineManager.Approve(400);
    }
}

simple enough, we create a reference  to the first node in our chain, then within the loop we build our chain. then when we submit our expense to our first node, if it can handle it, it does otherwise it passes it to the next node in the chain and so on, till their are no more nodes. now we could have created a final terminating node with some sort of business logic, but for a trivial reminder, it seemed like a bit overkill.

Thursday, 2 November 2017

Share Internals with other assemblies

Once in a while especially when you are unit testing you may want to expose classes, functions/methods, properties, fields, etc to another assembly, to do this all you have to do is in the AssemblyInfo.cs class of you the assembly whose internals you want to expose add the attrinbute

[assembly: InternalsVisibleTo("Namespace.of.assembly.to.have.access.to.internals")]

msdn InternalsVisibleTo

Sunday, 29 October 2017

Builder Pattern

The builder pattern is used to separate logic from data, it's defined as "Separation of the construction of a complex object from its representation so that the same construction process can be used to create multiple representations." What we are aiming for is to reuse common logic to create objects of the same type but different representations.

For example let's look at making a three part dinner, so to me a three part dinner is composed of a protein, a starch and a salad; i basically eat this for dinner almost everyday, but the components of the dinner vary. one day i might do Salmon, spinach, yams, another day i might do chicken breast, caesar salad and buckwheat. the point is that the dinner itself is the same, but the components of the dinner are different.

To get started we are going to need a Dinner class that store all of the properties of our dinner

enum ProtienStyle {raw = 0, bloody = 10, rare = 30, medium = 60, wellDone = 90 }
enum Protien { Chicken= 1, Turkey=2, Salmon=4, Ostrich=8, Squid=16, Bison=32 }
enum Green { Cabbage = 1, Salad = 2, Spinach = 4, Pickles = 8, Cucumber = 16, Peppers = 32, Carrots = 64 }
enum Starch { Yams, Potatos, Buckweat, Bread }

class Dinner
{
    public ProtienStyle ProtienStyle { get; set; }
    public Protien Protien { get; set; }
    public Green Salad { get; set; }
    public Starch Starch { get; set; }

    public string Display()
    {
        var sb = new StringBuilder();
        string protiens = Enum.GetValues(typeof(Protien)).Cast<Protien>()
            .Where(p => (p & Protien) == p)
            .Select(g => g.ToString())
            .Aggregate((x, y) => $"{x}, {y}");

        sb.AppendLine($"Protien:{protiens} are {ProtienStyle.ToString()}");
        sb.AppendLine($"Starch:{Starch.ToString()}");

        string ingredients = Enum.GetValues(typeof(Green)).Cast<Green>()
            .Where(i => (i & Salad) == i)
            .Select(g => g.ToString())
            .Aggregate((x, y) => $"{x}, {y}");

        sb.AppendLine($"Salad:{ingredients}");

        return sb.ToString();
    }

}

above we define our dinner class, which stores the various components of our dinner next we need to define an abstract dinner builder.

abstract class DinnerBuilder
{
    public Dinner Dinner { get; private set; } = new Dinner();
    public abstract void MakeSalad();
    public abstract void CookStarch();
    public abstract void CookMeat();

}


this class defines the abstraction that our concrete implementations are going to have to define, next let's look at our implementations

class SeafoodDinner : DinnerBuilder
{
    public SeafoodDinner() => Dinner.ProtienStyle = ProtienStyle.raw;
    public override void CookMeat() => Dinner.Protien = Protien.Salmon | Protien.Squid;
    public override void CookStarch() => Dinner.Starch = Starch.Yams;
    public override void MakeSalad() => Dinner.Salad = Green.Cabbage;
}

class SurfAndTurfDinner : DinnerBuilder
{
    public SurfAndTurfDinner() => Dinner.ProtienStyle = ProtienStyle.rare;
    public override void CookMeat() => Dinner.Protien = Protien.Bison | Protien.Squid;
    public override void CookStarch() => Dinner.Starch = Starch.Buckweat;
    public override void MakeSalad() => Dinner.Salad = Green.Salad | Green.Peppers;

}

we can see that this implementations of our Builder class really have no logic, they just hold our data, now our logic is in our DinnerCooker class, this would be referred to as the director.

class DinnerCooker
{
    DinnerBuilder _dinnerBuilder;
    public DinnerCooker(DinnerBuilder dinnerBuilder)
        => _dinnerBuilder = dinnerBuilder;

    public void CookDinner()
    {
        _dinnerBuilder.CookStarch();
        _dinnerBuilder.CookMeat();
        _dinnerBuilder.MakeSalad();
    }

    public Dinner GetDinner() => _dinnerBuilder.Dinner;

}

in our data cooker, is where the logic sits; the order you'd create your dinner, you'd start with your starch because that takes the longest, then you'd start your meat, and then while those two where cooking you'd make your salad.

now let's take a look at our main

class Program
{
    static void Main(string[] args)
    {
        var dc1 = new DinnerCooker(new SeafoodDinner());
        dc1.CookDinner();
        Console.WriteLine(dc1.GetDinner().Display());

        var dc2 = new DinnerCooker(new SurfAndTurfDinner());
        dc2.CookDinner();
        Console.WriteLine(dc2.GetDinner().Display());
    }

}

and as you can see we create our dinnerCooker and pass in our builder to it; the cooker then uses the data in the builder to create our dinner.

using System;
using System.Linq;
using System.Text;

namespace pc.patternBuilder
{
    enum ProtienStyle { raw = 0, bloody = 10, rare = 30, medium = 60, wellDone = 90 }
    enum Protien { Chicken = 1, Turkey = 2, Salmon = 4, Ostrich = 8, Squid = 16, Bison = 32 }
    enum Green { Cabbage = 1, Salad = 2, Spinach = 4, Pickles = 8, Cucumber = 16, Peppers = 32, Carrots = 64 }
    enum Starch { Yams, Potatos, Buckweat, Bread }
    class Dinner
    {
        public ProtienStyle ProtienStyle { get; set; }
        public Protien Protien { get; set; }
        public Green Salad { get; set; }
        public Starch Starch { get; set; }

        public string Display()
        {
            var sb = new StringBuilder();
            string protiens = Enum.GetValues(typeof(Protien)).Cast<Protien>()
                .Where(p => (p & Protien) == p)
                .Select(g => g.ToString())
                .Aggregate((x, y) => $"{x}, {y}");

            sb.AppendLine($"Protien:{protiens} are {ProtienStyle.ToString()}");
            sb.AppendLine($"Starch:{Starch.ToString()}");

            string ingredients = Enum.GetValues(typeof(Green)).Cast<Green>()
                .Where(i => (i & Salad) == i)
                .Select(g => g.ToString())
                .Aggregate((x, y) => $"{x}, {y}");

            sb.AppendLine($"Salad:{ingredients}");

            return sb.ToString();
        }
    }

    abstract class DinnerBuilder
    {
        public Dinner Dinner { get; private set; } = new Dinner();
        public abstract void MakeSalad();
        public abstract void CookStarch();
        public abstract void CookMeet();
    }

    class SeafoodDinner : DinnerBuilder
    {
        public SeafoodDinner() => Dinner.ProtienStyle = ProtienStyle.raw;
        public override void CookMeet()
            => Dinner.Protien = Protien.Salmon | Protien.Squid;
        public override void CookStarch()
            => Dinner.Starch = Starch.Yams;
        public override void MakeSalad()
            => Dinner.Salad = Green.Cabbage;
    }

    class SurfAndTurfDinner : DinnerBuilder
    {
        public SurfAndTurfDinner() => Dinner.ProtienStyle = ProtienStyle.rare;
        public override void CookMeet()
            => Dinner.Protien = Protien.Bison | Protien.Squid;
        public override void CookStarch()
            => Dinner.Starch = Starch.Buckweat;
        public override void MakeSalad()
            => Dinner.Salad = Green.Salad | Green.Cucumber | Green.Peppers;
    }

    class DinnerCooker
    {
        DinnerBuilder _dinnerBuilder;
        public DinnerCooker(DinnerBuilder dinnerBuilder)
            => _dinnerBuilder = dinnerBuilder;

        public void CookDinner()
        {
            _dinnerBuilder.CookMeet();
            _dinnerBuilder.CookStarch();
            _dinnerBuilder.MakeSalad();
        }

        public Dinner GetDinner() => _dinnerBuilder.Dinner;
    }


    class Program
    {
        static void Main(string[] args)
        {
            var dc1 = new DinnerCooker(new SeafoodDinner());
            dc1.CookDinner();
            Console.WriteLine(dc1.GetDinner().Display());

            var dc2 = new DinnerCooker(new SurfAndTurfDinner());
            dc2.CookDinner();
            Console.WriteLine(dc2.GetDinner().Display());
        }
    }
}