Consider the following UML diagram:
In a nutshell:
ChildClass1
andChildClass2
use all of the members ofParentClass
.ChildClass3
only usesMember1
andMember2
and the value ofMember5
is a constant value. (0)
What would be the best way to implement this behaviour?
At the moment, I've inherited the class as normal and overridden Member3
and Member4
to throw NotSupportedException
and made Member5
read-only and return 0
all the time.
I'm not convinced this is the best idea as Member3
and Member4
are irrelevant to ChildClass3
.
Other things I've considered:
Instead of inheriting. Creating a
ParentClass
insideChildClass3
and then exposing only the properties I need.Using interfaces, but this got too messy, too quickly.
Restructuring the hierarchy, but I didn't really look at this in too much detail.
Is there any other options?
For context: I tried to keep this simple to avoid walls of code, but this appears to have lead to confusion. Oops =/
ParentClass in this case is Person, with the following fields:
- Forename : string
- Surname : string
- Gender: string
- DateOfBirth : Nullable<DateTime>
- Location: int
Now in most cases, the child classes (Employee, Manager, etc.) use all of these fields. However one class (Visitor), I only need to know a name, I don't care about their age or location. Location in this case is set to 0. I know it's a magic number, but it's important to the system.
I can understand how this violates LSP, but at the same time, I don't really think having interfaces to split a name and other personal information makes a lot of sense. Naming this would give me a headache too.
In the other classes, there's interfaces everywhere; IMedicalData, IContactInformation, etc.
I only chose inheritance in this case since a visitor is technically a type of person.