Showing posts with label Patterns. Show all posts
Showing posts with label Patterns. Show all posts

Tuesday, 6 November 2012

Singleton and Dependency Injection

Ayende wrote this great blog post on the Singleton pattern, I always enjoy these kinds of posts from him because he looks at them from a real world perspective. It reminded me to make a specific subtle point on Singleton and that is:
Most of the issues that people have with the Singleton aren’t with the notion of the single instance, but with the notion of a global static gateway, which means that it becomes very hard to modify for things like tests, and it is easy to create code that is very brittle in its dependencies on its environment.
This has often lead to statements about statics/singletons are evil. But they don't have to be. You should continue to create objects that utilize dependency injection and abstractions and make sure they are decoupled from such statics or instances. The way you do this is very simple: Here is some typical Singleton (Implementations may vary): So when using this you have a choice, you can either use it this way: The above usage is very hard to test and doesn't allow me to change the implementation of the GetRaise method. Another big problem is the Dishonest API, there is no indication when I create the object or call the method that there is a hidden dependency to Manager which is a typical problem with using Singletons and statics like this. The solution is to rather ask for the instance and not let your class know about the singleton at all: Now I can test and change the implementation as I like, for example create a new derivative: If you don't like the manual approach, these days IoC containers are everywhere and the setup for example StructureMap is this easy: The above will just use the default Singleton instance to resolve. But you can also override it as follows: These techniques are indeed very basic but so often overlooked. The singletons are not evil when used correctly but must remain living in the root layer of your application where all the calls are made initially.

Saturday, 14 April 2012

Chain Of Responsibility: Why Can't Programmers Program?

According to CodingHorror he was battling to understand why:

Like me, the author is having trouble with the fact that 199 out of 200 applicants for every programming job can't write code at all. I repeat: they can't write any code whatsoever.

In order to make sure that the applicant could write code they would ask them to perform a simple task:

Write a program that prints the numbers from 1 to 100. But for multiples of three print "Fizz" instead of the number and for the multiples of five print "Buzz". For numbers which are multiples of both three and five print "FizzBuzz".

Most good programmers should be able to write out on paper a program which does this in a under a couple of minutes.

But Apparently:

Want to know something scary? The majority of comp sci graduates can't. I've also seen self-proclaimed senior programmers take more than 10-15 minutes to write a solution.

So apparently a number of companies use this question to quickly eliminate those who can't write any code. When I first heard of this I was surprised and thought what is the catch.

Would the person asking this be expecting some really fancy implementation?

But what the person is really looking for is to write it so that it just works exactly as requested

You can look at this page or search for examples which are available in just about every language out there, but here is the C# code:

public void Main()
{
    for (int
i = 1; i <= 100; i++)
    {
        FizzBuzz(i);
    }
}


public void FizzBuzz(int
value)
{
    if
(value % 3 == 0 && value % 5 == 0)
    {
        Console.WriteLine("FizzBuzz"
);
    }
    else if
(value % 3 == 0)
    {
       Console.WriteLine("Fizz"
);
    }
    else if
(value % 5 == 0)
    {
       Console.WriteLine("Buzz"
);
    }
    else
    {
       Console
.WriteLine(value);
    }
}

Now you can certainly try and get more fancy about this and some have certainly done so, but I thought it would be valuable to be able to write this and then say what fundamental principle are you violating and how to solve it.

The Chain Of Responsibility

The above example can be thought of in a real world application with various conditions for each of the inputs and providing a different implementation for each. And in this case this is a violation of a fundamental principle called the Open/closed principle

And in the above implementation we might want to add a check for the number divisible by 10 and print out Bazz. This certainly means our function is not Closed for modifications as we would have to add another code block and modify the if-else logic.

One solution to this problem would be to create one strategy per implementation and use the Chain-of-responsibility pattern

First create a printer object for any ancestor in the chain:

public abstract class Printer
{
    private Printer
_Next;
    public Printer SetNext(Printer
next)
    {
       this
._Next = next;
       return
next;
    }

