Search code examples
inheritanceumlsubclassclass-diagramsuperclass

Can behavior of subclasses vary according to traditional modeling?


I developed a class diagram, where I'm not sure if I understood the role of superclasses.

In my diagram, user is a superclass, but I still have different roles of users that have different behavior. Is it allowed to override behavior of subclasses or is that fundamentally wrong?

Is there a better design for this case?

enter image description here


Solution

  • Yes, a subclass can redefine/override the behavior of a superclass. So Blocked user, Normal user and Moderator user could each override some behavior of User and add their own behavior on top.

    UML allows the class of an object to change during its lifecycle. But most programming languages don't. This means that even if your design is fine in theory, in practice you will not be able to implement it: when you create a Normal user, you'd not be able to transform it into a Blocked user.

    You should therefore prefer composition over inheritance: you'd have an association between User and User role and let User role be specialized into Blocked user, Normal user and Moderator user. So you keep the user, but change the role to change behavior. In fact, you could go one step further and use the State design pattern.

    enter image description here

    Unrelated hint: when you consider to redefine behavior of a subclass, it's sound practice to design according to the Liskov Substitution Principle as much as possible.