Skip to content

Instantly share code, notes, and snippets.

@albertbori
Last active April 22, 2024 19:30
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 albertbori/0c21bf5af8c450a058657978a524028b to your computer and use it in GitHub Desktop.
Save albertbori/0c21bf5af8c450a058657978a524028b to your computer and use it in GitHub Desktop.
Composed Protocol Dependency Injection Documentation

Composed Protocol Dependency Injection (CPDI) Pattern

This dependency injection pattern uses native Swift language features to provide a safe, concise, deterministic, and intentional approach to dependency injection.

Overview

The primary Swift language feature that drives CPDI is called "protocol composition". This feature allows you to create a type alias from any combination of protocols. For example:

protocol Car {
    func drive()
}

protocol Airplane {
    func fly()
}

typealias Carplane = Car & Airplane

func start(vehicle: Carplane) {
    vehicle.drive()
    vehicle.fly()
}

The above example shows how you can combine two protocols into a single type alias and then use that to describe a tangible requirement. Additionally, that type alias can be used as a requirement for another type alias, and so on. For example:

protocol Motorcycle {
    func wheelie()
}

typealias Carplanecycle = Carplane & Motorcycle

func start(vehicle: Carplanecycle) {
    vehicle.drive()
    vehicle.wheelie()
    vehicle.fly()
}

The above example uses the Carplane type alias from the previous example and combines it effortlessly with the Motorcycle protocol.

Using this approach, we can provide every dependency to every part of a modularized app using a single parameter.

If we create protocols that describe something we depend on, we can compose those protocols together into a type alias in each file to describe that file's dependencies. For example:

protocol LoggingDependency {
    var logger: Logging { get }
}

protocol TrackingDependency {
    var tracker: Tracking { get }
}

If the above dependency protocols are defined somewhere accessible to our file's code, we can use those dependency protocols like so:

typealias ThunkDependencies = LoggingDependency
                            & TrackingDependency

func thunk(dependencies: ThunkDependencies) {
    dependencies.logger.logDebug("Thunk was called!")
    dependencies.tracker.trackEvent(Events.thunk)
}

Note: We recommend that you namespace your dependencies as shown above to avoid property and function name collisions in your dependencies. Instead of dependencies.trackAddToCart(), it should be dependencies.tracker.trackAddToCart().

Note: One of the major benefits of CPDI is that it cannot crash at runtime because all dependencies are satisfied explicitly and cannot be accessed outside of their intended runtime scopes. This inherent safety puts the burden of proof on the engineer (in the form of type safety) instead of putting the burden of proof on the end-user (in the form of crashes). It is for this and several other reasons that CPDI is preferred over the many other dependency injection approaches and libraries.

Basic Feature

In this simple example, we have a SwiftUI view that needs do to some tracking. We'll use CPDI to fulfill its requirements.

struct ProductDetailView: View {
    var body: some View {
        VStack {
            Text("Product Detail Page")
            Button("Add to cart") {
                // TODO: Track add to cart event
            }
        }
    }
}

To apply the CPDI pattern to ProductDetailView, we add a Dependencies type to the top of the same file where the dependencies are being used. We are also careful to name the dependencies type using the exact name of the type whose requirements it satisfies: ProductDetailViewDependencies. This location and naming of the dependencies type alias are critical for discoverability and maintainability. Following this pattern will help prevent any downstream confusion about the scope of a given type alias.

typealias ProductDetailViewDependencies = TrackingDependency

struct ProductDetailView<Dependencies: ProductDetailViewDependencies>: View {
    let dependencies: Dependencies
    var body: some View {
        VStack {
            Text("Product Detail Page")
            Button("Add to cart") {
                dependencies.tracker.trackAddToCart()
            }
        }
    }
}

Note: We also use a generic alias instead of using the ProductDetailViewDependencies type alias directly within the class. We do this because it lets us add generic dependencies (later on) without any additional code changes.

"Dependencies" Parameter Order

For readability, consistency, and convention, the dependencies parameter should always appear first in any parameter list. For example:

// BAD
ProductDetailView(sku: "ABC", disposition: ..., context: ..., dependencies: ...)

// GOOD
ProductDetailView(dependencies: ..., sku: "ABC", disposition: ..., context: ...)

