I've noticed that a big part of my code is built around callbacks. Is this considered a "design flaw"? Are there better design patterns that I should follow?
I guess you could see the observer pattern as something that could be used akin to callbacks. Have you checked them out?
In the book Pragmatic Programmer, they mention the example of a person waiting to be boarded on a flight. Instead of that person asking the check-in desk constantly whether it's okay for her to go on board (polling), the check-in desk announces publicly to all those interested when the flight is ready.
A pseudocode for this example might look something like this:
class Clerk implements CheckInNotifyer {
BunchOfObservers observers = new Bunch();
public void addObserver(CheckInObserver observer) {
observers.add(observer);
}
private void notifyListeners() {
observers.all.notifyCheckIn(new CheckInEvent());
}
}
class Passenger implements CheckInObserver {
public void notifyCheckIn(CheckInEvent event) {
event.getPlane().board();
}
}
class WaitingArea {
public init() {
Passenger passenger = new Passenger();
Clerk clerk = new Clerk();
clerk.addObserver(passenger);
}
}
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With