Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to go beyond callback programming?

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?

like image 673
Geo Avatar asked Dec 13 '25 20:12

Geo


1 Answers

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);
  }
}
like image 176
Henrik Paul Avatar answered Dec 16 '25 07:12

Henrik Paul