Sub-Dependencies

Dependencies type aliases should never be reused or shared with other types, except when forwarding them as sub-dependencies. Forwarding a Dependencies type alias should only happen in the following sub-dependencies situations:

  • Direct Child Dependencies
  • Superclass Dependencies
  • Helper or Static Function Dependencies

Direct Child Dependencies

If your code file instantiates a struct or class that has its own Dependencies type alias, you must forward that child's Dependencies type alias along with your file's Dependencies type alias.

Consider a SwiftUI view named ProductDetailView that includes a sub-view called ProductImageView. Each view requires specific dependencies:

  • ProductImageView depends on various services and utilities specific to its functionality, grouped under a type alias ProductImageViewDependencies.
  • ProductDetailView requires its own set of services, such as TrackingDependency, for tracking user interactions, grouped under a type alias ProductDetailViewDependencies.

To accommodate all requirements, ProductDetailViewDependencies must integrate ProductImageViewDependencies into its own dependency structure. For example:

typealias ProductDetailViewDependencies = TrackingDependency
                                        & ProductImageViewDependencies // Required by ProductImageView

struct ProductDetailView<Dependencies: ProductDetailViewDependencies>: View {
    let dependencies: Dependencies
    var body: some View {
        VStack {
            Text("Product Detail Page")
            ProductImageView(dependencies: dependencies) // Borrows ProductDetailViewDependencies
            Button("Add to cart") {
                dependencies.tracker.trackAddToCart()
            }
        }
    }
}

This principle applies in all code files that work with injected dependencies, not just for SwiftUI views.

Superclass Dependencies

Similar to child dependencies, if you inherit a class that has its own dependencies requirement, you must forward that superclass' Dependencies type alias along with your file's Dependencies type alias. In the following example, a UIKit view controller depends on a base view controller, which has its own dependencies requirement.

typealias ProductDetailViewControllerDependencies = TrackingDependency
                                                  & ShopBaseViewControllerDependencies // Required by ShopBaseViewController

struct ProductDetailViewController<Dependencies: ProductDetailViewControllerDependencies>: ShopBaseViewController {
    let dependencies: Dependencies
    init(dependencies: Dependencies) {
        self.dependencies = dependencies
        super.init(dependencies: dependencies) // Borrows ProductDetailViewControllerDependencies
    }
}

Scoping Dependencies

If you you have a dependency that should only be accessible within a certain struct/class, file, or module, or if you need a dependency to be instantiated and destroyed along with a certain component, view, or other memory scope, you will have to use a technique called "Dependencies Splicing".

In this approach, we use a concrete struct or class to splice the narrowly scoped dependencies into the broader-scoped dependencies in a way that maintains the desired memory scope and accessibility.

Continuing with our previous example, if we want to add a ProductDataRepositoryDependency to the ProductDetailView and that dependency is only internally available (within the same module), and you want that repository to be instantiated and destroyed along with the ProductDetailView, then we would add that dependency to the ProductDetailViewDependencies, as you would expect.

typealias ProductDetailViewDependencies = TrackingDependency
                                        & ProductDataRepositoryDependency

Then, we create a second dependencies type alias that splits out all of the broader-scope dependencies. This will be used to help construct the spliced dependencies concrete type.

typealias ProductDetailViewExternalDependencies = TrackingDependency

Now, we create the SplicedProductDetailViewDependencies type that allows us to create and inject the ProductDataRepository into a single Dependencies type, like so:

struct SplicedProductDetailViewDependencies<ExternalDependencies: ProductDetailViewExternalDependencies>: ProductDetailViewDependencies {
    private let externalDependencies: ExternalDependencies // Obtained from outside callers
    let productDataRepository: ProductDataRepository // Created locally
    var tracking: Tracking { // Forwarded to children
        externalDependencies.tracking
    }

    init(externalDependencies: ExternalDependencies, productDataRepository: ProductDataRepository) {
        self.externalDependencies = externalDependencies
        self.productDataRepository = productDataRepository
    }
}

Note: The spliced dependencies type encapsulates the external dependencies. Avoid accessing the external dependencies property directly outside of this type.

