I have been developing my skills at creating large object orientated programs (30+ classes). I am trying to make my code as clean as possible after reading a fantastic book called clean code. One problem I am having is to do with calling a method on an object from "across the program"
Say I have 5 classes. `ClassA ClassB ClassC ClassD ClassE`
an instance of ClassA contains an instance of ClassB, which in turn contains an instance of classC, so
`ClassA > ClassB > ClassC`
I'm not saying that this is the inheritance chain, rather that in the constructor of classA an instance of ClassB is created and so on.
Now, say that ClassD > ClassE in a similar way. ClassD is instansiated with an instance variable containing an instance of ClassE.
This is all well and good, and the classes are small and only handle one job, and it all seems nice and clean.
However, say that at some point in the program I need the instance of classC to call a method on the instance of ClassE. The two objects are on 'opposite sides of the program' so to speak. Yet the method call is necessary.
I am left with three options as I see it
- make the instance of classE a global variable, so that classD AND classC can access it (as well as anything else in the program). I feel like this is bad form as global variables are generally considered bad news
- Create the instance of ClassE at the top level, then pass it in as an argument to the constructors of ClassA, ClassB, and ClassC. The trouble with this is that I would end up with really long constructor argument lists if this is happening more than once, and it seems like lots of work to pass ojects down chains of constructors like this
- Move the object of ClassE to be instantiated by ClassC. The trouble with that is that its more strongly coupled with ClassD and only needs to be called once in the entire running of the program by ClassC.
So what do I do in situations such as these? And are there any resources I can read about this. I know that I could use the observer pattern for situations similar to this, but when its just for one method call it seems excessive, as I would be making things observable all over the program. I want my code as clean as possible!
Thanks in advance :)