Q1. Why are callback functions used?
Q2. Are callbacks evil? Fun for those who know, for others a nightmare.
Q3. Any alternative to
Q1. Callbacks are needed if you use a layered approach in which higher levels call lowers and get feedback from lowers via callback.
Q2. When taken some precautions they're not worse than e.g. exceptions. In some ways, they're similar.
Q3. More coupling: lower lovels know higher.
Remarks:
- simple way (1 callback handler per callback): Register CallbackHandler objects via interfaces
- Use signals (QT, boost,...), and make sure that unique signals are used per callback to enhance traceability
Edit: example:
User calls ProtocolHandler to send a message and ProtocolHandler calls the user to send the reply: mutual dependency.
Layered: user is higher level, ProtocolHandler is lower level. On startup, it registers a callback for the reply and calls the ProtocolHandler to send a message. The ProtocolHandler uses the callback to send the reply: Only user is dependent of ProtocolHandler.