The spliced dependencies type above combines the broad and narrow scope dependencies. This can be a struct or a class, as needed. SplicedProductDetailViewDependencies will now act as the underlying dependencies type for ProductDetailView. We accomplish this by changing ProductDetailView's generic dependency declaration like so:

struct ProductDetailView<ExternalDependencies: ProductDetailViewExternalDependencies>: View {
    let dependencies: SplicedProductDetailViewDependencies<ExternalDependencies>
    var body: some View {
        VStack {
            Text(dependencies.productDataRepository.productName)
            Button("Add to cart") {
                dependencies.tracking.trackAddToCart()
            }
        }
    }
}

How and where the SplicedProductDetailViewDependencies type is initialized depends on several factors, but for SwiftUI, it usually must be done by whoever is instantiating the SwiftUI view in question. The previous example may be declared like so:

ProductDetailView(
    dependencies: SplicedProductDetailViewDependencies(
        externalDependencies: ..., 
        productDataRepository: ProductDataRepository(dependencies: ...)
    )
)

Where the caller's Dependencies type alias conforms to our external ProductDetailViewExternalDependencies type alias that we just created.

When to Splice

Since "dependency splicing" brings some cognitive overhead and boilerplate, it's important to consider if you need to splice at all. In certain cases, it may make sense to pass the dependency as a separate parameter to your various call sites.

The main things to take into account when deciding on "dependency splicing" are:

  1. The accessibility of the dependency (public, internal, file-private / private)
  2. The memory-scope of the dependency (When should the dependency be created/destroyed from memory?)
  3. The number of components / sub-components that share the dependency
  4. The contiguous (or non-contiguous) nature of the components that share the dependency
  5. The number of dependencies that share the same scope

1 - Splicing for Accessibility

If you have a dependency that is rightfully internal or file-private / private, do not make it public to avoid splicing. Exposing internal dependencies that are not intended for external use is a shortcut that can propagate confusion and compiler complexity, and potentially introduce security considerations. Instead, evaluate the other factors above to determine if you need to use a "SplicedFooDependencies" type to encapsulate your internal or file-private / private dependency from your external APIs, or if you can just pass the dependency directly (internally) across component initializers or functions as a separate parameter.

2 - Splicing for Memory Scope

You should not instantiate a dependency at a higher memory scope than is required. Your dependency should be instantiated with the exact memory-scope and life-span/life-cycle that is required for the use case. This may require that you splice that dependency into the type whose memory scope it shares. Consider the other factors above to determine if you need to use a "SplicedFooDependencies" type to ensure that your dependency is memory-scoped correctly to your feature, view, or component, or if you can just pass the dependency directly across component initializers or functions as a separate parameter.

A helpful question is this: "Should this dependency only exist in memory for as long as the component that requires it? If not, what component should it be scoped with?" The answer to this question will help you know if you need to splice, and where you would splice the dependency.

3 - Splicing for Scope of Use

If your dependency is only used once, by one file, do not splice the dependency. Instead, pass it directly to the type via a separate initializer or function parameter. However, if your dependency has many, many uses, even within the same file, a splice may be preferred over the boilerplate of passing an additional dependency around a dozen or so call-sites. Considering the other factors above may reinforce or dispel the need for splicing based on number of components (or call sites) needing the dependency.

4 - Splicing for Distance Between Components

If your dependency is used by few (see above), contiguous components, it may make sense to pass that dependency directly as a separate parameter. However, if your dependency is used by 2+ components that are only distantly related, it may be considerably less work & cognitive load to splice that dependency at the closest shared ancestor, instead of passing the dependency as an extra parameter across many, many initializers and function calls. Consider the other factors above when making this decision.

5 - Splicing for Dependency Grouping

If you have several dependencies that share the same memory scope or accessibility, even if they are narrowly used, it may make sense to use "dependency splicing". Consider the above factors and weigh the amount of boilerplate required for splicing vs passing them all directly via initializer or function parameters.

Splicing Rubric

Ultimately, you must weigh the time-savings of CPDI for each dependency. CPDI favors the more broadly-used dependencies, but has quickly diminishing returns for internal/private or narrowly-used dependencies. You'll want to use CPDI splicing except in situations where passing a separate parameter from file-to-file (via initializers or function arguments) requires significantly less effort than splicing. This can also be affected by the number of internal/private or narrowly-used dependencies that share the same scope.

