In a game i’m programming, I use a composite object for all entities within the game. The entities are made up of component objects which define small chunks of functionality such as health, or movement.
My question is:
Is it ok to post a notification from a component, but reference its parent entity as the object sending the notification instead?
I’m tempted to do this, as it is easier to add observers to the entity, instead of finding the correct component inside the entity.
I’ve been told that you should never post a notification for another object.
What are the pros and cons?
Usually you think of a notification as coming “from” an object. Therefore, if you’re debugging and you want to find the source of the notification, you look for the code in that object itself.
It’s not illegal to violate that expectation, but it may make someone curse you a little bit when they have to work harder to find the real source of the notification.
Also, if you have a lot of separate components that all post the notification, it can get more difficult to refactor the code if you ever want to change the notification (for instance, the userInfo in it).
If you can guarantee that your component always has a valid pointer to its parent, the best solution is to make the component ask its parent to post the notification: