Input class - appropriate use of friend?
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 pr开发者_开发问答ivate 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?
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.
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.
精彩评论