1

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
  • 1
    related: Is inheritance that adds rules bad? 'Maybe the point an old professor of me once made is correct: "you should only ever use inheritance to overload the constructor". At the time that seemed a bit strict but now...'
    – gnat
    Commented Oct 9, 2014 at 12:27

2 Answers 2

9

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 RightAngles, 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
  • 5
    My complaint on the presented code is that a RightAngle doesn't necessarily represent a right angle (as you can change the inherited Degrees property) Commented Oct 9, 2014 at 13:51
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.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Not the answer you're looking for? Browse other questions tagged or ask your own question.