What is more suitable: polymorphism or hard binding?

52 views Asked by At

I am designing a business logic architecture, but I am hesitating between two options. Which is the most suitable / recommendable?

The first case gives flexibility, but according to this logic, the objects are in an arbitrary number, and some kind of objects could be completely absent:

enter image description here

In the second case, I can indicate the mandatory objects and the optional ones, but I think it looks terrible:

enter image description here

Is one of the two approaches better than the other one? If not, what would be the criteria to chose one rather than the other?

1

There are 1 answers

2
Christophe On BEST ANSWER

There is no right nor wrong model. The question is what you need and want to express.

First approach

Preliminary remark: The dashed arrows in the first diagram should have a hollow triangle as arrow head, which means "realise" (i.e. "implements"). Otherwise, it would just means that the classes also somehow depend on the interface.

enter image description here

This first diagram promotes decoupling. The design is in the spirit of the Open-Closed principle. It also increases componentization, as you could interchange any of the current class with equivalent classes without having to change ClassHolder. It's also an excellent solution if you have a variable number of items, whose real type are not known in advance.

Second approach

The second diagram makes hardwirings. This is perfectly fine if the associated classes have different roles known in advance and are moreover expected to offer different interfaces for different purposes. This in in fact a very common situation (imagine ClassHolder being a department, a1 manager, a2 financial controller, c employee, b office address):

enter image description here

It is not necessarily needed to have an intermediary interface either.

If it appears all these related classes are expected to implement the same interface but correspond to specific roles, you could imagine a third variant, associating the same interface several time to the same ClassHolder:
enter image description here