Posts From Category: architecture

SOLID Principles in Swift - Dependency Inversion Principle

Background

In this series of posts we are going to be covering the SOLID principles of software development. These are a set of principles / guidelines, that when followed when developing a software system, make it more likely that the system will be easier to extend and maintain over time. Let’s take a look at the problems that they seek to solve:

  • Fragility: A change may break unexpected parts, it is very difficult to detect if you don’t have a good test coverage
  • Immobility: A component is difficult to reuse in another project or in multiple places of the same project because it has too many coupled dependencies
  • Rigidity: A change requires a lot of effort because it affects several parts of the project

So what are the SOLID principles?

  • Single Responsibility Principle - A class should have only a single responsibility / have only one reason to change
  • Open-Closed Principle - Software should be open for extension but closed for modification
  • Liskov Substitution Principle - Objects in a program should be replaceable with instances of their sub types without altering the correctness of the program
  • Interface Segregation Principle - Many client-specific interfaces are better than one general-purpose interface
  • Dependency Inversion Principle - High level modules should not depend on low level modules. Both should depend on abstractions

In this article we will focus on the Dependency Inversion Principle.

What does it mean?

This principle has 2 main components described below:

High-level modules should not import anything from low-level modules. Both should depend on abstractions (e.g., interfaces) Abstractions should not depend on details. Details (concrete implementations) should depend on abstractions

I’ve interviewed many iOS developers over the years and I struggle to recall a single person who has actually got this part of the SOLID principles 100% right. I think a large part of this comes from the fact many use simple architectures such as MVVM that don’t break applications down into smaller layers and components/modules. This isn’t a criticism, not every app needs a VIPER/Clean architecture approach with multiple layers.

Most iOS developers I speak to come to the conclusion that this principle just means using protocols instead of concrete classes and injecting dependencies to help with testing/mocking. While this principle does rely on this to work it is not the primary purpose of the principle and exposes an issue once you start to depend on abstractions used across multiple layers / modules.

Setup

Lets setup a simple example in Xcode where we have two separate modules that depend on each other in order to provide some functionality.

If we create a simple Swift UI project using Xcode, then using File -> New -> Package create 2 new swift packages and add them to the project. One called LibraryA and one called LibraryB. Be sure to select your project in the ‘Add to’ drop down when naming your libraries. You should have something that looks like below Xcode.

Swift Packages Setup

Let’s start by adding a protocol and some custom data structure that we are going to be using across the 2 libraries we are working. Add a file called Protocol.swift in LibraryA and add the following code below:

import Foundation

public protocol MyProtocol {
    func doSomething(data: MyData)
}

public struct MyData {
    public let title: String
    public let subTitle: String
}

We have a simple one function protocol and a small struct, this is what we will be using to separate dependencies between our 2 libraries.

Next, lets create an implementation in LibraryA that has these protocols as a dependency. Create a file in LibraryA with the name ImplementationA:

import Foundation

public class ImplementationA {
    private let something: MyProtocol
    
    public init(something: MyProtocol) {
        self.something = something
    }
}

This is just a simple class that has the MyProtocol protocol has a dependency. Simple enough so far!

Now let’s create a class in LibraryB that implements the protocol that is being used in our class in LibraryA. Create a class in LibraryB called ImplementationB:

import Foundation
import LibraryA

public class ImplementationB: MyProtocol {
    public init() {}
    
    public func doSomething(data: LibraryA.MyData) {
        print("Do something")
    }
}

We have our class in LibraryB that is implementing the protocol we previously created in LibraryA. For this reason you will notice that we have to import LibraryA in this class as well. There is one additional step we need to do before this will compile correctly, we need to define our dependency in our package file. Let’s open the LibraryB package file and edit it to add the dependency between the 2 packages:

import PackageDescription

let package = Package(
    name: "LibraryB",
    products: [
        .library(
            name: "LibraryB",
            targets: ["LibraryB"]),
    ],
    // Assign LibraryA as dependency
    dependencies: [
        .package(path: "../LibraryA")
    ],
    targets: [
        .target(
            name: "LibraryB",
            // Add dependency to target
            dependencies: ["LibraryA"]),
        .testTarget(
            name: "LibraryBTests",
            dependencies: ["LibraryB"]),
    ]
)

We won’t go into all the options you need in the swift package file but hopefully by reading this you can see we have defined a dependency and added it to our LibraryB target. If you attempt to build the project it should compile successfully.

Now let’s look at the structure of these 2 libraries and their relationship to each other.

LibraryB to LibraryA Dependency

As you can see, we have LibraryA, this contains the protocols and LibraryB that implements the protocols. In order for LibraryB to implement the protocols it needs a dependency to LibraryA in order to work.

Problem 1

Now what happens if we want to use the protocols in another Library? Let’s call this LibraryC? At moment the protocols are contained in LibraryA where they are being used and implemented by Library B.

  • We can’t use the protocols in another library without adding LibraryA which may contain code and other assets we don’t want.
  • We could copy the protocols to LibraryC, however if you needed LibraryA and LibraryC in the same project you would get class clashes.
  • We would need to edit LibraryB to add another dependency in this case. What happens if we are not the owners of LibraryB? How would we even do this?

One solution we can try is moving the protocols from LibraryA to LibraryB. This reverses the dependencies and helps to solve the problems highlighted above. Let’s go ahead and do this now.

  • Copy the Protocols.swift file we created from LibraryA to LibraryB
  • Remove the import of LibraryA from the implementationB.swift
import Foundation

public class ImplementationB: MyProtocol {
    public init() {}
    
    public func doSomething(data: MyData) {
        print("Do something")
    }
}
  • Add an import of LibraryB to the top of implementationA.swift
import Foundation
import LibraryB

public class ImplementationA {
    private let something: MyProtocol
    
    public init(something: MyProtocol) {
        self.something = something
    }
}
  • Update the LibraryB package file to remove the LibraryA dependency
import PackageDescription

let package = Package(
    name: "LibraryB",
    products: [
        .library(
            name: "LibraryB",
            targets: ["LibraryB"]),
    ],
    // Assign LibraryA as dependency
    dependencies: [],
    targets: [
        .target(
            name: "LibraryB",
            // Add dependency to target
            dependencies: []),
        .testTarget(
            name: "LibraryBTests",
            dependencies: ["LibraryB"]),
    ]
)
  • Update the LibraryA package file to add the LibraryB dependency
import PackageDescription

let package = Package(
    name: "LibraryA",
    products: [
        // Products define the executables and libraries a package produces, and make them visible to other packages.
        .library(
            name: "LibraryA",
            targets: ["LibraryA"]),
    ],
    dependencies: [
        // Dependencies declare other packages that this package depends on.
        .package(path: "../LibraryB")
    ],
    targets: [
        // Targets are the basic building blocks of a package. A target can define a module or a test suite.
        // Targets can depend on other targets in this package, and on products in packages this package depends on.
        .target(
            name: "LibraryA",
            dependencies: ["LibraryB"]),
        .testTarget(
            name: "LibraryATests",
            dependencies: ["LibraryA"]),
    ]
)