Using the above concepts, the following table can help you determine if you need to splice a dependency in your specific scenario. The left column represents the possible memory scopes of a given dependency. The right columns represent the accessibility of the dependency, and the values in the grid suggest whether you should splice in that scenario or pass the dependency as a separate parameter outside of CPDI.

Memory Scope ⬇️ x Publicly Available Internally Available File / Privately Available
Global (Static or Near-Static) N/A Splice N/A
Entire Feature Splice Splice N/A
Shared with Non-Adjacent Descendants Maybe Splice Maybe Splice N/A
Shared with Direct Descendants Separate Parameter Separate Parameter Separate Parameter
Single Type Separate Parameter Separate Parameter Separate Parameter

Note: Key Terms

  • Global - Static or near-static dependency that's instantiated at startup or when the module is first loaded or called.
  • Entire Feature - A widely-used dependency that is instantiated and destroyed along with the entire feature it's associated with.
  • Shared with Several Non-Adjacent Descendants - This dependency is instantiated by a distance ancestor, being passed down by potentially several initializers that may or may not be directly connected.
  • Shared with Direct Descendants - This dependency is used only by a parent type and its direct descendants or passed through very few initializers.
  • Single Type - This dependency is used only within a single piece of code or file and should be memory-scoped with that code.
  • Publicly Available - Your dependency type is marked as "public" because you want to share this type with callers outside of your module, making it part of your module's public API.
  • Internally Available - Your dependency type is marked as "internal" (or, by default is internal), and is intended for access across any file in the given module.
  • File / Privately Available - Your dependency type is marked as "private" or "fileprivate" and is not intended for access outside of the given file.

Public Encapsulation (Factory)

To prevent from having to make all of your dependencies type aliases public, you can splice your dependencies at the top-most object/struct or call site of your feature. Regardless, it's usually a good idea to create a publicly accessible wrapper around your internal functionality to create a single entry point into your feature. Here is such an example:

public typealias ProductFeatureDependencies = ProductDetailViewExternalDependencies
                                            & ProductDataRepositoryDependencies
                                            // & Other encapsulated component dependencies

First, we created a new ProductFeatureDependencies type alias in a new file where our feature's API will live. We declare this type alias as publicly accessible.

Note: You may need to declare your "External" Dependencies type aliases as public as well, as required, but no other type aliases should be made public. If you find yourself making all of your types public to fix compiler warnings, you should reevaluate how you are splicing your dependencies.

Next, we create the public API using ProductFeatureDependencies:

public struct ProductFeature<Dependencies: ProductFeatureDependencies> {
    let dependencies: Dependencies

    public init(dependencies: Dependencies) {
        self.dependencies = dependencies
    }

    public func productDetailView(for sku: String) -> some View {
        ProductDetailView(
            dependencies: SplicedProductDetailViewDependencies(
                externalDependencies: dependencies, 
                productDataRepository: ProductDataRepository(dependencies: dependencies, sku: sku)
            )
        )
    }

    // Other Product feature functions
}

This provides a succinct API for accessing all of our internal code, and a simple Dependencies type alias for external callers to grok and use.

Finally, callers can invoke your feature at any time using the following code:

ProductFeature(dependencies: dependencies).productDetailView(for: "ABC")

Where the caller's Dependencies type alias conforms to our external ProductFeatureDependencies type alias that we just created.

All In One Reference

The following example shows the ideal setup for forwarding any kind of dependencies for a type called Foo.

typealias FooDependencies = FooBaseDependencies   // Superclass dependencies
                          & LoggingDependency	  // Used directly in this file
                          & BarDependencies       // Direct child's dependencies
                          & Baz_trackDependencies // Helper/function call w/ dependencies

class Foo<Dependencies: FooDependencies>: FooBase {
    let dependencies: Dependencies
    let bar: Bar
    
    init(dependencies: Dependencies) {
        self.dependencies = dependencies           // set own dependencies, if required
        self.bar = Bar(dependencies: dependencies) // pass child-dependencies
        super.init(dependencies: dependencies)     // pass superclass dependencies
        Baz.track(dependencies: dependencies)      // pass helper function dependencies
        dependencies.logger.log("foo Loaded!")     // use dependencies directly
    }
}

