1

I have to find and solve a problem containing a circular dependency where I either store opaque pointers between the objects involved or use a separate class on a higher level to realize the relationship between the objects.

So I figured a simple problem where I have two classes, bank and account should do. The bank contains a list with accounts and the account contains a pointer to its bank. Circular dependency achieved.

But there is another condition which I have to satisfy which is that I have to make sure that the classes and the relationship between them can be tested independent of eachother.

The Bank class uses functions which do stuff on accounts, for example transfer funds between them, withdraw or add funds. And the account contains similar functions which edits its variables.

Testing the account class is easy as instantiating the class and test the functions but how can I test a class which depends on another class independent from the dependency? And how do you test a relationship between two classes?

I'm having trouble finding information on circular dependencies other than that you should avoid them but in larger projects they can be hard to avoid.

PSilo
  • 39
  • 1
  • 6

2 Answers2

0

The important question is why should the Account need to know which Bank owns it? It's hard to think where an operation on an Account that requires that information wouldn't be better done as an operation involving the bank. For instance transferring money from one account to another would generally involve Bank A removing money from Account AA, handing it to Bank B which then adds to to account BB.

Maybe you need to remove the dependency and then find out what is 'impossible' without it, and reconsider what you are trying to do, and perhaps recast it in terms of bank doing something with account rather than account doing something to bank.

Tom Tanner
  • 9,244
  • 3
  • 33
  • 61
0

Consider writing a stripped down version of account

e.g.

class Account
{
   public:
      bool failDebit;
      bool Debit(unsigned int quid) { return failDebit;}
}

Then you can test your Bank class by setting failDebit first for both cases. Then you can make it more complex if your have a more complex function in Bank that uses more that one Account and test the Bank class for all eventualities by using a similar approach. The Account class can be very simple and just mimic the return values.

NB This is a little simplictic as then may be dependencies between various function calls that may need to be taken into account (no pun intended).

Ed Heal
  • 59,252
  • 17
  • 87
  • 127