Now let’s see a diagram of what we have done. Now if we look at our 2 libraries at a high level the dependencies look like this.

LibraryA to LibraryB Dependency

So now, our LibraryA has a dependency on LibraryB. LibraryA is using the protocols that are defined AND implemented in LibraryB! Problem solved… right… Not entirely.

If we review the problems we discussed earlier, if LibraryC wanted to make use of the protocols and implementation in LibraryB that is now possible as LibraryB has no knowledge of LibraryA or LibraryC. However this creates a new problem…

Problem 2

What if LibraryA and LibraryC want to use different implementations of the protocols from each other? What if we introduced LibraryD that wanted to implement the protocols and be used by another library such as LibraryC? In order to facilitate this we would need to create a dependency between LibraryD and LibraryB. What problems does this create?

We are introducing a dependency to a library we don’t need, in order to implement the protocols within it. In our example there isn’t much in LibraryB but imagine LibraryB had lots of other code and its own dependencies? Now we are including all of those in our project in order to have access to the protocols.

LibraryA to LibraryB Dependency Problems

Solution

This is where Dependency Inversion comes in. What we need to do is create a separate library for the protocols and any data that passes through them. Then, we make the dependencies between our different libraries to that one, thus removing the dependencies between our different layers. Let’s do that now.

  • Create a new package and add it to your project, naming it Protocols. Now move the Protocols.swift file that we created earlier into the Protocols package. Your Xcode project file explorer should look like below:

Protocols in own package

  • Now lets edit the dependencies of our packages so that both LibraryA and LibraryB depend on protocols. Your package files for LibraryA and B should now look like the below:
import PackageDescription

let package = Package(
    name: "LibraryA",
    products: [
        // Products define the executables and libraries a package produces, and make them visible to other packages.
        .library(
            name: "LibraryA",
            targets: ["LibraryA"]),
    ],
    dependencies: [
        // Dependencies declare other packages that this package depends on.
        .package(path: "../Protocols")
    ],
    targets: [
        // Targets are the basic building blocks of a package. A target can define a module or a test suite.
        // Targets can depend on other targets in this package, and on products in packages this package depends on.
        .target(
            name: "LibraryA",
            dependencies: ["Protocols"]),
        .testTarget(
            name: "LibraryATests",
            dependencies: ["LibraryA"]),
    ]
)
import PackageDescription

let package = Package(
    name: "LibraryB",
    products: [
        // Products define the executables and libraries a package produces, and make them visible to other packages.
        .library(
            name: "LibraryB",
            targets: ["LibraryB"]),
    ],
    dependencies: [
        // Dependencies declare other packages that this package depends on.
        .package(path: "../Protocols")
    ],
    targets: [
        // Targets are the basic building blocks of a package. A target can define a module or a test suite.
        // Targets can depend on other targets in this package, and on products in packages this package depends on.
        .target(
            name: "LibraryB",
            dependencies: ["Protocols"]),
        .testTarget(
            name: "LibraryBTests",
            dependencies: ["LibraryB"]),
    ]
)
  • Now update the imports of your implementation files so that they import Protocols instead. Your implementation files should look like the below:
import Foundation
import Protocols

public class ImplementationA {
    private let something: MyProtocol
    
    public init(something: MyProtocol) {
        self.something = something
    }
}
import Foundation
import Protocols

public class ImplementationB: MyProtocol {
    public init() {}
    
    public func doSomething(data: MyData) {
        print("Do something")
    }
}

Let’s have a look at what we have done here. We have moved the dependencies between the layers into a separate package and are now pointing both sides at that rather than one way or the other. Let’s update our diagram to show how this helps us.

Dependency Inversion

Now if we want to use LibraryA, B, C, or D it does not matter in our dependency graph. They all point to the protocols and data and can be used interchangeably without the need to modify the libraries, so they depend on each other. We also avoid importing any unnecessary classes that we don’t need in order to satisfy the dependencies.

This is what dependency inversion is. It’s separating protocols and data dependencies from the dependencies themselves and putting them into their own package. This way you completely separate the layers from each other, and they can be used together without any knowledge of each other. Awesome!

Read More

SOLID Principles in Swift - Interface Segragation Principle

Background

In this series of posts we are going to be covering the SOLID principles of software development. These are a set of principles / guidelines, that when followed when developing a software system, make it more likely that the system will be easier to extend and maintain over time. Let’s take a look at the problems that they seek to solve:

  • Fragility: A change may break unexpected parts, it is very difficult to detect if you don’t have a good test coverage
  • Immobility: A component is difficult to reuse in another project or in multiple places of the same project because it has too many coupled dependencies
  • Rigidity: A change requires a lot of effort because it affects several parts of the project

So what are the SOLID principles?

  • Single Responsibility Principle - A class should have only a single responsibility / have only one reason to change
  • Open-Closed Principle - Software should be open for extension but closed for modification
  • Liskov Substitution Principle - Objects in a program should be replaceable with instances of their sub types without altering the correctness of the program
  • Interface Segregation Principle - Many client-specific interfaces are better than one general-purpose interface
  • Dependency Inversion Principle - High level modules should not depend on low level modules. Both should depend on abstractions

In this article we will focus on the Interface Segregation Principle.

What does it mean?

The summary of the principle is as follows:

Many client-specific interfaces are better than one general-purpose interface

In Swift, we use Protocols rather than interfaces in languages such as Java so from here on out we will refer to interfaces as Protocols.

Now the purpose of this rule is quite straight forward in comparison to some of the other rules in the SOLID principles. What it means is its better to create smaller Protocols than to create one large one with lots of methods defined.

What’s the problem

So why does having one large protocol cause a problem? Let’s examine one of the classic Cocoa Touch protocols to see why this is an issue.

public protocol UITableViewDataSource : NSObjectProtocol {

    // 1
    func tableView(_ tableView: UITableView, numberOfRowsInSection section: Int) -> Int
    func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell

    // 2
    optional func numberOfSections(in tableView: UITableView) -> Int
    optional func tableView(_ tableView: UITableView, titleForHeaderInSection section: Int) -> String? 
    optional func tableView(_ tableView: UITableView, titleForFooterInSection section: Int) -> String?
    optional func tableView(_ tableView: UITableView, canEditRowAt indexPath: IndexPath) -> Bool
    optional func tableView(_ tableView: UITableView, canMoveRowAt indexPath: IndexPath) -> Bool
    optional func sectionIndexTitles(for tableView: UITableView) -> [String]?
    optional func tableView(_ tableView: UITableView, sectionForSectionIndexTitle title: String, at index: Int) -> Int
    optional func tableView(_ tableView: UITableView, commit editingStyle: UITableViewCell.EditingStyle, forRowAt indexPath: IndexPath)
    optional func tableView(_ tableView: UITableView, moveRowAt sourceIndexPath: IndexPath, to destinationIndexPath: IndexPath)
}

I am sure many of you have implemented this protocol at some point in your past ;) I have modified the source slightly to make it easier to read and get the point across So why are we looking at this?

  1. Only 2 methods you have to implement on the first 2.
  2. The rest of the methods are optional and you can implement whichever ones you feel you want to use.

Now this protocol has its roots in Objective C helps it masks the problem somewhat. In Objective C as you can see in the code above its possible to mark certain functions as optional. This means you can implement them if you want to but don’t have to, this allows this protocol declaration to contain too many methods without causing problems for the implementing class.

In Swift, it is not possible to mark functions as optional, all functions need to be implemented. Let’s update the above protocol to be more Swifty and see what problems that might cause us.

protocol MyUITableViewDataSource {

    func tableView(_ tableView: UITableView, numberOfRowsInSection section: Int) -> Int
    func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell

    func numberOfSections(in tableView: UITableView) -> Int
    func tableView(_ tableView: UITableView, titleForHeaderInSection section: Int) -> String? 
    func tableView(_ tableView: UITableView, titleForFooterInSection section: Int) -> String?
    func tableView(_ tableView: UITableView, canEditRowAt indexPath: IndexPath) -> Bool
    func tableView(_ tableView: UITableView, canMoveRowAt indexPath: IndexPath) -> Bool
    func sectionIndexTitles(for tableView: UITableView) -> [String]?
    func tableView(_ tableView: UITableView, sectionForSectionIndexTitle title: String, at index: Int) -> Int
    func tableView(_ tableView: UITableView, commit editingStyle: UITableViewCell.EditingStyle, forRowAt indexPath: IndexPath)
    func tableView(_ tableView: UITableView, moveRowAt sourceIndexPath: IndexPath, to destinationIndexPath: IndexPath)
}

Now that we have converted our protocol to be more swifty, what problem will this cause when we attempt to make a class conform to this protocol? Let’s have a look at an example.

class MyTableViewDatasource: MyUITableViewDataSource {
    func tableView(_ tableView: UITableView, numberOfRowsInSection section: Int) -> Int {}
    func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell {}
    func numberOfSections(in tableView: UITableView) -> Int {}
    func tableView(_ tableView: UITableView, titleForHeaderInSection section: Int) -> String? {}
    func tableView(_ tableView: UITableView, titleForFooterInSection section: Int) -> String? {}
    func tableView(_ tableView: UITableView, canEditRowAt indexPath: IndexPath) -> Bool {}
    func tableView(_ tableView: UITableView, canMoveRowAt indexPath: IndexPath) -> Bool {}
    func sectionIndexTitles(for tableView: UITableView) -> [String]? {}
    func tableView(_ tableView: UITableView, sectionForSectionIndexTitle title: String, at index: Int) -> Int {}
    func tableView(_ tableView: UITableView, commit editingStyle: UITableViewCell.EditingStyle, forRowAt indexPath: IndexPath) {}
    func tableView(_ tableView: UITableView, moveRowAt sourceIndexPath: IndexPath, to destinationIndexPath: IndexPath) {}
}

Our class above now has to implement every single protocol method. Even if we don’t intend to use it. In the objective c implementation of the protocol we have the option of implementing only the ones we need whereas now we must implement every single method. Imagine all the view controllers in the world that would be full of empty methods in order to conform to this protocol!

This protocol breaks the interface segregation principle.

A better solution

To improve the solution we could break the one big interface down into smaller protocols. That way we could conform to only the protocols we were interested in implementing for our functionality. This may looks something like:

  1. UITableViewDataSource - For the 2 compulsory methods we are familier with
  2. UITableViewSectionsDatasource - For methods relating to multi section methods
  3. UITableViewSectionTitles - For methods relating to headers and footers in sections
  4. UITableViewEditable - For methods relating to editing and moving cells

This way we could conform to select methods we want, rather than one big interface where we may only want a small subset of the methods.

A good example

A good example of interface segregation in the iOS SDK is Codable. The definition of Codable is as below:

typealias Codable = Decodable & Encodable

Basically Codable is just the combination of 2 other protocols: Decodable and Encodable. This is a great example of how to do the interface segregation. If you are building say a JSON parse struct, you may wish to only conform to Decodable so you can decode the JSON. If in the future you wanted to serialize the struct for something like say data storage you can conform to Encoding later if needed.

Summary

The interface segregation principle is the easiest of the principles to understand in my opinion. In basic terms it means don’t create a big protocol with lots of methods that aren’t always required to be implemented depending on the implementation requirements.

Instead, separate the protocol into smaller protocols with only the methods required for a single piece of functionality to work. Not only does this avoids having lots of redundant methods it also helps to facilitate the single responsibility principle by allowing functionality to be broken down into different classes. For example, you could have different classes to handle different activities rather than one big class with all functionality in.

Read More

SOLID Principles in Swift - Liskov Substitution Principle

Background

In this series of posts we are going to be covering the SOLID principles of software development. These are a set of principles / guidelines, that when followed when developing a software system, make it more likely that the system will be easier to extend and maintain over time. Let’s take a look at the problems that they seek to solve:

  • Fragility: A change may break unexpected parts, it is very difficult to detect if you don’t have a good test coverage
  • Immobility: A component is difficult to reuse in another project or in multiple places of the same project because it has too many coupled dependencies
  • Rigidity: A change requires a lot of effort because it affects several parts of the project

So what are the SOLID principles?

  • Single Responsibility Principle - A class should have only a single responsibility / have only one reason to change
  • Open-Closed Principle - Software should be open for extension but closed for modification
  • Liskov Substitution Principle - Objects in a program should be replaceable with instances of their sub types without altering the correctness of the program
  • Interface Segregation Principle - Many client-specific interfaces are better than one general-purpose interface
  • Dependency Inversion Principle - High level modules should not depend on low level modules. Both should depend on abstractions

In this article we will focus on the Liskov Substitution Principle.

What does it mean?

So the Liskov Substitution Principle states:

Derived classes must be substitutable for their base classes

What exactly does this mean? In a basic sense it for example if you have a function that accepts a type of class which is a parent of other classes, any class that subclasses the parent class should be able to be passed in without it breaking the program.

See a summary of the main points of the principle below:

  1. Contra variance of method parameter types in the sub type.
  2. Covariance of method return types in the sub type.
  3. New exceptions cannot be thrown by the methods in the sub type, except if they are sub types of exceptions thrown by the methods of the super type.
  4. Don’t implement stricter validation rules on input parameters than those implemented by the parent class.
  5. Apply at the least the same rules to all output parameters as applied by the parent class.

