Favor composition over inheritance — in Swift

Application design still has importance, no matter which “fun” framework you want to learn this week

Steven Curtis
5 min readSep 9, 2019

--

Object-oriented langages have been accused of a lack of reusability. The accusation is that there is an implicit exnvironment that they carry around them. A possible solution to this is protocol conformance, and this Medium post will cover this particular topic.

Prerequisites:

  • Use of the Mirror API for reflection
  • Some understanding of OOP is useful

Terminology

Composition: A fundamental OO concept, where a class is described that reference one or more object of other classes in instance variables.

Interface: A programming structure that allows properties to be exposed as a public API.

Inheritance: A fundamental OO concept that enables new objects to take on the properties of existing objects. A class that inherits from a superclass is called a subclass or derived class.

Mixin: A special kind of multiple inheritance. Is a trait with its own properties, and since property values are stored in the concrete class rather than the protocol we can say that Swift does not fully support mixins.

Trait: An interface containing method bodies (in Swift protocol extensions can provide the trait of interface methods).

The problem

Saving and loading files

I’ve created a nice little App that simply saves and loads files.

To do so we are going to use inheritance, in this case the implementation of a base class.

This means that each class inheriting from it needs to implement a read and a write function

class FileHandlerBaseClass {func read(_ filename: String) -> String {return ""}func write(_ filename: String, _ contents: String) {}func allFiles() -> [String] {return []

--

--