Service-oriented AppDelegate

AppDelegate is typically a huge class. It knows too much about your application and it progressively becomes a mess. Here, I will show you how to decouple it from its sub-functionalities by creating a clean plugin-based architecture.

We are facing the problem in an incorrect way. Think about how you are managing your AppDelegate. I bet you that it’s huge, or at least you are using some workaround but you are not proud about how you are coding it.

The problem with AppDelegate is that it knows too much about your app. It knows your dependencies, how to initialize them, how to parse your push notifications, and many more things.

TL;DR

You can create ApplicationServices, those are objects that shares the AppDelegate life cycle and performs actions on its steps. Your AppDelegate then becomes observable and your services are its observers. This approach allows you to decouple AppDelegate from its services and create Single-responsibility objects.

You only have to create services and register them on AppDelegate. The result is the smallest and cleanest AppDelegate you have ever seen.

Typical AppDelegate

Typically, AppDelegate has a lot of responsibilities.

Initialize EVERY dependency of your application.

Setup global UIAppearance values.

Handle push notifications.

Register to push notifications.

And many more.

The problem here is that your AppDelegate knows exactly how every Component works and how to instantiate them. It also knows how your app should look like. And it knows the format of your push notifications. In result, it grows A LOT more than you may expect.

A different approach

Imagine that you have your dependencies encapsulated in their own components, called ApplicationService.

Every ApplicationService is a sub-AppDelegate. It shares its life cycle and performs actions in the events it requires.

Your AppDelegate becomes an observable source of events, as it only notifies its services that something happened.

Services-oriented AppDelegate

Application Services

Application Services are objects that share the AppDelegate life cycle. ApplicationService is just a tagging protocol. If you are using PluggableApplicationDelegate, It looks like this:

public protocol ApplicationService: UIApplicationDelegate {}

As you can see, it’s only UIApplicationDelegate, but with a more expressive name.

When you implement it, it’s like implementing an AppDelegate, but the key difference here is that you are coding a single responsibility component.

Here is an example implementation:

The new AppDelegate

Now, your AppDelegate becomes a lot smaller, as it only has to inherit from PluggableApplicationDelegate and register its services.