Let’s take a look at what these different rules mean for subclasses.

The Parent Class

First of all, let’s define our parent class or base class that contains some functionality. Let’s use a vehicle class as an example, this vehicle has a throttle which can be set at any value between 0 and 100.

// 1
enum VehicleError: Error {
    case outOfBounds
}

// 2
class Vehicle {
    private var throttle: Int = 0
    
    // 3
    func setThrottle(throttle: Int) throws {
        guard (0...100).contains(throttle) else {
            throw VehicleError.outOfBounds
        }
        self.throttle = throttle
    }
}

Let’s step through it:

  1. First of all we define a custom error to throw if the throttle is not within bounds
  2. Here we define our vehicle class that has a throttle variable to store the value being set
  3. We have a function to set the throttle value, there is a guard statement to check whether the value being set is in the appropriate range. If it is not, we throw an error, if it is we set the value

Validation rules on input parameters

Now let’s create a subclass that breaks the principle. We will make a lorry class that inherits from the super class but adds its own restrictions to the throttle function, only allowing the throttle to be set between 0 and 60 for example.

class Lorry: Vehicle {
    override func setThrottle(throttle: Int) throws {
        guard (0...60).contains(throttle) else {
            throw VehicleError.outOfBounds
        }
        
        try super.setThrottle(throttle: throttle)
    }
}

So what is happening here? We have subclassed the Vehicle class and overriden the setThrottle method. Now what we have done here is we have added a guard statement to check if the throttle is between 0 and 60. We throw an error saying out of bounds if outside of that, if it is within bounds we call the super class method.

Why is this a problem? Well imagine we are building a system / class that interacts with the Vehicle class. Now based on the Vehicle class you would expect to be able to set the throttle to anything between 0 and a 100. However now, if someone chooses to pass a Lorry subclass to your system / class, you will not be able to set the throttle above 60. Depending on how this other class or system is built this may have unintended side effects as you can’t set the values that you are expecting without getting an error.

This example breaks the rule:

Don’t implement stricter validation rules on input parameters than those implemented by the parent class.

Errors in the liskov principle

Let’s modify our example to see how we could break the principle by throwing different errors. Let’s modify the Lorry subclass:

enum LorryError: Error {
	case outOfBounds
}

class Lorry: Vehicle {
    override func setThrottle(throttle: Int) throws {
        guard (0...60).contains(throttle) else {
            throw LorryError.outOfBounds
        }
        
        try super.setThrottle(throttle: throttle)
    }
}

So what is happening here:

  • We have added a new Error type called LorryError
  • When we have our bounds exception we are throwing this new error type instead of the one provided by the super class

Why does that cause a problem? To find out let’s take a look at the error handling code:

// 1
let vehicle: Vehicle = Vehicle()

do {
	// 2
    try vehicle.setThrottle(throttle: 110)
} catch VehicleError.outOfBounds {
	// 3
    print("System shutdown")
} catch {
	// 4
    print("Show generic error")
}

Let’s step through this code:

  1. We are creating a Vehicle super class object.
  2. We are calling our function with a value considered out of bounds
  3. We catch the outOfBounds exception and print a system shutdown message
  4. We have a generic catch for other errors where we show a generic error message

Now if we run this code we see the below message in the console as expected:

System shutdown

So what happens if we replace our Lorry subclass with its new error and put it in place of the Vehicle super class? If we change line one to read:

let vehicle: Vehicle = Lorry()

If we run the code above we will now see a different error:

Show generic error

The error handling code is not aware of subclass specific errors so is no longer able to handle them accordingly. Imagine a mission critical system that needs to shut down if an out of bounds happens, in this case the error would be missed as it would require the error handling class to have knowledge of all possible sub types in order to handle all the errors appropriate. Defeating the point of using the super class and thus breaking the principle:

New exceptions cannot be thrown by the methods in the sub type, except if they are sub types of exceptions thrown by the methods of the super type.

Contra variance and Covariance of parameters and return types

In the list of rules you may recall seeing two items talking about contra variance and covariance of parameters and return types. What does that mean exactly?

  1. Contra variance of method parameter types in the sub type.
  2. Covariance of method return types in the sub type.

Contra variance of method parameter types in the sub type

Contra variance means that we can use change the type of method parameter to a super class of the type but not a subclass. This rules works basically in combination with the rule below:

Don’t implement stricter validation rules on input parameters than those implemented by the parent class.

What it means is, we can use a super class of a parameter, thus ‘weakening’ the restrictions of the method, but not a subclass of that type which would tighten the restrictions of the method.

Covariance of method return types in the sub type

Covariance means that the type being used can be a sub type of the class provided by the super class function return type. Similarly, this works in the same way as the 5th rule:

Apply at the least the same rules to all output parameters as applied by the parent class.

Now both of these rules aren’t possible to be broken as part of Swift. It’s not possible to overload functions providing alternative type specifications, at least while still referring to the super class type. We can override methods and provide different parameter types and return types but this requires the calling class to know the type of the subclass. When referring to the super class, the super class implementation is always called regardless of subclass functions with different params.

Read More

SOLID Principles in Swift - Open / Closed Principle

Background

In this series of posts we are going to be covering the SOLID principles of software development. These are a set of principles / guidelines, that when followed when developing a software system, make it more likely that the system will be easier to extend and maintain over time. Let’s take a look at the problems that they seek to solve:

  • Fragility: A change may break unexpected parts, it is very difficult to detect if you don’t have a good test coverage
  • Immobility: A component is difficult to reuse in another project or in multiple places of the same project because it has too many coupled dependencies
  • Rigidity: A change requires a lot of effort because it affects several parts of the project

So what are the SOLID principles?

  • Single Responsibility Principle - A class should have only a single responsibility / have only one reason to change
  • Open-Closed Principle - Software should be open for extension but closed for modification
  • Liskov Substitution Principle - Objects in a program should be replaceable with instances of their sub types without altering the correctness of the program
  • Interface Segregation Principle - Many client-specific interfaces are better than one general-purpose interface
  • Dependency Inversion Principle - High level modules should not depend on low level modules. Both should depend on abstractions

In this article we will focus on the Open-Closed Principle.

What does it mean?

So the open-closed principle states:

Software should be open for extension but closed for modification

What exactly does this mean? I think out of all the principles this is the hardest to understand. Mostly due to the fact the explanation leaves far too much open to interpretation. A simple Google search will offer up several examples of how this principle works. In this article I will present my take on the principle and how to build software that will comply with it.

Let’s focus on a type that by design, violates the open closed principle.

Enums

