Geo
Geo

Reputation: 96887

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?

Upvotes: 2

Views: 1132

Answers (6)

Roger Nelson
Roger Nelson

Reputation: 1912

In an object oriented language I find polymorphism a much 'cleaner' (no casting and no messy function type declarations) and a more object oriented method (deriving from an interface) to achieve the functionallity provided by callbacks.

Upvotes: -1

reinierpost
reinierpost

Reputation: 8591

It's also known as event-driven programming.

Upvotes: 4

Rake36
Rake36

Reputation: 1022

It depends. For Javascript, I prefer the observer pattern for anything that can actually be aware of a fired event - mainly because you can register and manage multiple observers. But for something like an AJAX call, wrapping it in a closure and including the callback method seems like the cleanest approach.

Upvotes: 1

Javier
Javier

Reputation: 62623

it's not bad, it's just the only way to do functional programming in non-functional languages.

Upvotes: 3

Henrik Paul
Henrik Paul

Reputation: 67733

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);
  }
}

Upvotes: 7

Joel Coehoorn
Joel Coehoorn

Reputation: 416011

Another option that works especially well when you have a number of procedures with callbacks going at once is to use WaitHandles.

Upvotes: 3

Related Questions