Skip to content

Instantly share code, notes, and snippets.

@claybridges
Created March 24, 2020 20:28
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save claybridges/6c3abcaf361fb515c86c31b9640e97bf to your computer and use it in GitHub Desktop.
Save claybridges/6c3abcaf361fb515c86c31b9640e97bf to your computer and use it in GitHub Desktop.

Notification observations and handlers

For a class, each notification observation should be handled by a single method. The name of that method should be handle appended with the name of the notification being observed. For instance, for notification name

NSNotification.Name.LUUICachedPaymentMethodDidUpdate

the handler would be

private func handleCachedPaymentMethodDidUpdate(...)

Skip whatever LU/LUUI prefixes exist.

Only the notification observation should call/reference the handler method.

Here's how the resultant code would look:

  // somewhere
  NotificationCenter.default.addObserver(self, selector: #selector(handleCachedPaymentMethodDidUpdate),
                                         name: NSNotification.Name.LUUICachedPaymentMethodDidUpdate,
                                         object: nil)

  // later
  private func handleCachedPaymentMethodDidUpdate(_ notification: NSNotification) {
     // 🧹 handle it! 
  }

All notification handler methods should be private, and should be grouped together in a section delineated by

// MARK: - Notification handlers

Motivation

When trying to comprehend code, especially when debugging, it can become confusing to have a method that is called by:

  • multiple notifications
  • both by a notification and direct calls

Breaking out notification handlers on their own is a simple, consistent way to structure this for clarity.

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment