Sunday, March 14, 2010

Has is better than Is!
Objects can have a , “have a” relationship or “is a” relationship with other objects. If that makes no sense check it out below:
Has A

public class SpaceShip
{
public void FireMissiles()
{
Console.WriteLine("Missiles Fired");
}
public void GoLightspeed()
{
Console.WriteLine("Gone Lightspeed");
}
}
public class Fighter : SpaceShip
{
}
public class Freighter : SpaceShip
{
}
class Program
{
static void Main(string[] args)
{
Fighter fighter = new Fighter();
Freighter freighter = new Freighter();
fighter.FireMissiles();
freighter.FireMissiles();
}
}


Can you see the problem? The Freighter has inhertied or “is a” relation ship with SpaceShip. So it has fired missles when it doesnt carry any. Hmmmm
Lets fix it with a “is a” relation ship

public class SpaceShip
{
public int FuelLevel { get; set; }
public int MissilesRemaining { get; set; }
public void FireMissiles()
{
Console.WriteLine("Missiles Fired");
}
public void GoLightspeed()
{
Console.WriteLine("Gone Lightspeed");
}
}
public class Fighter
{
private SpaceShip spaceShip;
public Fighter()
{
spaceShip = new SpaceShip();
}
public void FireMisslesFromBaseClass()
{
spaceShip.FireMissiles();
}
}
public class Freighter
{
private SpaceShip spaceShip;
public Freighter()
{
spaceShip = new SpaceShip();
}
public void GoLightSpeedFromBaseClass()
{
spaceShip.GoLightSpeed();
}
}
As you can see the freighter can no longer call the method FireMissles() , it would cause a compiler error so our bug would be picked up at compile time instead of runtime. However it can but it can GoLightSpeed()!

Apologies for any typos I am typing the code in word