Enums are a very powerful tool in Swift. They are first class types and such can have associated values and conform to protocols for example. However when used at the boundary of a particular system or module they can present a particular problem.

Let’s imagine an analytics system where we can log events. This is a design pattern I’ve seen in many places:

// 1
enum AnalyticsEvent {
    case newsList
    case newsDetail(id: Int)
}

// 2
class AnalyticsController {
    func sendEvent(_ event: AnalyticsEvent) {
        let title = event.title
        let params = event.params
        
        // Send data to analytics network
    }
}

// 3
extension AnalyticsEvent {
    var title: String {
        switch self {
        case .newsList:
            return "News List"
        case .newsDetail:
            return "News detail"
        }
    }
    
    var params: [String : String] {
        switch self {
        case .newsList:
            return [:]
        case .newsDetail(let id):
            return ["id": "\(id)"]
        }
    }
}

Let’s look at what we have here.

  1. The first thing that is defined is an enum that houses all the different analytics events that are available. Some with associated values.
  2. Next we have our analytics controller, this takes an event as a parameter, takes information from the event and would then send that on to our analytics system.
  3. Here we have extended the AnalyticsEvent enum to add 2 variables, one for title and one for params that contain a switch for each of our events.

On the surface or at first look this might appear an ok solution. We have hidden our implementation of the analytics network inside our AnalyticsController and setup a defined set of events that we can support.

The Problem

Now lets look at the problems that this approach causes.

  • What happens if we need to add new events to our analytics system?
  • What if our analytics system was part of a separate package or module?
  • What happens when we have a lot of events?

So first of all, every time we need to add / update or remove any of the events in our analytics system we need to modify the enum. We can’t just implement new events and have them be compatible with the system. Also if the number of events becomes very large then the code will grow large in size. Making it hard to read, maintain and a bit of a mess. Also the enum now has multiple responsibilities, as it covers many events breaking the single responsibility principle.

The second issue which is probably the more important one, is let’s say we are breaking our app down in to separate packages. This Analytics Controller and Event would be in a separate package, what if we wanted to re-use it across different projects? Both of these scenarios become very difficult because we are using an enum that would need to be updated to accommodate events for different apps. The package would need constantly updating as new events were added.

The Solution

So we have identified some issues with the above implementation, how can we change it to make solve these issues we have identified? Look at the new example:

// 1
struct NewsListEvent: AnalyticsEvent {
    var title: String {
        return "News List"
    }
    
    var params: [String : String] {
        return [:]
    }
}

struct NewsDetailEvent: AnalyticsEvent {
    let id: Int
    
    var title: String {
        return "News detail"
    }
    
    var params: [String : String] {
        return ["id": "\(id)"]
    }
}

// 2
protocol AnalyticsEvent {
    var title: String { get }
    var params: [String: String] { get }
}

class AnalyticsController {
    func sendEvent(_ event: AnalyticsEvent) {
        let title = event.title
        let params = event.params
        
        // Send data to analytics network
    }
}

Let’s look at how we have changed the example:

  1. First of all we have now removed the enum. Using an enum as a huge list of possible options is considered a code smell. Especially when it involves something that may change often. If you have a finite number of states that is unlikely to change, that is more suited to an enum than a list of analytics events. We have refactored those enum cases into 2 separate classes now.

  2. We have switched the enum for a protocol that exposes the necessary items required by our analytics controller (we could have potentially done this in the previous example however we would still have the enum).

So what advantages does this have over the previous implementation?

  • With the events now being in separate classes we are now following the single responsibility principle, each event has its own class that can be updated whenever they need to be.
  • Now that we are using a protocol and not an enum, we are now able to add new events to our app without ever having to touch the analytics system. Simply create a new class and make it conform to AnalyticsEvent, and we can use it with the analytics controller.
  • Further to that we could have our analytics system in a separate reusable package, then our client apps could define their own set of events to use with the system.

Our analytics code is now open for extension, but does not need to be modified to support new events. Unlike our enum example.

Read More

SOLID Principles in Swift - Single Responsibility Principle

Background

In this series of posts we are going to be covering the SOLID principles of software development. These are a set of principles / guidelines, that when followed when developing a software system, make it more likely that the system will be easier to extend and maintain over time. Let’s take a look at the problems that they seek to solve:

  • Fragility: A change may break unexpected parts, it is very difficult to detect if you don’t have a good test coverage
  • Immobility: A component is difficult to reuse in another project or in multiple places of the same project because it has too many coupled dependencies
  • Rigidity: A change requires a lot of effort because it affects several parts of the project

So what are the SOLID principles?

  • Single Responsibility Principle - A class should have only a single responsibility / have only one reason to change
  • Open-Closed Principle - Software should be open for extension but closed for modification
  • Liskov Substitution Principle - Objects in a program should be replaceable with instances of their sub types without altering the correctness of the program
  • Interface Segregation Principle - Many client-specific interfaces are better than one general-purpose interface
  • Dependency Inversion Principle - High level modules should not depend on low level modules. Both should depend on abstractions

In this article we will focus on the Single Responsibility Principle.

Problem

The first principle in the list is the Single Responsibility Principle. This principle is defined as follows:

A class should have only one reason to change

This means a class should be responsible for only one task, not multiple. Let’s take a look at an example and how we can refactor it using the principle.

struct SomeNews: Codable {
    let id: Int
    let title: String
}

class NewsDatasource {
    func getNews(completion: @escaping ([SomeNews]) -> Void) {
        // 1. Create request
        let url = URL(string: "SomeNews/URL")!
        let request = URLRequest(url: url)
        
        // 2. Fetching data
        let dataTask = URLSession.shared.dataTask(with: request) { (data, response, error) in
            
            // 3. Parsing data
            guard let data = data,
                  let news = try? JSONDecoder().decode([SomeNews].self, from: data) else {
                completion([])
                return
            }
            
            completion(news)
        }
        
        dataTask.resume()
    }
}

This looks like a fairly simple news datasource / service that is fetching some news items from the web. However if we take a closer look we will see it’s responsible for more than one task.

  1. Creating the URLRequest that is used to fetch the news articles
  2. Fetching the data using a URLSession
  3. Parsing the data

Already that is 3 different responsibilities this class has. They may seem fairly straight forward in this example but imagine how this could get out of hand quickly in a larger codebase. Let’s cover some of the scenarios.

  • Is this example the news request is simple. However what if the request was more complex, what if we needed to add headers etc to that request? All that code would be in this class.
  • What if we wanted to change the request used to fetch the news? We would have to make a code change here. Or what if we could fetch news from more than one API? How would we do that in the current structure?
  • Once the request has been made we are using a JSONDecoder to decode the response. What if the response comes back in a different format? What if we wanted to use a different decodable for the response?
  • What if the news request can be used in multiple places?

As we can see from the above list, there are several scenarios that would require a code change of this class. If we recall what the single responsibility stands for:

