I’m having some trouble deciding how two classes should interact and the problem I’m having seems like it would come up a lot so I was wondering if anyone knows of a design pattern (or any kind of solution) that addresses my issue.
Basically I have two classes. Class A deals with displaying information to the user and Class B deals with storing data. Class A needs to get data from class B, format the data based on Class A’s internal state, and output the data. For example Class B contains English strings and Class A will always translate those strings into a language that is specified by an instance variable of Class A before preforming any further processing on them.
I can come up with two potential solutions for this but neither of them seem very clean.
-
Make Class B an instance variable of Class A. Write function in Class A that get the data out of Class B and format it for use in other functions in Class A.
This solution doesn’t seem great because it does not stop Class A from directly accessing the data in Class B without formatting it. -
Make a Class C that extends Class B. Make Class C an instance variable of Class A. Class C will override the Getters of Class B so that the formatting is always applied to the data. However in order to format the data Class C needs to know about Class A’s internal state. This could be accomplished by passing a pointer to Class A into the constructor of Class C. Class C could then call a function in Class A that calculated Class A’s internal state.
Let me know if this is confusing and I could provide a more concrete example.
thanks
In alternative #1, I don’t think “stopping Class A from directly accessing the data in Class B without formatting it” is a concern. Any class can fail to do what it says it does, it doesn’t take a bad design to do that. So I don’t think that’s a valid concern. A is the only thing that knows its internal state, so it should be providing the logic to transform the output.
One alternative to that, which may be overengineered for your needs, is to use something like the Strategy pattern. Basically, B accepts a strategy to format data, and in that function (that A would provide) you could rely on A’s state.
Something like this:
The strategy could be an instance variable of A. This keeps B completely decoupled from A, only coupled to the FormattingStrategy interface.