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.

Xna: Load Texture2D from Embedded Resource

If you’re writing an app which uses Xna, you may need to load a texture from an embedded resource. Here’s how:

First embed the resource in your app. Do so by choosing Embedded Resource as the Build Action in the properties of the resource.

Properties Dialog for a File

After that you can load the Texture2D using a stream handle to the embedded file.

Stream stream = Assembly.GetCallingAssembly().GetManifestResourceStream("AppNamespace.Folder.font.bmp");
return Texture2D.FromFile(graphicsDevice, stream);

GetCallingAssembly() can be exchanged with GetExecutingAssembly() if needed. The name of the resource must be fully qualified with the app’s namespace and folders. I usually keep my resources in a folder Resources so I would have: AppNamespace.Resources.font.bmp.

500 Downloads of the Same Game

My little Xna game that I wrote nearly 2 years ago reached the 500 downloads mark (binaries and source) the other day. With that said, I’d like to say that I’m working on version 2.0.

In version 2.0 I’m going to make the code more event driven. The old code uses the Xna Game class and in the new version I’ll be making it WinForms based. Almost a complete rewrite.

My work so far is available through SVN on the project’s Codeplex page.