The Law
The Law

Reputation: 334

Too high coupling or okay to design like this?

Let's say I have a classA, that has its own methods with its own private fields and what have you(bascically adhere to encapsulation standards). Then I have classB, that needs for its execution the final state(that is obtained through one of the methods of classA, which somewhat breaks the encapsulation) of the classA. And then we have classC, that again needs final state of classB. And so on and so on, to let's say to classM. Is that considered too high coupling or not?

Edit: Ok, let's say I was designing Loot system, that depends whether the drop happens based on enemy defeated(each enemy has different drop chance). If the enemy is defeated, the class handling battle stuff would roll a dice, whether it drops something or not, and then I need to propagate that state to the other class handling the loot distribution. If there is drop, class handling loot executes loot generation and distribution to player, if not, void.

The final execution would be something like:

classA a = new classA;
...  //classA does its stuff
classB b = new classB(a.getFinalState());
... // again class does its stuff based on outcome of A
classC c = new classC(b.getFinalState());

And so on.

Upvotes: 4

Views: 189

Answers (2)

m c
m c

Reputation: 1104

Edit: you may achieve what you want by following a Delegation Pattern and its close sibling Decorator Pattern

Builder Pattern, as already suggested, is a valid alternative. It always depends on what your original design aims to.

Upvotes: 1

Suresh Atta
Suresh Atta

Reputation: 122006

Yea. There is tight coupling with level 2. That's highly avoidable and considered as bad practise which reduces flexibility and re-usability of code. And testing is a night mare.

If they have interrelated properties consider looking at Builder Pattern.

Builder pattern is to find a solution to the telescoping constructor anti-pattern

That constructor anti-pattern is what you have so far.

Upvotes: 2

Related Questions