A class should have only one reason to change

There is also a side effect of this which isn’t as obvious, that is testability. Let’s look at some examples:

  • How would we test changes the URLRequest? If did indeed change the URLRequest or it was being generated differently, how would we test that?
  • How do we test how our class handles responses from the server? What happens if we get an error for example?
  • How do we test our decoding code? How can we be sure that it is going to handle incorrect data correctly? How does our news datasource handle decoding errors?

If we look at the code in the example we can see that in would be impossible to write unit tests covering any of the above scenarios. Let’s have a look at how we can break this class down into single components, allowing us to make changes only in one place and at the same time improving testability.

Breaking it down

URL Builder

Let’s start by breaking this class down into separate classes, each with one responsibility. First of all let’s take out the building of the URLRequest and put it in another class.

class NewsURLBuilder {
    private let hostName: String
    
    init(hostName: String) {
        self.hostName = hostName
    }
    
    func getNews() -> URLRequest {
        let url = URL(string: "\(hostName)SomeNews/URL")!
        let request = URLRequest(url: url)

        return request
    }
}

Great, now we have a class that’s only responsibility is to build and return a URLRequest. In a more complex system this class might need ids, user tokens etc in order to configure the request. In the scenario where we need to change how news is retrieved we only need to modify this one class in order to make that change. We can also change the hostname based on the environment such as dev, test and prod.

The other benefit of doing this is we can now write unit tests to make sure that the URLRequest is being built correctly. Let’s do a small example now:

class URLBuilderTests: XCTestCase {

    func testURLBuilder() throws {
        let builder = NewsURLBuilder(hostName: "http://mytest.com/")
        let request = builder.getNews()
        
        XCTAssertEqual(request.url?.absoluteString, "http://mytest.com/SomeNews/URL", "Request URL string is incorrect")
    }

}

Our URL builder isn’t particularly complex so doesn’t need many tests. But at least here with it being in a separate component we can test the construction and make sure it’s being created correctly. We could expand this test to test other elements of the request if needed, or if we needed different parameters to build the request.

Parser

Next lets take the parser and put that into it’s own class.

class NewsParser {
    private let decoder: JSONDecoder
    
    init(decoder: JSONDecoder) {
        self.decoder = decoder
    }
    
    func parse(data: Data) -> [SomeNews] {
        return (try? decoder.decode([SomeNews].self, from: data)) ?? []
    }
}

Here we can see we have taken our decoding code and put it into a separate class. This class has one reason to change, it only needs to be changed if the parsing needs to be changed! Also like our URL builder class we can now test the decoding to make sure we get the results we are expecting:

class NewsParserTests: XCTestCase {

    func testCorrectData() throws {
        let correctJSON = """
        [
          {
            "id": 1,
            "title": "Test Article 1"
          },
          {
            "id": 2,
            "title": "Test Article 2"
          }
        ]
        """
        
        let data = correctJSON.data(using: .utf8)!
        
        let parser = NewsParser(decoder: JSONDecoder())
        let news = parser.parse(data: data)
        XCTAssertFalse(news.isEmpty)
        XCTAssertEqual(news[0].id, 1)
        XCTAssertEqual(news[0].title, "Test Article 1")
    }

    
    func testInCorrectData() throws {
        let incorrectJSON = """
        [
          {
            "id": 1,
            "title": "Test Article 1"
          },
          {
            "id": 2,
        ]
        """
        
        let data = incorrectJSON.data(using: .utf8)!
        
        let parser = NewsParser(decoder: JSONDecoder())
        let news = parser.parse(data: data)
        XCTAssertTrue(news.isEmpty)
    }
}

So what have we done here. We have created a couple of unit tests for our parser.

  • The first one supplies the parser with some correct JSON data and checks that the news objects we receive are correct and have the right data.
  • The second test sends some incorrect data to the parser and tests that we receive an empty array as expected

I’m aware that we aren’t handling errors in this example, this has been done to try and keep things as simple as possible

Putting it all together

Now that we have separated out these components into separate pieces, lets see how our datasource looks now.

class NewsDatasource {
    private let requestBuilder: NewsURLBuilder
    private let parser: NewsParser
    
    init(requestBuilder: NewsURLBuilder, parser: NewsParser) {
        self.requestBuilder = requestBuilder
        self.parser = parser
    }
    
    func getNews(completion: @escaping ([SomeNews]) -> Void) {
        // 1. Create request
        let request = requestBuilder.getNews()
        
        // 2. Fetching data
        let dataTask = URLSession.shared.dataTask(with: request) { [weak self] (data, response, error) in
            
            // 3. Parsing data
            guard let self = self,
                let data = data else {
                completion([])
                return
            }
            
            completion(self.parser.parse(data: data))
        }
        
        dataTask.resume()
    }
}

Now if we look here we can see that we have swapped out the code for building the request and parsing the data for our separate classes. Now our example is following the single responsibility principle. We have 3 components now:

  1. A component to build our request
  2. A component to execute the request
  3. A component to parse the data we get back from the request

So what have we gained:

  • We now have test coverage of our components (we could update the NewsDatasource to have tests too but that is a bit more advanced and out of scope of this article)
  • We have the ability to re-use these components in other parts of the app or in other apps if we need to
  • If we need to make changes, each component is only responsibility for one thing, so we can update and test each change in turn. Rather than making multiple changes in one place and not be able to test them!

Feel free to download the sample and play around with the tests yourself!

Read More

Repository Pattern in Swift

Background

All apps developed require data of some description. This data is stored somewhere, could be on the device itself, in a remote database/service or a combination. Let’s take a look at the most common sources of data:

Each of these methods saves data in a different format. Now I’m sure you will have used at least one of these methods in your apps at some point to retrieve / save data.

When not using the repository pattern it is quite common to access and use these elements directly, either in your ViewController or in some other part of your app depending how it is structured.

The problem

What’s the problem with this approach? Your app becomes difficult to maintain. Now if you only have a small app with a few screens then this isn’t much of a problem as there are only a few elements to change.

However, what if you are working on a large app with several developers and lots of code? You could have NSManagedObjects or Codable objects littered throughout the codebase for example. What happens if you wish to remove Core Data? Perhaps move to realm? You would need to modify all of the classes in your codebase where you had used your Core Data objects.

Similarly, if you are using Codable objects directly from your JSON response. What happens when your backend team changes the API or you switch to a different API provider? The structure of the data may change which means your Codable objects might change. Again you will need to modify a large number of classes if you are working on a large app.

We can also apply this to the other options such as accessing data from 3rd party frameworks. If we use the objects returned from the framework directly, they will all need changing if we change provider or the SDK changes.

There is also the question of query language. Web services use headers and URLQueryItem, Core Data uses Predicates and so on. Every entry point to query the data must know and understand the underlying query language in order to get the information it once. Again, if this changes we need change every query point to the new format.

