user974967
user974967

Reputation: 2946

container class member interaction

I'd like to get some advice on how I can improve my overall program design.

I have a main class which has two members that frequently need to interact with each other. This container-like class has an Initialize() function which initializes both of the members, and other functions which provide access to the outside world:

class Foo {
public:
    bool InitializeAandB();
    void UseFoo();

private:
    TypeA a;
    TypeB b;
};

At some point after UseFoo() is called, a will need to call one of b's public functions. So, let's say TypeA has a member function like this:

void TypeA::Function() {
    if (true) {
        TypeB *bpointer;
        bpointer->Interact(); // Need pointer to b here.
    }
}

TypeA and TypeB are separate entities and cannot be combined into a single class. It just so happens that these separate entities need to interact with each other at various times.

I don't want to make a and b public because they shouldn't be visible from the outside world. Adding TypeA and TypeB as friends in Foo seems like a hacky fix. Also not ideal because then both TypeA and TypeB need to know about Foo when they only need to know about each other. Same goes for public GetA() and GetB() accessor functions.

A third option is to add a TypeB* member to TypeA and a TypeA* member to TypeB which are set during InitializeAandB(). But this seems redundant on some level, like I'm missing a better overall design.

Is there a better way to design this?

Upvotes: 1

Views: 94

Answers (3)

Vladislav Rastrusny
Vladislav Rastrusny

Reputation: 29985

I agree with @CreativeMind. You should use DI container here.

Refactor initialization phase into separate class, fill your DI container with instances of A and B. Extract interfaces from their implementation and place it as a contract somewhere. Now they are services and can ask container for each other.

Foo can now use A and B the same way - via container.

Upvotes: 0

CreativeMind
CreativeMind

Reputation: 917

Dependency injection is the only option I can think of.

Upvotes: 1

Arun
Arun

Reputation: 20383

How about passing TypeB * as an argument to TypeA::Function() (and vice versa)?

Upvotes: 1

Related Questions