TANASCHITA.COM
Articles about Swift and iOS Development by Natascha Fadeeva

iOS Interview Questions and Answers for Senior Developers Part 5 - Architecture & Design Patterns

Check your knowledge on architecture and design patterns in Swift iOS

Image of the author.
Published 2. September 2020 - 6 min read

I recently got into the position of leading the technical interviews when my client was searching for a new senior iOS developer.

It's a challenging task to evaluate the skills and knowledge of another developer. In this post, I share my results of the most useful iOS and Swift questions and answers with you. I categorised the questions into different topics:

  1. Swift Programming Language (covered here)
  2. Networking (covered here)
  3. Persistence & Databases (covered here)
  4. Concurrency (covered here)
  5. Architecture & Design Patterns (covered in this post)
  6. Testing (coming soon)
  7. Continuous Integration (coming soon)

The purpose of these interview questions is to get to know the developers knowledge on architecture and design patterns with a focus on iOS development.

Software architecture and design pattern decisions have a great impact on the success of a product, especially in the long run.
Software architecture and design pattern decisions have a great impact on the success of a product, especially in the long run.

So let's get started.

1. What is the idea behind the MVC architecture?

MVC stands for Model View Controller.

  • the View represents the User Interface layer
  • the Model represents the Data Access layer
  • the Controller represents the Business Logic layer

The controller is the mediator between the view and the model. The model and the view know nothing about the controller or each other. They communicate with the outside world by sending a notification about some event, for example by calling a callback method or using the observer pattern.

2. Which alternative architectures do you know? Explain one of them.

Examples of alternative architectures are MVVM (Model-View-ViewModel), MVP (Model-View-Presenter) or VIPER (View-Interactor-Presenter-Entity-Routing).

The MVVM architecture consists of a Model, a View and a ViewModel. The View and the Model are already familiar from MVC and have the same responsibilities. The mediator between them is represented by the View Model.

In theory, you could say that MVC and MVVM are the same architectures with different namings for the mediator. In practice however, many developers ran into the Massive View Controller problem with Apple's MVC by using a UIViewController as the Controller. But UIViewControllers are too involved in the View’s life cycle so it’s hard to separate them.

The main difference between the ViewModel from MVVM and the Controller from MVC is that the ViewModel is defined to be UIKit independent. With MVVM, the UIViewController becomes part of the View.

3. Explain the observer design pattern. What options do you have to implement the observer design pattern in Swift?

The observer design pattern is characterized by two elements:

  • A value being observed (an observable), which notifies all observers if a change happens.
  • An observer, who subscribes to changes of the observable.

Existing solutions of the observer pattern in iOS are:

  • Notifications
  • Key-Value Observing
  • Publishers (observables) and Subscribers (observers) of the Combine Framework

4. What is a singleton design pattern? When would you use and when would you avoid singletons?

The singleton design pattern ensures that only one instance exists for a given class.

In Swift, this pattern is easy to implement:

class ChocolateFactory {
    static let shared: ChocolateFactory = {
        let instance = ChocolateFactory()
        return instance
    }()
}

A singleton is useful when exactly one object is needed to coordinate actions across the app. A good example is Apple's UIApplication.shared instance, because within the app there should be only one instance of the UIApplication class.

The singleton pattern is easy to overuse though. In most cases, it can be replaced with dependecy injection, for example by passing the dependencies into the object's initializer. With the dependecy injection approach, modularity and testability of the code improves. It becomes a lot easier to mock and fake passed in dependencies for unit tests.

5. Name some other design patterns you know and give a short explanation.

Examples of other design patterns are the delegate design pattern, the factory design pattern and the facade design pattern.

The delegate design pattern allows an object to communicate back to its owner in a decoupled way. This way, an object can hand off (delegate) some of its responsibilities to its owner. A common way to define a delegate is by using protocols. The delegate design pattern is an old friend on Apple's platforms. Examples are UITableViewDelegate, UICollectionViewDelegate, UITextViewDelegate etc.

The factory design pattern is a way to encapsulate the implementation details of creating objects. It separates the creation from the usage of the objects. The initialization is done in a central place. So when the initialization logic of certain objects changes, you don't need to change every creation in the whole project.

Example of a simple factory:

