5

I have something like this

Class App
    Module A
    Module B
    Module C
    Module D

Each of the modules have a single responsibility and are pretty well encapsulated (public interface, private implementation).

The problem is, these modules need to reference each other a lot. (No reasonable way around this, I think.) This has led to a lot of cumbersome parameter passing.

Module A
    method(B& b)
    method(int i, C& c)
    method(bool b, D& d, B& b, C& c)

What if I just put something like App& app inside A? (And then initialize app appropriately.) This way I can just do this:

Module A
public:
    method()
    method(int i)
    method(bool b)

private:
    App& app

Looks more readable, seems logical enough. Yes, it is less predictable which modules modify which, but it seems justified. Or am I just being lazy? What is the correct way to approach this kind of problem?

1 Answer 1

5

Having a reference to the whole App is a sign of poor design (it's like having a global context who totally breaks encapsulation).

Foster dependency injection and especially constructor injection if you need to use a dependency in more than 1 method.

Possible implementation of Module A:

Module A
public:
    Module A(B& b, C& c) //ctor
    method()
    method(int i)
    method(bool b, D& d) //d could also be injected in the constructor

private:
    B& b
    C& c

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge that you have read and understand our privacy policy and code of conduct.

Not the answer you're looking for? Browse other questions tagged or ask your own question.