3

Of course it depends on the situation. But when a lower level object or system communicate with an higher level system, should callbacks or events be preferred to keeping a pointer to the higher level object?

For example, if we are working on a game, we have a world class that has a member variable vector<monster> monsters. When the monster class is going to communicate with the world class, should I prefer using a callback function then or should I have a pointer to the world class inside the monster class?

x29a
  • 1,761
  • 1
  • 24
  • 43
hidayat
  • 9,493
  • 13
  • 51
  • 66
  • Is the world object a single instance? If so, you may want you use the Singleton pattern. – kenny Feb 22 '11 at 12:16
  • 3
    You probably don't want a Singleton if low coupling is a concern. Singletons allow coupling from all over the place. – stefaanv Feb 22 '11 at 12:31

1 Answers1

6

It generally is preferrable to use callbacks to communicate with higher level classes for the reasons you mention and to avoid mutual/cyclic dependencies.

In your case, you still have to define what is the lower level module. Should world really need to know what a monster is? Aren't monster just creatures or opponenents? Doesn't monster need some kind of environment to act in? Only you can answer that to come to a workable solution.

stefaanv
  • 14,072
  • 2
  • 31
  • 53
  • yes monsters are just creatures, but the question was more general if I should use pointers or callbacks, what is the best solution. – hidayat Feb 22 '11 at 12:23
  • @hidayat: that was the first (and main) part of the answer. I just wanted to point out that it is not always obvious what the higher class should be. – stefaanv Feb 22 '11 at 12:29