Let’s have a look at the diagram below:

Core Data Example

Here we have an app structure that is making use of Core Data. There is an object that is being used to access the stack that returns some data. Let’s say for this example that it is news articles. These new articles must inherit from NSManagedObject to be used in Core Data. Now if our data layer is returning NSManagedObjects to the rest of our app structure we now have a dependency between Core Data and the rest of the files in our app. If we wish to move to Realm for example, or switch to using some other form of data store we would need to modify all the of files in the app. The app in this example is only small, imagine having to do that for a much bigger app!

Domain Objects and the Repository

This is where Domain Objects come in. Domain Objects are value objects that are defined by your application. Rather than using objects and structures defined outside of the app, we define what we want the objects to look like. It’s then up to the repository to map between the data storage object / structure to these value objects.

When we do this, it means any changes to the data access layer, as we discussed earlier such as data structure changes or changes in provider don’t impact the rest of the app. The only part of the app that needs to be updated is the repository and it’s mapping to the domain objects.

The below quote summarises the idea of the pattern:

Repositories are classes or components that encapsulate the logic required to access data sources. They centralize common data access functionality, providing better maintainability and decoupling the infrastructure or technology used to access databases from the domain model layer.

Let’s have a look at our previous example but modified to use the a repository and domain objects:

Core Data Example 2

So what is the difference here? As you can see the Core Data stack is still returning NSManagedObjects, however the repository is converting that to a domain object. This object doesn’t inherit from NSManagedObject, also it’s structure and attributes are defined by the app rather than what is in the data store.

Now if we wanted to move away from Core Data to something else the only classes that need to be changed are the Core Data stack and the repository. The rest of the app does not need to be changed as we can map the new data stores type to our domain objects using the repository.

Example

To show a small working example we are going to use a couple of Free Public APIs (highly recommend this resource if you are looking to build a demo app or experiment). We will use 2 APIs that returns users. However they return them in a different format.

https://jsonplaceholder.typicode.com/users/1

https://randomuser.me/api/

As we have done in previous blog posts we are going to use QuickType to generate our Codable objects from our JSON response. We will start with our first request.

// MARK: - User
struct User: Codable {
    let id: Int
    let name, username, email: String
    let address: Address
    let phone, website: String
    let company: Company
}

// MARK: - Address
struct Address: Codable {
    let street, suite, city, zipcode: String
    let geo: Geo
}

// MARK: - Geo
struct Geo: Codable {
    let lat, lng: String
}

// MARK: - Company
struct Company: Codable {
    let name, catchPhrase, bs: String
}

This structure will allow us to decode the response from the first request. Let’s make a simple example that takes the response and outputs some data. We will be using code from our Simple JSON Decoder to process the output so feel free to read up if the code you see doesn’t make sense.

let url = URL(string: "https://jsonplaceholder.typicode.com/users/1")!
// 1
let task = URLSession.shared.dataTask(with: url, completionHandler: { (user: User?, response, error) in
	// 2
    if let error = error {
        print(error.localizedDescription)
        return
    }

    // 3
    if let user = user {
        print(user.name)
        print(user.address.street)
        print(user.address.city)
        print(user.address.zipcode)
        print(user.address.geo.lat)
        print(user.address.geo.lng)
    }
})
task.resume()

So let’s step through what’s happening here:

  1. First of all we are making the request using our Simple JSON Decoder to return our new User type.
  2. Output any errors
  3. So here we are outputting the name, address and location of the user we get back. Super simple right now.

Managing change

