Archive for the ‘Programming’ Category

The Last Example Object Hierarchy You’ll Ever Need

Tuesday, September 9th, 2008

Explaining OO concepts to people is tricky when you’re using abstract names like class A extends B implements C.  So over the years I’ve come up with a system that I’m very happy with.  I share it with you here, dear reader.  It’s in Java, but it applies equally well to .NET languages.  C++ and other multiple inheritance developers need modify it only slightly to make Flier a mixin base class.

interface Flier {
    public void fly (int howFar);
}
abstract class Bird { }
abstract class FlyingBird extends Bird implements Flier { }
abstract class FlightlessBird extends Bird { }
abstract class Mammal { }
public class Robin extends FlyingBird {
    public void fly () { flapWings(); }
}
public class Penguin extends FlightlessBird { }
public class Squirrel extends Mammal { }
public class FlyingSquirrel extends Squirrel implements Flier {
    public void fly () { glide(); }
}

As vs. Is

Tuesday, September 9th, 2008

I was recently asked what the advantage is to using the C# as keyword as opposed to doing the classic type-in-parentheses style. Here’s the main difference in functionality, in case you were curious:

Mammal aMammal;
Walrus walrus = (Mammal) aMammal;
walrus.sharpenTusks();

That’ll work fine as long as aMammal really is a Walrus. If it’s not, an exception will be thrown. So we have to guard it like this:

Mammal aMammal;
if (aMammal is Walrus) {
    ((Walrus) aMammal).sharpenTusks();
}

Fine, that works, but it’s not as clean as this:

Mammal aMammal;
Walrus walrus = aMammal as Walrus;
if (null != walrus) {
    walrus.sharpenTusks();
}

If aMammal isn’t really a Walrus, the walrus variable will be null. Now there are a lot fewer parentheses floating around, and in my opinion it’s much cleaner. I wouldn’t recommend this if there are a lot of choices for the type, because you’d need n variables, one for each option. In that case, you’re probably better off using the is operator. But if you find yourself needing to use is a lot in the first place, you might consider your design a little. That’s a code smell that indicates you might want to introduce an abstract method into your base class.

Celtic cross