Don’t names classes AbstractThing or ISerializable

By Adrian Smith25 Feb 2013500 words3 mins to read

Naming a class AbstractThing violates the Liskov Substitution Principle, and causes client code to read wrong. Call a class a name which you'd be happy to call any of the objects belong to the class.

If you want to borrow your friend's phone, and you're not sure what brand it is, how many times have you asked "Excuse me mate, can I borrow your abstract phone? Cheers."

Object-oriented modeling and programming allows certain classes of objects to specialize other general classes of objects. For example, both a Rectangle and Circle are special types of of Shape.

Every Rectangle is a Shape. Everywhere you can use a Shape, you can use a Rectangle. Code that deals with a Rectangle (but which can also deal with Circles) might look like:

Shape s = .....;

Using an object (e.g. a Rectangle) anywhere you can use a generalization of it (e.g. a Shape) is an important part of the object-oriented concept, and known as the Liskov Substitution Principle.

It's also obvious: what sort of sentence or logic would make statements about shapes, but then not be applicable to rectangles?

If you name the generalization an AbstractShape, this principle is violated. A Rectangle isn't an AbstractShape. If anything it's a "Concrete Shape"! A rectangle isn't abstract (in the sense of "I don't know what type of shape this is. Could be a rectangle, could be anything else."). Code using AbstractShape then reads wrong:

AbstractShape s = new Rectangle(...);

The same is true of interfaces. What do all objects which are serializable have in common? They are Serializable. Naming the interface ISerializable would lead to code like:

ISerializable s = new String("hello")

But s refers to a particular instance; a particular thing. There's nothing abstract or "just an interface" about s. s is a String, which is a specialization of the more general type of thing called a Serializable. The line of code, including s's type, must reflect what s actually is. It's a serializable.

Further, what if you change an interface to an abstract class, or a concrete class to an abstract class, or vice-versa? The client code must be updated. While isn't too much of a pain with refactoring tools, it still leads to the suspicion that irrelevant information about the tools used to construct the implementation are leaking out to client code.

A class of a set of objects is named to capture the common aspects of those objects. If all objects are rectangles, call their class Rectangle. Naming a superclass, abstract or not, is no different. What do all the object modeled have in common? Some are rectangles, some are circles, but they are all Shapes.

The objects being classified into classes are not AbstractShapes, BaseShapes, IShapes, or similar.

This article was written by Adrian Smith on 25 Feb 2013

Follow me: Facebook | Twitter | Email

More on: Words & Language | Software Architecture | Coding