How do I design a subclass whose method contradicts its superclass? Let's say we have this example:
# Example 1 class Scissor def right_handed? true end end class LeftHandedScissor < Scissor def right_handed? false end end
Let's assume that the inheritance is necessary in this example e.g. that there might be other methods aside from
right_handed? that are being inherited.
So a LeftHandedScissor is a Scissor. Its method
right_handed? matches the signature and return value type of its superclass's method. However, the subclass method contradicts the return value of the superclass method.
This bothers me because it looks like a logical contradiction:
- All scissors are right-handed.
- A left-handed scissor is a scissor.
- Therefore, a left-handed scissor is right-handed.
I considered introducing an AbstractScissor to avoid this contradiction:
# Example 2 class AbstractScissor def right_handed? raise NotImplementedError end end class RightHandedScissor < AbstractScissor def right_handed? true end end class LeftHandedScissor < AbstractScissor def right_handed? false end end
My colleague says the downside to this solution is that it's more verbose. Aside from adding an extra class, it requires us to call scissors "right-handed scissors", which no one does in the real world.
This leads me to my last solution:
# Example 3 class AbstractScissor def right_handed? raise NotImplementedError end end class Scissor < AbstractScissor def right_handed? true end end class LeftHandedScissor < AbstractScissor def right_handed? false end end
It's nearly the same as example 2 but I just renamed RightHandedScissor as Scissor. There's a chance that someone might assume LeftHandedScissor is a subclass of Scissor based solely on the class names, but at least the code makes it obvious that that's not the case.
Any other ideas?