In our codebase, I encountered the following construct: There is a base class B, and then there is a class D which derives from B, but does not override or add any members. In fact, D is completely empty – except for a constructor that initializes some (inherited) properties in a special way.
Consider this contrived C# example:
public class Angle
{
public Angle(float degrees)
{
Degrees = degrees;
}
public float Degrees { get; set; }
}
public class RightAngle : Angle
{
public RightAngle() : base(90)
{
}
}
To me, this seems like a gross violation of OOP principles, but I cannot really pinpoint the issue. Is this a proper use of inheritance or a bad idea? Should I replace the derived class with -for example- a static factory?
1
While mildly distasteful, this sort of thing isn’t the worst thing in the world. It doesn’t explictly violate any OO principles.
My main complaint is that with just the code above, not all right angles are RightAngle
s, though using value semantics would solve that.
Personally, I would work to make the class immutable and then simply have a static readonly instance of Angle.RightAngle
or similar.
1
I believe the inheritance approach taken here in your question is to only guarantee that the object creation happens in a whole by appropriately setting the mandatory attributes of the class, if the proper object creation is the sole purpose then i would suggest object Builder patterns instead of going with the inheritance approach.