    protected abstract bool HandlePrint(int
value);

    public virtual bool Print(int
value)
    {
        if (!this
.HandlePrint(value))
        {
           if (this._Next != null
)
           {
              return this
._Next.Print(value);
           }
           return false
;
        }
        return true
;
    }
}

The abstract method HandlePrint gets a value and it is up to the strategy to decide whether it supports the given value and handles the request. It can either stop processing or let the processing continue further down the chain.

And then we would have an implementation for each of the printing strategies:

public class FizzBuzzPrinter : Printer
{
    protected override bool HandlePrint(int
value)
    {
       if
(value % 3 == 0 && value % 5 == 0)
       {
           Console.WriteLine("FizzBuzz"
);
           return true
;
        }
        return false
;
    }
}


public class FizzPrinter : Printer
{
    protected override bool HandlePrint(int
value)
    {
        if
(value % 3 == 0)
        {
            Console.WriteLine("Fizz"
);
            return true
;
        }
        return false
;
    }
}


public class BuzzPrinter : Printer
{
    protected override bool HandlePrint(int
value)
    {
       if
(value % 5 == 0)
       {
           Console.WriteLine("Buzz"
);
           return true
;
       }
       return false
;
    }
}

Also we can now very easily add the ability to check for 10 and print Bazz by registering a new handler.

public class BazzPrinter : Printer
{
    protected override bool HandlePrint(int
value)
    {
        if
(value % 10 == 0)
        {
            Console.WriteLine("Bazz"
);
            return true
;
        }
        return false
;
     }
}

Now our implementation of our printing engine can be closed to modifications:

public void Main()
{
    Printer printer = new FizzBuzzPrinter
();
        printer
          .SetNext(
new BazzPrinter
())
          .SetNext(
new FizzPrinter
())
          .SetNext(
new BuzzPrinter
());

// Add bazz printer

    for (int
i = 1; i <= 100; i++)
    {
        Console.Write(string.Format("{0}:"
, i));

        if
(!printer.Print(i))
        {
            Console
.WriteLine();
        }
     }
}

image

So there you have it the solution can and is simple initially provided you know what the potential violation is and problems that can be caused down the line. And once you made more than 2-3 modifications to it its time to think about refactoring it.

Live writer was harmed 5 times during the making of this post.

Wednesday, 23 November 2011

Building your own IoC Container

I have been meaning to do a series on IoC containers so I finally thought of starting with this introduction. 

Before getting into the details let me just introduce you to the problem. IoC is all about DI and object creation.

In fact you can think a little bit about an abstract factory. Except with one major difference and that is the client class never even knows about the existence of the IoC Container (factory). I found this blog where this is actually explained very nicely by a simple table:

Dependency Injection as compared with Abstract Factory.
Characteristic DI AF
Is responsible for instantiating classes? Yes Yes
Class needs to know details of the created object? No No
Class needs to explicitly request creation of desired object? No Yes
Class is dependent upon the DI/Factory that creates objects on its behalf? No Yes

Another good explanation:

From Castle Windsor's Website:

Inversion of Control is a principle used by frameworks as a way to allow developers to extend the framework or create applications using it. The basic idea is that the framework is aware of the programmer's objects and makes invocations on them.

This is the opposite of using an API, where the developer's code makes the invocations to the API code. Hence, frameworks invert the control: it is not the developer code that is in charge, instead the framework makes the calls based on some stimulus.

There is another explanation on Wikipedia

Those sites do a real good job of explaining the concept that can be hard to understand.

The most important thing to understand is that IoC Containers are JUST tools and even though they may be described as patterns your code should not depend on them and it is merely a tool to facilitate dependency injection. Their job is to remove concrete references or instantiations in the code base and restrict it to one place called the Composite root.

Now before you dive in, there are LOTS of these frameworks already written and I mean lots, at first I thought there were many, but then i found Scott Hanselman’s blog on the containers available and they are even more.