Forbidden Patterns (Don'ts)

The following uses of CPDI will land you into trouble. Avoid using these where possible, but if you use them, do it right.

Composing Into Protocols

You may be tempted to create a new protocol that composes other dependencies into it. Resist this urge. Always use type aliases when composing and forwarding protocols.

protocol ProductDetailViewDependencies: TrackingDependency & ProductImageViewDependencies {
    // ...
}

The consequences of using the above approach are that when you compose this protocol with other type aliases that forward the same sub-dependencies, you will get unresolvable compiler errors akin to, "duplicate conformance detected".

Helper Functions

You should avoid passing dependencies directly into functions. Instead, you should pass the dependencies via the initializer of the thing that vends the helper function. However, if you must, the following pattern should be followed when passing dependencies into helper functions.

Similar to child dependencies and superclass dependencies, if your file calls a helper function that has its own dependencies requirement, you must forward that function's Dependencies type alias along with your file's Dependencies type alias. In the following example, a SwiftUI view modifier requires a dependencies type alias that must be satisfied by the ProductDetailViewDependencies type alias. The view modifier in this example auto-expands the product view when tapped.

typealias ProductDetailViewDependencies = TrackingDependency
                                        & View_autoExpandDependencies // Required by `.autoExpand(...)`, declared in `View+AutoExpand.swift`

struct ProductDetailView<Dependencies: ProductDetailViewDependencies>: View {
    let dependencies: Dependencies
    var body: some View {
        VStack {
            Text("Product Detail Page")
            Button("Add to cart") {
                dependencies.tracker.trackAddToCart()
            }
        }
        .autoExpand(dependencies: dependencies) // Borrows ProductDetailViewDependencies
    }
}

Inherited Dependencies

When building protocols that have extended behavior, using an associatedtype for Dependencies is generally discouraged because it can lead to difficult situations where confusing, circular, or unresolvable dependency loops can occur. It is also a conceptual POP violation to mix implementation constraints into an abstract description of functionality. Instead, stick to providing convenience directly through dependencies and not through protocol conformance of self. Protocol Oriented Programming favors extensions that provide reflexive or laterally-available concrete behavior. If your protocol extension needs a dependency, rethink your pattern.

Otherwise, if you must use this pattern, adhere to the following guidelines:

If your type implements a protocol with an associated Dependencies type, you must also forward that base class or protocol file's FooDependencies type alias along with your file's dependencies type alias, like so:

typealias ProductDetailViewDependencies = TrackingDependency
                                        & ProductImageViewDependencies
                                        & ProductComponentDependencies // Required by ProductComponent

struct ProductDetailView<Dependencies: ProductDetailViewDependencies>: View, ProductComponent /* <- Implicitly uses ProductDetailViewDependencies */ {
    let dependencies: Dependencies
    var body: some View {
        VStack {
            Text("Product Detail Page")
            ProductImageView(dependencies: dependencies)
            Button("Add to cart") {
                dependencies.tracker.trackAddToCart()
            }
        }
        .onAppear {
            log("appeared!")
        }
    }
}

The above example implements and uses a protocol called ProductComponent by forwarding its ProductComponentDependencies type alias. ProductComponent is defined like so:

typealias ProductComponentDependencies = LoggingDependency

protocol ProductComponent {
    associatedtype Dependencies: ProductComponentDependencies
    let dependencies: Dependencies
}

extension ProductComponent {
    func log(message: String) {
        dependencies.logger.log(message: "ProductComponent: " + message)
    } 
}

Best Practices & Common Pitfalls

The following sections contain more information on what to CPDI patterns to avoid and how to avoid them.

"Dependencies" Reuse

🚫 Avoid: “It’s ok to reuse the dependencies type alias from another file, especially if it’s convenient.”

Bad Examples

struct ProductDetailView<Dependencies: HotDealsDependencies>: View { ... }
struct ProductDetailView<Dependencies: AllProductDependencies>: View { ... }

The problem with this approach is that the original type alias no longer describes the dependency requirements of a given file, and it’s very, very difficult to figure out which files need which dependencies and which dependencies are actually used. It also is a violation of the “least knowledge principle”, which indicates that code should not be exposed to or interact with distant or unrelated concepts.

Every file that uses a dependency should define its own “Dependencies” type alias. This includes any “Spliced” dependencies type, if required. This keeps dependencies well-scoped and easy to reason about.


Following Compiler Prompts Instead of CPDI

🚫 Avoid: “If the compiler complains that ‘FooDependencies does not conform to BarDependency’ when passing dependencies into a child component, it’s ok to just add BarDependency to my file's type alias.”

Bad Example

typealias ProductDetailViewDependencies = TrackingDependency // Used by this file
                                        & LoggingDependency 
                                        // 👆 LoggingDependency is used by ProductImageView, but not used by this file
struct ProductDetailView<Dependencies: ProductDetailViewDependencies>: View {
    let dependencies: Dependencies
    var body: some View {
        VStack {
            Text("Product Detail View")
            ProductImageView(dependencies: dependencies)
            // 👆 Gave us the compiler error: "ProductDetailViewDependencies does not conform to LoggingDependency", so our knee-jerk reaction was to add LoggingDependency to ProductDetailViewDependencies.
        }
        .onAppear { dependencies.tracker.track(Events.productDetailViewAppeared) }
    }
}

The problem with this approach is that it breaks the automatic cascading of dependencies from file-to-file and level-to-level. If you add 'BarDependency' directly to your file because on if your child requires it, then if your child later removed the BarDependency requirement, your file would still needlessly be requiring it because you added it directly to your file's requirements instead of forwarding your child's Dependencies type alias.

Each “Dependencies” type alias should only include dependencies used within that file. This includes forwarding the “Dependencies” type aliases of your direct children. This keeps dependencies well-scoped and easy to reason about.

Correct Example

typealias ProductDetailViewDependencies = TrackingDependency
                                        & ProductImageViewDependencies
                                        // 👆 Forward the child's "Dependencies" type alias, not the individual dependencies of the child

struct ProductDetailView<Dependencies: ProductDetailViewDependencies>: View {
    let dependencies: Dependencies
    var body: some View {
        VStack {
            Text("Product Detail View")
            ProductImageView(dependencies: dependencies)
        }
        .onAppear { dependencies.tracker.track(Events.productDetailViewAppeared) }
    }
}

Type Alias Naming Pattern

🚫 Avoid: “ProductContainerView is basically the top-level component for the "Product" feature, so I’ll just name its ‘Dependencies’ type alias ‘ProductDependencies’.”

Bad Example

typealias ProductDependencies = ...

struct ProductContainerView<Dependencies: ProductDependencies>: View { ... }

The problem with this approach is that when engineers attempt to use ProductContainerView, they will have a tough time finding which “Dependencies” type alias belongs to that type.

Each “Dependencies” type alias should be prefixed with the type name it represents. E.g.: “ProductDetailView” would have a dependencies type alias named “ProductDetailViewDependencies". This makes child component “Dependencies” type aliases easy to find and grok.

Correct Example

typealias ProductContainerViewDependencies = ...

struct ProductContainerView<Dependencies: ProductContainerViewDependencies>: View { ... }

Type Alias Location

🚫 Avoid: “I like to organize each type in a separate file. I’ll put my ‘Dependencies’ type alias in a file next to the file where it is used.”

Bad Example

// In ProductDetailViewDependencies.swift
typealias ProductDetailViewDependencies = ...

// In ProductDetailView.swift
struct ProductDetailView<Dependencies: ProductDetailViewDependencies>: View { ... }

While organizing types in separate files is good in many cases, doing so in this case makes it more difficult to make the mental connection between the sub-dependencies declared in the “Dependencies” type alias and the actual requirements of the file where it is used.

Each “Dependencies” type alias should be defined in the same file where the types are being used. This makes child component “Dependencies” type aliases easy to find, and makes it easier to know which dependencies are actually needed in the “Dependencies” type alias.


Convenience & Helpers

🚫 Avoid: “I’m going to extend this protocol with some conveniences, but those conveniences require some dependencies, so I’ll add a ‘Dependencies’ associated type to the protocol.”

Bad Example

typealias ContextLoggableViewDependencies = LoggingDependency

/// Provides context-logging behavior to the implementing type
protocol ContextLoggableView: View {
    associatedtype Dependencies: ContextLoggableViewDependencies
    var dependencies: Dependencies { get }
    var context: String { get }
}

extension ContextLoggableView {
    func log(_ message: String) {
        dependencies.logger.log("\(context): \(message)")
    }
}

typealias ProductDetailViewDependencies = ContextLoggableViewDependencies

struct ProductDetailView<Dependencies: ProductDetailViewDependencies>: ContextLoggableView {
    let dependencies: Dependencies
    let context: String = "com.foo.product-detail-view"

    var body: some View {
        VStack {
            Text("Product Detail View")
            ...
        }
        .onAppear { log("View loaded!") }
    }
}

Protocol-Oriented Programming has a very particular scope of usefulness. It works best when extending protocols with reflexive behavior, or behavior that uses adjacent types (not needing dependency injection).

More than this, attaching a Dependencies requirement to your protocol imposes opinionated implementation details to all implementers, which is a violation of properly scoped abstractions.

Use concrete, injected dependencies to provide convenience to your file. This creates a very clear inversion-of-control pattern that works seamlessly with CPDI.

Good Example

typealias ContextLoggerDependencies = LoggingDependencies

/// Provides context-logging behavior to any caller
struct ContextLogger<Dependencies: ContextLoggerDependencies>: ContextLogging {
    let dependencies: Dependencies
    let context: String

    func log(_ message: String) {
        dependencies.logger.log("\(context): \(message)")
    }
}

typealias ProductDetailViewDependencies = ContextLoggerDependencies

struct ProductDetailView<Dependencies: ProductDetailViewDependencies>: View {
    let dependencies: Dependencies
    var logger: ContextLogger { ContextLogger(dependencies: dependencies, context: "com.foo.product-detail-view") }

    var body: some View {
        VStack {
            Text("Product Detail View")
            ...
        }
        .onAppear { logger.log("View loaded!") }
    }
}

Another Good Example

protocol ContextProviding {
    var context: String { get }
}

extension Logging {
    func log(_ message: String, source: some ContextProviding) {
        log("\(source.context): \(message)")
    }
}

typealias ProductDetailViewDependencies = LoggingDependency

struct ProductDetailView<Dependencies: ProductDetailViewDependencies>: View, ContextProviding {
    let dependencies: Dependencies
    let context = "com.foo.product-detail-view"

    var body: some View {
        VStack {
            Text("Product Detail View")
            ...
        }
        .onAppear { logger.log("View loaded!", source: self) }
    }
}

Generic Dependencies

🚫 Avoid: “To keep things simple, I’ll just use my Dependencies type alias directly as an existential type (any) instead of a generic type (some).”

Bad Example

typealias ProductDetailViewDependencies = ...

struct ProductDetailView: View {
    let dependencies: ProductDetailViewDependencies
    ...
}

Doing this will cause explosion of upstream and downstream changes if a generic dependency is introduced in the future. With SwiftUI being based on protocols with associated types (View), generic dependencies will become very common as modularized features vend Views to each other through dependency injection.

Pass your Dependencies type alias generically (using a generic alias and constraint) This saves a lot of work later on, if a generic dependency is introduced in the future.

Good Example

typealias ProductDetailViewDependencies = ...

struct ProductDetailView<Dependencies: ProductDetailViewDependencies>: View {
    let dependencies: Dependencies
    ...
}

Spliced Dependencies Reuse

🚫 Avoid: “To keep things simple and DRY, I’ll just use this other Spliced Dependencies type to instantiate my narrow-scope dependency, even though it’s instantiated at a different scope than my feature.”

Bad Example

struct ProductDetailView<ExternalDependencies: HotDealsExternalDependencies>: View {
    let dependencies: SplicedHotDealsDependencies<ExternalDependencies>
    ...
}

Doing this can cause circular references, memory leaks, high-memory usage, high CPU usage, etc.

Splice in narrow-scoped dependencies along with their corresponding components in the same file where the dependencies are used. This keeps dependencies well-scoped and easy to reason about. It also protects against memory leaks and reduces overall memory footprint and CPU usage.

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