Now let’s say we change provider. Maybe our backend team changes the API, or we switch data provider or from 2 different data provider SDKs. In our example we will switch from the first url (https://jsonplaceholder.typicode.com/users/1) to the second (https://randomuser.me/api/).

The first thing we will need to do is change all of our codable objects as the structure of the response is different. Let’s use QuickType again to give us the new structure:

// MARK: - Users
struct Users: Codable {
    let results: [Result]
    let info: Info
}

// MARK: - Info
struct Info: Codable {
    let seed: String
    let results, page: Int
    let version: String
}

// MARK: - Result
struct Result: Codable {
    let gender: String
    let name: Name
    let location: Location
    let email: String
    let login: Login
    let dob, registered: Dob
    let phone, cell: String
    let id: ID
    let picture: Picture
    let nat: String
}

// MARK: - Dob
struct Dob: Codable {
    let date: String
    let age: Int
}

// MARK: - ID
struct ID: Codable {
    let name: String
    let value: String?
}

// MARK: - Location
struct Location: Codable {
    let street: Street
    let city, state, country: String
    let postcode: Int
    let coordinates: Coordinates
    let timezone: Timezone
}

// MARK: - Coordinates
struct Coordinates: Codable {
    let latitude, longitude: String
}

// MARK: - Street
struct Street: Codable {
    let number: Int
    let name: String
}

// MARK: - Timezone
struct Timezone: Codable {
    let offset, timezoneDescription: String

    enum CodingKeys: String, CodingKey {
        case offset
        case timezoneDescription = "description"
    }
}

// MARK: - Login
struct Login: Codable {
    let uuid, username, password, salt: String
    let md5, sha1, sha256: String
}

// MARK: - Name
struct Name: Codable {
    let title, first, last: String
}

// MARK: - Picture
struct Picture: Codable {
    let large, medium, thumbnail: String
}

Now this is more complicated that it needs to be for our example but I’m leaving it here as an extreme example of how different things can be. As you can probably tell the structure and types have change dramatically from our first example. So let’s try and output the same data from this example in our previous example. We can ignore the request part and just focus on the data output so we can see the differences:

// Request 1 output
if let user = user {
    print(user.name)
    print(user.address.street)
    print(user.address.city)
    print(user.address.zipcode)
    print(user.address.geo.lat)
    print(user.address.geo.lng)
}


// Request 2 output
if let user = users?.results.first {
    print("\(user.name.first) \(user.name.last)")
    print(user.location.street.name)
    print(user.location.city)
    print(user.location.postcode)
    print(user.location.coordinates.latitude)
    print(user.location.coordinates.longitude)
}

As you can see from even this simple example. We would have to change 7 lines of code, just to produce the same output. Now imagine this change happening on a much bigger project! There could possibly be 100s of lines of code that would need updating, all because the API response has changed.

Repository Pattern

Here is where the repository pattern comes in. We can create a user repository that fetches the user and converts it to our domain object. That way we don’t need to update the output.

First thing to do is design our domain object that will represent a User in our system. Now all we are doing in this simple example is outputting a few attributes so let’s design our object with just those attributes as we don’t need the rest.

struct DomainUser {
    let name: String
    let street: String
    let city: String
    let postcode: String
    let latitude: String
    let longitude: String
}

Here we have a nice simple representation of our User object. There is no need to consider any of the other possible attributes returned from the API. We aren’t using them in our application and they will just sit around taking up valuable memory. You will also notice that this object doesn’t conform to Codable or subclass NSManagedObject. This is because DomainObject should not contain any knowledge about how they are stored. That is the responsibility of the repository.

To design our repository we can make use of Generics and Protocols to design a repository we can use for anything, not just our DomainUser. Let take a look:

protocol Repository {
    associatedtype T
    
    func get(id: Int, completionHandler: (T?, Error?) -> Void)
    func list(completionHandler: ([T]?, Error?) -> Void)
    func add(_ item: T, completionHandler: (Error?) -> Void)
    func delete(_ item: T, completionHandler: (Error?) -> Void)
    func edit(_ item: T, completionHandler: (Error?) -> Void)
}

protocol CombineRepository {
    associatedtype T
    
    func get(id: Int) -> AnyPublisher<T, Error>
    func list() -> AnyPublisher<[T], Error>
    func add(_ item: T) -> AnyPublisher<Void, Error>
    func delete(_ item: T) -> AnyPublisher<Void, Error>
    func edit(_ item: T) -> AnyPublisher<Void, Error>
}

Here we have different functions for all of the operations we can do. What you will notice is that none of these functions specify where or how the data is stored. Remember when we talked about different storage options at the beginning? We could implement a repo that talks to an API (like in our example), one that stores things in Core Data or one that writes to UserDefaults. It’s up to the repository that implements the protocol to decide these details, all we care about is that we can load and save the data from somewhere.

See it action

Now we have defined what the repository pattern is, let’s create 2 implementations. One for our first request and one for the second. Both should return domain objects, rather than the type returned from the request.

// 1
enum RepositoryError: Error {
    case notFound
}

struct FirstRequestImp: Repository {
    typealias T = DomainUser
    
    // 2
    func get(id: Int, completionHandler: @escaping (DomainUser?, Error?) -> Void) {
        let url = URL(string: "https://jsonplaceholder.typicode.com/users/1")!
        let task = URLSession.shared.dataTask(with: url, completionHandler: { (user: User?, response, error) in
            if let error = error {
                completionHandler(nil, error)
                return
            }

            guard let user = user else {
                completionHandler(nil, RepositoryError.notFound)
                return
            }
            
            // 3
            let domainUser = DomainUser(
                name: user.name,
                street: user.address.street,
                city: user.address.city,
                postcode: user.address.zipcode,
                latitude: user.address.geo.lat,
                longitude: user.address.geo.lng
            )
            
            completionHandler(domainUser, nil)
        })
        task.resume()
    }
    
     // 4
    func list(completionHandler: @escaping ([DomainUser]?, Error?) -> Void) {}
    func add(_ item: DomainUser, completionHandler: @escaping (Error?) -> Void) {}
    func delete(_ item: DomainUser, completionHandler: @escaping (Error?) -> Void) {}
    func edit(_ item: DomainUser, completionHandler: @escaping (Error?) -> Void) {}
}

struct SecondRequestImp: Repository {
    typealias T = DomainUser
    
    func get(id: Int, completionHandler: @escaping (DomainUser?, Error?) -> Void) {
        let url = URL(string: "https://randomuser.me/api/")!
        let task = URLSession.shared.dataTask(with: url, completionHandler: { (users: Users?, response, error) in
            if let error = error {
                completionHandler(nil, error)
                return
            }

            guard let user = users?.results.first else {
                completionHandler(nil, RepositoryError.notFound)
                return
            }
            
            // 5
            let domainUser = DomainUser(
                name: "\(user.name.first) \(user.name.last)",
                street: user.location.street.name,
                city: user.location.city,
                postcode: "\(user.location.postcode)",
                latitude: user.location.coordinates.latitude,
                longitude: user.location.coordinates.longitude
            )
            
            completionHandler(domainUser, nil)
        })
        task.resume()
    }
    
    func list(completionHandler: @escaping ([DomainUser]?, Error?) -> Void) {}
    func add(_ item: DomainUser, completionHandler: @escaping (Error?) -> Void) {}
    func delete(_ item: DomainUser, completionHandler: @escaping (Error?) -> Void) {}
    func edit(_ item: DomainUser, completionHandler: @escaping (Error?) -> Void) {}
}

There’s quite a bit of code here so let’s step through it.

  1. First of all we have defined a new error to send back if we don’t receive any user info from the API.
  2. This is the same call we made in our example before.
  3. Now here we are taking the returned Codable User and converting it to your new DomainUser class.
  4. We aren’t implementing the other functions in this example so just leaving them empty for now to remove errors.
  5. This struct is the second request we are making, and again here we are mapping our Users Codable type from the second request to our DomainUser.

Now that we have made our two repositories, let’s show how we can quickly switch between them without breaking / changing code.

let repository: FirstRequestImp = FirstRequestImp()
repository.get(id: 1) { (user, error) in
    if let error = error {
        print(error)
    }
    
    if let user = user {
        print(user.name)
        print(user.street)
        print(user.city)
        print(user.postcode)
        print(user.latitude)
        print(user.longitude)
    }
}

Here is our example from earlier in the article but updated to use our new repositories. Here we go and fetch the user and print their details, the same as before. Now below we can switch to our second request and see how that will work.

let repository: SecondRequestImp = SecondRequestImp()
repository.get(id: 1) { (user, error) in
    if let error = error {
        print(error)
    }
    
    if let user = user {
        print(user.name)
        print(user.street)
        print(user.city)
        print(user.postcode)
        print(user.latitude)
        print(user.longitude)
    }
}

Now notice how the only part we changed was the implementation class? The rest of the code remained the same even though where the data was coming from has changed and is coming back in a completely different structure. Now imagine we are using this repo in many places to fetch user details. We can quickly switch between different data sources without changing the code that uses it. The only changes we have to make are to the repo and to the data mapping code. So only one change rather than a change in every single class that uses these objects.

Conclusion

So let’s recap what we have discussed here:

  • First of all we discussed the problem of using data storage classes throughout your codebase. Especially on large projects if you need to switch data source / structure.
  • We then discussed how using the repository pattern and mapping to domain objects rather than using data storage classes can make your code easier to change in the future.
  • We worked through some examples of how changing API structures can impact your code.
  • We then implemented a basic repository pattern with mapping to domain objects to show how doing this can make updating your project easier.

Finally let’s discuss the pros and cons of the approach:

Advantages

  • Code is easier to change if you need to switch data source or structure
  • Separates concerns of where / how data is stored away from the rest of your app

Disadvantages

  • Adds more code and complexity
  • Need to write mappers for each object to domain objects
  • Not really needed on smaller solo projects

Feel free to download the playground and play around with the examples yourself

Read More