Home > Articles > Home & Office Computing > Mac OS X

  • Print
  • + Share This
From the author of Higher Order Messaging

Higher Order Messaging

Higher order messaging is a pattern that was invented relatively recently. I've written a much longer article describing the details of how to implement it, so I'll just give an overview of the kind of thing you can use if for here.

Higher order messaging is based on the idea of higher-order functions in functional programming languages. In a functional language, you have functions like map and fold that take other functions as arguments. Higher order messages take messages as arguments.

One of the simplest higher order messages is -ifResponds. This is useful in delegates, where you'd use it like this:

[[delegate ifResponds] delegateMessage];

The -ifResponds method is added to a category on NSObject and returns a proxy. This proxy implements -forwardingTargetForSelector: by first calling -respondsToSelector: on the original receiver, and then returning it if this method returns YES. The end result is that -delegateMessage is sent to receiver only if receiver implements this method.

You can use the same pattern for a number of other things; for example, enumerating over collections by providing a proxy that handles the enumeration. We also use it in the EtoileFoundation framework to run methods in a new thread. You could probably combine it with Grand Central to add an invocation to a queue.

Because they create proxies and use forwarding, higher order messages have a lot more overhead than normal messages. They are generally only a good idea in code that is not performance-critical, or in places where the method body is so expensive the extra cost of the proxy is not significant.

  • + Share This
  • 🔖 Save To Your Account