class ChocolateFactory {
    static func produceChocolate(of type: ChocolateType) -> Chocolate {
        switch type {
        case .dark:
            return DarkChocolate()
        case .raw:
            return RawChocolate()
        }
    }
}

The facade design pattern provides a simpler interface for a complex subsystem. Instead of exposing a lot of classes and their APIs, you only expose one unified API. The facade pattern improves the readability and usability. It also decouples and reduces dependencies. If implementation details under the facade change, the facade can retain the same API while things change behind the scenes.

For example, you could create a ChocolateShopService and hide all the http requests and persistence details behind it.

class ChocolateShopService {

    func getChocolates() -> [Chocolate] {
        if isOnline {
            return httpClient.get("/api/chocolates")
        } else {
            return localStore.getChocolates()
        }
    }
}

6. How can you avoid the problem of so called spaghetti code?

The term spaghetti code is used for unstructured and difficult-to-maintain code. To avoid spaghetti code it is important to constantly think about building clean, reusable and testable components.

Those qualities can be achieved by focusing on decoupling and separation of concerns, for example through dependency injection, generic solutions, protocol oriented programming and by using appropriate design patterns.

7. What is your undestanding of reactive programming? What possibilities do you have on iOS?

Reactive programming is programming with asynchronous observable streams.

A stream (also called an observable) can emit either a value of some type, an error or a completed event. You can listen to a stream by subscribing to it (observing it).

You can observe those async streams and react with various functional methods when a value is emitted. You can merge two streams, filter a stream to get another one or map data values from one stream to another new one.

To use reactive programming in iOS you can use the Combine framework that was introduced at WWDC 2019. Or you can use a third party library like RxSwift.

8. What is TDD? What benefits and limitations does it have?

TDD stands for test driven development. The idea behind it is to write tests before writing code.

Benefits Test driven development leads to higher code test coverage. Also, the tests provide documentation about how the app is expected to behave. TDD helps to build modularized code, because it requires the developer to think in small units that can be written and tested independently. This leads to decoupled focused components and clean interfaces.

Limitations TDD only focuses on unit tests, it does not cover UI or integration tests. So additional tests are needed to make sure that the app is working properly. When using TDD, code design decisions become even more important than they already are, because tests become part of the maintenance overhead. Badly written tests are prone to failure and expensive to maintain.

9. What are good use cases to use extensions in Swift?

An extension in Swift is a powerful way to add new functionality to existing classes, structures or enums without modifying its code.

For example, accessing an array element leads to a crash if the specified index doesn't exist. To avoid a crash, you could wrap every access in an if-block. A more elegant solution with an extension looks like this:

extension Array {
    /// Returns the element at the specified index if it is within bounds, otherwise nil.
    subscript(safe index: Index) -> Iterator.Element? {
        return indices.contains(index) ? self[index] : nil
    }
}

// Usage:

let value = someArray[safe: 6]

10. What is your understanding of protocol oriented programming?

Protocol oriented programming is a concept of designing your code base by using protocols. In Swift, protocols provide an extensive set of features, so they have become a powerful way of managing code complexity and creating modular testable components.

A protocol allows you to group similar methods and properties for classes, structs and enums. In contrast to class inheritence, objects can conform to multiple protocols.

Like classes, protocols also support inheritence. For example, the Comparable protocol inherits from Equatable in Swift. You can also combine two protocols together to build new protocols, for example:

typealias Codable = Decodable & Encodable

To implement default behaviour with protocols, you can use protocol extensions.

protocol Chocolate {
    var hasSugar: Bool { get }
}

extension Chocolate {
    var hasSugar: Bool {
        return true
    }
}

struct DarkChocolate: Chocolate {
    // hasSugar is true by default
}

This way, all types that conform to the same protocol will get the default behaviour.

11. Explain dependency injection. What types of dependency injection do you know?

Dependency injection is a technique where an object gets its dependencies from the outside instead of creating the dependency internally. With dependency injection, the objects get less coupled, more reusable and more testable, it gets a lot easier to mock objects for unit tests.

Dependency injection can be implemented in different ways, for example an initializer-based or a property-based dependency injection.

There are also some external libraries like Swinject or Dip that centralize the managing of dependencies.

Written by

Image of the author.
Natascha Fadeeva
Author and creator of this site

Contact

Image Credits

Image credits to michelekieslichfotografie from Pixabay