Monday, 14 October 2019

The Decorator pattern, pragmatism and Glowing Cats

The Decorator Pattern

After a couple of days of engaged debate between colleagues on the matter of the Decorator pattern, and I taking the side to NOT use it for a particular situation, due to it being unnecessary and at risk of becoming an anti-pattern, I was inspired to write a post.

Implementing a pattern for the sake of it without having a real need for it and based on poor judgement on how the code will realistically change over time, is in my opinion, wrong.

The decision to adopt a pattern should always come from a pragmatic mindset.

The Decorator Pattern being an example of this.

The Problem

Most patterns, like the Decorator pattern are designed to solve specific problems. If the problem doesn't exist, then you don't need it, unless you truly anticipate that problem becoming reality.

The YAGNI principle.

The Decorator pattern can be used to combat the problems/limitations of traditional inheritance with a complex hierarchy and multiple layers.

Inheritance is sufficient for simple scenarios, such as below:


Here, you can see an Animal abstract class with a single abstract method called Animate(). The subclasses here are Dog and Cat.


The purpose of the Animate method is for the animal to act out what comes natural to the animal. For example, a dog barks and wags it's tail and a cat meows and purrs (and occasionally attacks you).




For thousands of years, domesticated animals haven't required levels of inheritance beyond this, until recently!

The modern age and it's scientific breakthroughs in gene editing has seen us modifying genes of living organisms using biological nanotechnology, such as CRISPR. 

This, of course, would only ever lead to one thing; GLOWING CATS!


Read more on glowing cats


I know, right?

Now, what if I wanted to edit the glowing cats genes to have red eyes?

And what if I wanted it to wag it's tail?

This means that our inheritance hierarchies will become complex.






These emerging complex inheritance hierarchies would now begin to look like this:



Now, what if I wanted the inheritance to be dynamic, so that it supports all possible combinations inheritance?


What if I wanted to change the order that these genes were edited?


What if I wanted a cat that didn't glow and just had the red eyes and the tail wagging?


Or what if I just wanted the tail wagging?


Or any other permutation you can think of?



The problem with using inheritance for this solution is that the hierarchy is static and declared at compile time.

And because C# doesn't support multiple inheritance that limits us to getting anywhere close to supporting such a dynamic structure.

Therefore simple inheritance is not suitable for scenarios like this, that have several layers of inheritance which might need to be interchangeable.


The Solution


This is where the Decorator pattern comes in.

Thousands of years ago, when the Object Oriented Gods designed the Animal abstract class and it's domesticated Cat and Dog children, they didn't anticipate humans discovering gene editing.

I wouldn't expect them to have already defined a Decorator class. But that's good and they shouldn't have had to, there was no need for it, the problem didn't exist yet.

We now have a need for it, and so we can create it now.

Look at this diagram:




Notice the AnimalDecorator class inheriting from the Animal class. This is the Decorator class.
(Note: Interfaces (e.g. IAnimal) can be used instead of inheritance, but for this example I've kept it an inheritance problem)

The purpose of this class is to chain inheritance together dynamically at runtime.

It does this by being both the Animal, and accepting within it, it's Animal predecessor. (This sounds wiser than intended)

It's subclasses are the various children that would have inherited directly from the Cat class.

Now, this means that at runtime we can dynamically control and alter the hierarchy in any order we can imagine and for whatever purpose is needed. We are no longer bound to the static compile time  inheritance hierarchy.


The Code

void Main()
{  
 var c = new Cat();
 var gc = new GlowingCatDecorator(c);
 var cre = new CatWithRedEyesDecorator(gc);
 var cwt = new CatThatWagsTailDecorator(cre);
 Console.WriteLine(cwt.Animate());
}


 Output












The above code shows the beauty of the Decorator pattern, in that we have the complete freedom to extend behaviour in any way we see fit, rather than being limited to a static inheritance hierarchy.


class AnimalDecorator : Animal
{
 private Animal _animal;

 public AnimalDecorator(Animal animal)
 {
  _animal = animal;
 }

 public override string Animate()
 {  
  return _animal.Animate();
 }
}

The Decorator class is both the Animal, whilst containing the instance of it's animal predecessor. The idea is that we are chaining/extending behaviour together.


class GlowingCatDecorator : AnimalDecorator
{
 public GlowingCatDecorator(Animal animal): base(animal){} 

 public override string Animate()
 {
  var a = base.Animate();
  return a + "\n*Glows*";
 }
}

class CatWithRedEyesDecorator : AnimalDecorator
{
 public CatWithRedEyesDecorator(Animal animal): base(animal){}

 public override string Animate()
 {
  var a = base.Animate();
  return a + "\n*Evil red eyes*";
 }
}

class CatThatWagsTailDecorator: AnimalDecorator
{
 public CatThatWagsTailDecorator(Animal animal): base(animal){}

 public override string Animate()
 {
  var a = base.Animate();
  return a + "\n*Wags tail*";
 }
}

Notice how the concrete classes of the AnimalDecorator are invoking base.Animate(), calling upon the Animal higher up in the inheritance hierarchy chain.

I love this design pattern, it's useful tool for implementing dynamic run-time inheritance. This does not mean you should start implementing it for all your classes in the unlikely case that all your classes will need extension. If you wish to extend a class, most of the time simple inheritance will suffice. If it needs further extension later, and you want those extensions to be dynamic then consider using this pattern.