tags:

views:

63

answers:

2

After seeing one of my classes grow far too large, I decided to separate out its input handling into another class. However, in order for the input to actually do anything to the object, it needs access to its private members.

I could obviously provide public functions in the main class that input class could use, but since coupling is natural here anyway, would it be appropriate to just make it a friend? Or am I missing some pattern that would fit right in here?

A: 

It sounds to me like making the classes friends defeats the purpose of splitting up the one class that is "too large." If you do that then you'll be dividing the class up into two, but they'll still be tightly coupled and just as inseparable as before.

One approach would be to write public methods that describe what you want to do in response to input. For example, if your class represents a cursor that can move in four directions based on arrow key input, you'd write methods like "MoveUp" and "MoveLeft", and then call those methods outside of the class in response to input events. In that case, it wouldn't be necessary to access the class's private cursor data.

Parappa
+1  A: 

There's no definitive answer to your question; it's really a matter of taste, to be honest. It sounds like using the friend keyword is fine here, if these two classes are logically coupled, especially if no other class will ever need access to the private member variables you're referring to. Another option would be to make the input handling class a nested class inside the main class. It will then automatically have access to the private member variables, and more strongly emphasize the logical coupling of the two classes.

But this is a subjective judgment call; whatever approach you think makes your code more readable, more accessible, and easier to maintain is the right answer.

Charles Salvia
In C++ nested classes don't have access to private members of the nesting class. It needs to be friend and have a parent pointer. In Java, it is automatic.
stefaanv
The C++03 standard doesn't automatically give nested classes access to private members of the enclosing class, but this is considered a defect. See http://www.open-std.org/JTC1/SC22/WG21/docs/cwg_defects.html#45. Most mainstream compilers allow it, and it will be allowed in the C++0x standard. Thus, for all intents and purposes, the friend keyword is not necessary
Charles Salvia
Okay, I tried it in gcc and it works. I stand corrected. It saves a "friend" declaration which is fine by me. Thanks for sharing this.
stefaanv