What is you experience with using callbacks in object-oriented programs? Do callbacks lead to a code that is higher quality (easier to understand, extend and maintain)? Or should callbacks be rather avoided in object-oriented code?
To illustrate the issue, consider following two ways in which a class can notify that it finished processing asynchronous task (The code is in C++ using plain function pointers as callbacks, but these are just details, the question is about object oriented practices):
Define an interface for notification and pass an object implementing this interface to an asynchronous reader:
class IReadFinishedListener { virtual void readDone() = 0; }; class ReaderA { void asyncRead(IReadFinishedListener& readFinished); };
Pass a callback to a reader:
class ReaderB { void asyncRead(void (*readFinishedCallback)(void)); };
The first solution seems more pure from the object oriented perspective. You have an explicitly defined interface, which documents what the code implementing the interface does. You can easily find classes that implement the interface, the code can be easier to follow.
Second solution is more lightweight, it does not require additional interface, which is often hard to design and name. It also seems more flexible, because it can reduce coupling between the class that handles reading and a code that is notified when reading finishes. But, the code can become harder to follow because there is no explicit interface that documents which classes can handle the notification.