Marker Interfaces

May 24, 2011 design-patterns

In Snowball I was debating adding an empty interface to identify certain classes in my framework as components. I wasn't sure if this was code smell or not so I did some searching on Stackoverflow and found out this concept is actually called "Marker Interfaces". Learn something new every day.

Favoring Composition over Inheritance

You may have heard the expression before "Favor Composition over Inheritance", but do you know what it means and how to apply it? Lets take this code for example:

abstract class Car
{
	public Color Color { get; protected set; }
	public Engine Engine { get; protected set; }
}

class ElectricCar : Car
{
	public ElectricCar()
	{
		this.Color = Color.Blue;
		this.Engine = new ElectricEngine();
	}
}

class SportsCar : Car
{
	public SportsCar()
	{
		this.Color = Color.Red;
		this.Engine = new V8Engine();
	}
}

class Truck : Car
{
	public Truck()
	{
		this.Color = Color.White;
		this.Engine = new DieselEngine();
	}
}

In this contrived example, we've defined three types of cars. Each instance of each of the cars will always have the same color and same engine. What happens when we need a 4th type? We have to define another class. By refactoring this code, we can compose a car type by giving it a color and an engine:

class Car
{
	public Color Color { get; private set; }
	public Engine Engine { get; private set; }
	
	public Car(Color color, Engine engine)
	{
		this.Color = color;
		this.Engine = engine;
	}
}

Car electricCar = new Car(Color.Blue, new ElectricEngine());
Car sportsCar = new Car(Color.Red, new V8Engine());
Car truck = new Car(Color.White, new DieselEngine());
Car familyCar = new Car(Color.Black, new V4Engine());

Now we can compose many car types, with any combination of colors and engines and we've only defined one class.

Implementing basic Dependency Injection using a Service Container

By extending your Service Container class, a very basic version of dependency injection can be implemented. We'll implement two forms of dependency injection: constructor and property injection.

Read More