Building your own

So if there are so many ones out there and they have so many features why would you even bother?

Because when i show you how incredibly simple and little code the most basic implementation is you will get a better understanding what it is about and what you might expect out of a library if you plan to use one in the future.

And since it is only about a screen full of code it is easy to absorb.

Lets say I have some Interfaces:

Code Snippet
  1. public interface IFoo
  2.     {
  3.         void DoSomething();
  4.     }
  5.  
  6.     public interface IBar { }

IFoo is something that implements some functionality and IBar will just pretend to be some dependency.

Then I have some objects implementing Foo

Code Snippet
  1. public class FooBase : IFoo
  2.     {
  3.         private IBar _bar;
  4.  
  5.         public FooBase(IBar bar)
  6.         {
  7.             this._bar = bar;
  8.         }
  9.  
  10.         public void DoSomething()
  11.         {
  12.             Console.WriteLine(string.Format("{0} doing something to {1}"this.GetType().FullName, this._bar.GetType().FullName));
  13.         }
  14.     }
  15.  
  16.     public class FooImplementation1 : FooBase
  17.     {
  18.         public FooImplementation1(IBar bar)
  19.             : base(bar)
  20.         {
  21.         }   
  22.     }
  23.  
  24.     public class FooImplementation2 : FooBase
  25.     {
  26.         public FooImplementation2(IBar bar)
  27.             : base(bar)
  28.         {
  29.         }  
  30.     }

Then we can also create 1 or 2 dummy example IBar dependencies:

Code Snippet
  1. public class Bar1 : IBar { }
  2.  
  3. public class Bar2 : IBar { }

Now you can probably imagine that normally we would create these objects something like:

Code Snippet
  1. IFoo foo = new FooImplementation1(new Bar1());

But that is of course hardcoding all the concrete implementations and dependencies manually.

Using an IoC container it looks like this:

Code Snippet
  1. var container = new Container()
  2.     .Bind<IFoo, FooImplementation1>()
  3.     .Bind<IBar, Bar1>();

You create your container  in your composition root, and map the types to your concrete implementations.

Then you resolve your objects:

Code Snippet
  1. var foo = container.Resolve<IFoo>();
  2. foo.DoSomething();

The container knows that IFoo is mapped to concrete type FooImplementation1, and that a dependency is required to IBar, it can then also resolve that instance since we also provided it.

Here is how to build this incredibly simple container:

Code Snippet
  1. public class Container
  2.     {
  3.         Dictionary<Type, Func<object>> _resolvers;
  4.  
  5.         public Container()
  6.         {
  7.             this._resolvers = new Dictionary<Type, Func<object>>();
  8.         }
  9.  
  10.         public Container Bind<T, U>()
  11.         {
  12.             return this.Bind<T>(() => (T)this.ActivateInstance(typeof(U)));
  13.         }
  14.  
  15.         public Container Bind<T>(Func<T> resolver)
  16.         {
  17.             this._resolvers[typeof(T)] = () => resolver();
  18.             return this;
  19.         }
  20.  
  21.         public object Resolve(Type type)
  22.         {
  23.             Func<object> ctor = null;
  24.             if (this._resolvers.TryGetValue(type, out ctor))
  25.             {
  26.                 return ctor();
  27.             }
  28.             throw new Exception(string.Format("Cannot resolve type: {0}", type.FullName));
  29.         }
  30.  
  31.         public T Resolve<T>()
  32.         {
  33.             return (T)this.Resolve(typeof(T));
  34.         }
  35.  
  36.         private object ActivateInstance(Type type)
  37.         {
  38.             var constructor = type.GetConstructors()[0];
  39.             var parameters = constructor.GetParameters();
  40.             var inputParameters = new object[parameters.Length];
  41.             for (int i = 0; i < inputParameters.Length; i++)
  42.             {
  43.                 var parameter = parameters[i];
  44.                 inputParameters[i] = Resolve(parameter.ParameterType);
  45.             }
  46.             return constructor.Invoke(inputParameters);
  47.         }
  48.        
  49.     }

