Sort of IS-A

TL;DR

If it violates the Liskov Substitution Principle, then change it.

Nearly Is

I’ve discovered a noteworthy design anti-pattern recently. That’s not to say I’ve invented a new bad way of doing things, or even that this discovery is a surprise. I just mean I’ve seen a nest of code where this pattern is really not working.

The best way to summarise it, is something like this:

I want my object to have those properties, so I’m going to make it inherit them… but we’d better mark everything as non serializable, so it doesn’t get written to JSON.

This is the classic mistake of using implementation inheritance instead of composition. It’s further proven by the need to kind of disable the object behaving as a whole in terms of serialization.

The examples I’ve seen involve a class that contains header information, which needs to be stored out as a header in future, being inherited by something that contains the body too. The body is marked as non serializable, so the object can be serialized as though it’s JUST the header, then the body inside it is rendered separately and added on.

In fairness, the complete object does need fields like date and type which relate both to IT and the header it is pretending to be.

The clue, however, is in the clunkiness of forcing everything to be transient just to avoid accidents.

When you have to disable features of a subclass, or worse use a subclass to disable features of its superclass, then you’ve used inheritance incorrectly.

Here’s the thing, though. The composition version of this feels uglier. Suddenly there’s a child object to manage, and it feels like it’s more work.

It’s much cleaner altogether though, and composition is usually preferable to this sort of smashing together.

Summary

If something nearly IS a thing, it’s not good enough to force it to PRETEND to be a thing and try not to get found out!

Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out /  Change )

Google photo

You are commenting using your Google account. Log Out /  Change )

Twitter picture

You are commenting using your Twitter account. Log Out /  Change )

Facebook photo

You are commenting using your Facebook account. Log Out /  Change )

Connecting to %s