4

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.

The Law
  • 344
  • 3
  • 20
  • I don't understand the problem here? Why not just pass in the object a to the constructor of object b? It can interrogate it through normal means to determine the state without breaking encapsulation. If you're worried about exposing too much, maybe try using package-private getters or isolate the interfaces to their own modules? You're asking good questions, but thinking too hard. ;-) – jgitter Oct 13 '15 at 14:26

2 Answers2

2

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.

Community
  • 1
  • 1
Suresh Atta
  • 120,458
  • 37
  • 198
  • 307
1

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.

m c
  • 1,104
  • 1
  • 12
  • 21