That’s it!, that is all the code. Of course even though this example is a little naive it may work for you just as is in the real word, will fall a bit short of the many edge cases you may run into in the real world. But that is OK, even though you could use this understanding and dive right into the more mature frameworks. Or you could extend this example and create providers or wrappers to some of the other libraries out there which can probably be a good idea if you may decide to change in the future. Even if some may argue that this is not necessary.

You will notice that there are 2 ways to bind objects first is to map an interface to a concrete class. The second is to map an interface to a lambda function that provides the concrete instance. Just adding this very simple method makes it quite a bit more flexible so you could do this:

Code Snippet
  1.  
  2. var foo3 = container
  3.     .Bind<IFoo>(() => new FooImplementation1(container.Resolve<IBar>()))
  4.     .Resolve<IFoo>();
  5.  
  6. foo3.DoSomething();

That’s it for this article. Look for future posts where I will be looking at other frameworks and cases that you will run into and want to deal with.

Saturday, 29 October 2011

OO Enums

I was looking for feedback on my previous post about Enum Visitors.

I was literally inundated with feedback from 1 person:

The Article lacks the why

and

Why would i want to do this if an enum is:

  • What I know
  • Easy to understand
  • Performs well

Clearly this looks like many reasons not to fuss.

There are even more things in favour of the enum like the bitwise operations.

I welcome this criticism because I, much like other programmers often fixate on a certain solution or implementation and forget what the original problem was or even if there really was one and why we wanted to solve it in the first place.

I do not advocate to add complex patterns to your code base just for the sake of using the pattern.

And even though I think a part of me  was trying to solve a problem that perhaps isn’t such a big problem but to see if I could come up with something decent.

So lets look at the reasons NOT to use my method.

It’s added complexity for some.

Enums are FAST, and I mean VERY fast, got say 1-5 enums even with the most tweaked dictionary the switch statement will be much faster.

You may run into a scenario where you have 100ds of enums where the performance goes the other way, but in this case you probably wont be using enums anyway.

And I can possibly think of scenarios like high speed logging, where you might want to think a bit more about how your performance may be affected

That’s about the last i will say about the performance, because I feel that unless you are running VERY tight loops with 1000ds of iterations this will be a fraction of your programs execution time for either of these methods.

Many people reduce OO/Layers or abstractions to gain performance and there are times you simply have no other choice, however I feel that favouring ease of use and maintenance over performance where acceptable is often a better choice.

But either way there might be situations I will be the first to say DON’T use this way.

But lets look at why this might be a good idea.

Having a switch statement you may introduce many pathways through your code known as Cyclomatic Complexity.

This means it becomes hard to test the function entirely without stimulating it with ALL the options the enumeration provides.

If we invert this operation and instead of switching over an enum we use a visitor or strategy map it is a little bit like the Hollywood Principle (Don’t call us, We’ll call you)

In fact if you think about it this is one of those really cool and catchy terminologies, but often it is described in a way that is hard to understand.

And I don’t see in the description that they refer to this or the visitor even though i feel this is appropriate.

I have read MANY places that people constantly refer to OCP (Open-Close principle), and how the switch statement violates this.

And  I somewhat agree, when you switch around many conditions, as soon as 1 or more of those conditions change the code that is switching around them needs change.

This means the system must change and cannot just be extended by adding a strategy class or a visitor method.

However you still need to make a change the only difference is where. If you have added switch logic over the same enum on many places then changing an enum changes the code in all those places.

The difference between the visitor/strategy and the switch statement is that with the switch statement it is YOU the caller or consumer that needs change. YOU need to decide which type you are dealing with and write the if-else or switch logic to control the flow of the code, you may do this MANY times and this increases your responsibility of future change instead of just being concerned of the business logic of your program.

