Why Patterns Do Not Suck... Part 1


Never meant the opposite though, but inserting "...sucks" in the title seems fashionable these days.

Not that I am "pattern happy" (or at least not that I am aware of) but when you recognize where a pattern might fit without overcomplicating the design, you better use it. That's what they were meant for.

When learning patterns I found pretty difficult finding simple "real world" examples (and it is not that none of us creates a hierarchy of animals on a daily basis, God forbid!) where the patterns can be explained and that lever inside your brain turns to tell you "Of course, this makes sense now".

Not that there aren't fine examples, but I'd like to add more if I am allowed. And the blog-o-sphere is free enough to allow me doing so.

So, let's say that you are working with classes that have a somewhat similar API, but for some reason you can't use a common ancestor to use them. Whatever reason applies: bad design, not similar enough to extract a common interface, code-base not owned,... you name it. Looks like a perfect job for the Adapter Pattern (link and link) that aims for "letting classes with incompatible interfaces work together".

Even if we knew nothing of patterns and we had to come with a design solution for the problem, I am pretty sure that we might have come with a similar solution. And that's the beauty of it. Patterns are nothing fancy when applied "for the good". They serve as a common language and are there to provide some hints when you have the feeling of "something similar has to have been done before".

An example of one of the aforementioned cases might wanting to access the indexers of a NameValueCollection and an IDictionary<string, string> in an unified manner, without being aware that different classes are behind the scenes.

Simple enough, we create an abstraction for the functionality we want to share. And the shape of abstraction I have chosen is a very simple abstract class that defines the interface of a generic read/write indexer:

Once we have the abstraction we will need to create the corresponding adapter classes, that are dead-simple as well. For example, for a generic dictionary:

And there we go. We might use it as follows:

It´s not the most valuable snippet ever, because it does not express the power of the pattern. But waht about his one?

And that's all. Why did I chose to start with this Adapter pattern? It's very simple, I had the example at hand and it will be used in another post on design patterns...

Enjoy it

share class