Event Publisher Revision 1

I have imported my latest event publishing code into the Word Counter. Since the DomainEventType enum didn’t provide much value besides obtaining a notification name, I decided to get rid of it and obtain a name by another means.

In the current iteration (see the Gist), the event protocol reveals a static eventName. I also removed the duplicated notification factory from concrete events:

import Foundation

public typealias UserInfo = [NSObject : AnyObject]

public protocol DomainEvent {
    class var eventName: String { get }

    init(userInfo: UserInfo)
    func userInfo() -> UserInfo
}

public func notification<T: DomainEvent>(event: T) -> NSNotification {
    return NSNotification(name: T.eventName, object: nil, userInfo: event.userInfo())
}

It’s weird that I have to write notification<T: DomainEvent>(event: T) to access static properties of the event type. notification(event: DomainEvent) doesn’t work as of Swift 1.1., because “Accessing members of protocol type value ‘DomainEvent.Type’ is unimplemented”.

In a similar vein, a method like this doesn’t satisfy the generics requirement:

func foo(event: DomainEvent) {
    let notification = notification(event)
    // ...
}

But this does:

func foo<T: DomainEvent>(event: T) {
    let notification = notification(event)
    // ...
}

Mixing protocols and generics makes me wonder where the problem lies, but hey, it does work this way, although generics pose a slight performance penalty to protocols if I remember the WWDC talks correctly.

Painless Event Delivery With a Custom Publish-Subscribe Infrastructure

Teaser image

In my apps, I have used a custom event delivery mechanism on top of NSNotificationCenter with great success: I send a lot more events and consequently decouple parts of my code more easily. Putting your own objects around the Cocoa foundation can help use them more often. I want to show you how my EventPublisher works, and why custom event types make me send a lot more events than when I only had NSNotifications.

Continue reading …

Split Commands and Informational Return Values Apart Using Events

When you reason about objects in your system and their means of communication, you can differentiate between three messaging flavors according to Mathias Verraes: imperative, interrogatory, and informational messages. Before we can talk about informational messages and their value, let’s recap the other two and see what the difference is, because them calling for being extracted is not easy to spot.

Continue reading …