Using a strategy or visitor you simply call the Accept method or execute on the strategy and can only focus on the business logic you should be concerned of.

The flow of execution is inverted and this is the important concept to understand.

Of course this is just one abstraction, the decision is made somewhere and when the enum changes so does the somewhere. So you may have a situation where you only need to make a code decision for your application in ONE place.

Take this example:

public enum MessageType
{
Unknown,
Message,
Success,
Highlight,
Error
}

Say this is just a simple enumeration to use in our code to log certain status messages now we could switch around the code like this:

Would result in code such as this:

void LogMessageWithEnum(MessageType messageType, string message)
{
switch (messageType)
{
case MessageType.Message:
Console.ForegroundColor = ConsoleColor.White;
break;

case MessageType.Success:
Console.ForegroundColor = ConsoleColor.Green;
Console.WriteLine(message);
Console.ForegroundColor = ConsoleColor.White;
break;

case MessageType.Highlight:
Console.ForegroundColor = ConsoleColor.Yellow;
Console.WriteLine(message);
Console.ForegroundColor = ConsoleColor.White;
break;

case MessageType.Error:
Console.ForegroundColor = ConsoleColor.Red;
Console.WriteLine(message);
Console.ForegroundColor = ConsoleColor.White;
break;
}

If this is converted to a visitor:

public class MessageTypeVisitor
{
public MessageTypeVisitor(string message, bool newLine)
{
this.Message = message;
this.NewLine = newLine;
}

void LogMessage(string message)
{
if (NewLine)
Console.WriteLine(this.Message);
else
Console.Write(this.Message);
}



[EnumVisitor(MessageType.Message)]
public void LogMessage()
{
Console.ForegroundColor = ConsoleColor.White;
Console.WriteLine(this.Message);
}

[EnumVisitor(MessageType.Success)]
public void LogSuccess()
{
Console.ForegroundColor = ConsoleColor.Green;
Console.WriteLine(this.Message);
Console.ForegroundColor = ConsoleColor.White;
}

[EnumVisitor(MessageType.Highlight)]
public void LogHighlight()
{
Console.ForegroundColor = ConsoleColor.Yellow;
Console.WriteLine(this.Message);
Console.ForegroundColor = ConsoleColor.White;
}

[EnumVisitor(MessageType.Error)]
public void LogError()
{
Console.ForegroundColor = ConsoleColor.Red;
Console.WriteLine(this.Message);
Console.ForegroundColor = ConsoleColor.White;
}

public string Message { get; set; }

public bool NewLine { get; set; }
}

Using this will become as follows:

messageType.Accept(new MessageTypeVisitor(formattedMessage, newLine));

Now your code becomes more open-close, you could be asking an abstract factory or IoC container to provide you with a MessageTypeVisitor meaning your code would never have to change its logic based on what enumeration was provided.

Of course all this really is, is an abstraction, I can create a function LogMessageWithEnum and be done with it. My code that uses the LogMessageWithEnum is shielded from the underlying switch and decision making, and in some cases this may be the only place I use this enum, My code may not use this enum for any other reason. So by simply using a function I have created a sufficient abstraction and remain closer to Open-Close to my consuming code.

The problem really comes in when I have these same switch statements scattered around making the same or very similar decisions around this enumeration, in this case I haven't sufficiently abstracted myself from the use of this.

In conclusion

I wanted to create something for those times where you are looking for this type of solution. But not replace the enum or usage of this sparingly or in a way that makes sense. As always let your own common sense guide your solution.

Friday, 28 October 2011

My Hammers

 

If all you have is a hammer, everything starts looking like a nail

 

image image
* Image source * Image source

Have you ever felt like certain patterns/classes/libraries just work in EVERY situation or solves any problem that is REALLY HARD.

These certainly feel like hammers and in fact golden hammers in a world full of nails.

Of course you should always question yourself if it is on any extreme, and that if you are really trying to hit screws with hammers then maybe its time to think of another approach.

In any case I will talk about the tools that works for me in so many situations and that are most of the time, EASIER to understand, FASTER to write and more maintainable.

In either case I’m sure to never leave home without them

So let me jump in in no particular order…

#1. The Builder

image This feels appropriate to start with not just for the name but it takes care of all those complex creations you may have in an application.

If you find yourself saying:

I don’t want to use DI because it makes my object creation more complex.

Then you might want to consider using a builder.

The builder may also reduce or replace singletons in your application.

The builder pattern as described by Wikipedia:

The builder pattern is an object creation software design pattern. The intention is to abstract steps of construction of objects so that different implementations of these steps can construct different representations of objects. Often, the builder pattern is used to build products in accordance to the composite pattern, a structural pattern.

You can certainly read the documentation to an example implementation, but in fact just like all patterns they will vary greatly in their implementation and in my opinion they have added additional layers of complexity to this than what is needed.

The most important thing here is (abstract steps of construction).

So for instance just to follow on the concept of abstraction, in the documentation there is a use of a director, which is something you DON’T HAVE TO DO.

I found this post on stackoverflow with the exact same question.

So this really is just an abstraction to the steps of construction of an object and can be:

  1. A method.
  2. A Class with one method
  3. A Base class and many steps of construction, with many child builders
  4. A Class accepting other Builders as constructor arguments
  5. A Class with fluent API to specify some optional or additional properties.
  6. A Builder can be 1:1 or 1:* meaning being able to construct more than one type of object.

The organization of this logic is therefore determined to what makes sense and it depends on the size and complexity of construction, so I would extract more builders and base classes as construction complexity increases, the same rules as any class keep responsibilities only as big as they need to be.

With that said I will just pick an average example.

Say we had a controller which had a bunch of dependencies that needed creation, we could create the following builder:

public class ControllerBuilder
{
public Controller Build()
{
return new Controller(BuildDao());
}

protected virtual Dao BuildDao()
{
return new Dao(this.BuildContext());
}

protected virtual IDataContext BuildContext()
{
return new LinqDataContext();
}
}

And in our unit test project I can construct the exact same controller for my unit test, however modify override a small part to replace with the appropriate dependencies for in memory tests.

public class MemoryControllerBuilder : ControllerBuilder
{
protected override IDataContext BuildContext()
{
return new MemoryDataContext();
}
}

Usage of this then becomes something like this:

public class WebPage
{
public void Page1_Load()
{
Controller controller = new ControllerBuilder().Build();
}

public void Page2_Load()
{
Controller controller = new ControllerBuilder().Build();
}
}

The builder aids you application in achieving better Inversion of control, Dependency injection and still keeping things explicit

#2. The Dictionary

image The dictionary is probably one of the most powerful, flexible, high performing hammer/tool in modern languages like C# that is like sunlight, vital but often overlooked or taken for granted.

In the past many older languages never had dictionaries out of the box and third party vendors went out their way to create implementations of dictionaries, today in C# this is available out the box for FREE.

Many remember hash tables. And since generics in C# this became the generic Dictionary. They are in fact the same thing underneath.

Each object provides a GetHashCode() which is a unique key that the dictionary uses to sort objects for fast lookup.

The dictionary truly can turn many things into a nail, try to imagine wherever you used a dictionary for something what the alternative would be. You would find that the alternative is much less elegant and performing.

The dictionary makes many patterns SO EASY they seem trivial at worst for example:

Service Locators

Factories

Mappers

Also anything needing lookup, Dictionaries are great for:

Loose-Coupling and supporting principles like Open-Close.

The Dictionary can be responsible for many new powerful patterns.

If you browse to Wikipedia and look up Design Patterns you won’t really notice the mapper pattern really being documented even though in fact it should be.

By simply combining strategy and factory using a dictionary we can create a very powerful pattern to map objects from strings/enumerations or any constant type to abstractions and therefore following a whole bunch of good principles like Open-Close and so many other and yet this seems so simple we hardly think about it at all.

Example:

Say we have an enumeration as follows: (Simply indicating an environment that is configured)

public enum Environment
{
Production,
Test
}

The example is extremely trivial to keep things simple and short but imagine a situation where this can grow to a much larger size.

We would normally code this as follows:

switch (environment)
{
case Environment.Production:
return @"c:\production";
case Environment.Test:
return @"c:\test";
default:
throw new Exception("Invalid environment");
}

Once again the example is very simple, but pretend that we could be doing much more complicated things depending on environment.

If we wanted to convert this to the strategy pattern (also called provider). We would declare a provider like this:

public abstract class EnvironmentPathProvider
{
public abstract string GetPathName();
}

Then we would create the different strategies like this:

public class ProductionEnvironmentPathProvider : EnvironmentPathProvider
{
public override string GetPathName()
{
return @"c:\production";
}
}

public class TestEnvironmentPathProvider : EnvironmentPathProvider
{
public override string GetPathName()
{
return @"c:\test";
}
}

And now our usage looks like this:

public Dictionary<Environment, EnvironmentPathProvider> BuildProviderMap()
{
var map = new Dictionary<Environment, EnvironmentPathProvider>();
map.Add(Environment.Production, new ProductionEnvironmentPathProvider());
map.Add(Environment.Test, new TestEnvironmentPathProvider());
return map;
}

public string GetFileLocation(Environment environment)
{
EnvironmentPathProvider provider = null;
if (BuildProviderMap().TryGetValue(environment, out provider))
{
return provider.GetPathName();
}
throw new Exception("Invalid environment");
}

We added more code which seems unnecessary, but it is only in this initial example and after this our code will not increase much and we are much more open close and extensible in our program. And we are combining  more than one good OO principles.

So next time you use a dictionary spare a thought for this awesome hammer.

#3. The Lambda

image It will be hard to say how useful this really is and give enough reasons to say why.

I will try and say that when the books on design patterns were written they were written to take most languages into consideration. For the danger of not being hunted down by old elitists with long beards I will refrain from mentioning a language or specific. But I do believe that lambdas sometimes replaces the need for certain patterns.

From MDSN:

A lambda expression is an anonymous function that can contain expressions and statements, and can be used to create delegates or expression tree types.

The article provided also gives some great examples.

Linq would also not be possible without this. This also makes new patterns emerge like IoC, Factories, Mappers etc.

How to use this is probably beyond the scope of this article, it simply is that useful, this certainly is more than just a golden hammer but more like a platinum hammer in my toolbox.

 

#4. The Interface

image The ultimate abstraction.

There is no better way to isolate yourself from concrete implementations of code.

Interfaces also makes multiple inheritance possible without some of the trouble associated with it.

An interface contains only the signatures of methods, properties, events or indexers. A class or struct that implements the interface must implement the members of the interface that are specified in the interface definition.

From MDSN:

An interface contains only the signatures of methods, properties, events or indexers. A class or struct that implements the interface must implement the members of the interface that are specified in the interface definition.

Principles like ISP (Interface segregation principle) are worth noting and keeping in mind when designing interfaces.

So next time you are dealing with an external dependency or API library consider protecting yourself against the volatility of change and use interfaces.

#5. Linq

image Language integrated query:

Language Integrated Query (LINQ, pronounced "link") is a
Microsoft .NET Framework component that adds native data querying capabilities to .NET languages, although ports exist for Java[1], PHP and JavaScript.

I’d have to admit that this has increasingly become a more popular tool for me over time.

At first we saw linq as a great tool for querying databases particularly due to its type safety. But also for the provider support (one query can work on a number of platforms).

However from how this has grown for me over time and from what i see that can be done with this just within the language on objects, Lists, PLINQ.

Suddenly it just seems like so much effort to write

foreach (BaseController controller in controllers)
{
...
}

vs.

controllers.ForEach(controller => .. )

So that concludes the list of hammers for now, these might change over time but for now I consider them vital tools.