Skip to Content
Course content

43: Protocol-Oriented Design Philosophy

Click on the "Edit" button in the top corner of the screen to edit your slide content.

Imagine you're hiring for a startup. In a traditional, old-school company, you might hire someone because they have a "Management Degree." That's their identity. Because they are a "Manager," they automatically inherit all the traits, burdens, and expectations of every other manager in the building, whether those traits are actually useful for the specific project at hand or not. This is how Class-based inheritance works; you define what an object is.

Now, imagine a more modern approach. Instead of looking for a "Manager," you look for a list of capabilities. You need someone who can "Write Python," "Manage a Budget," and "Speak Japanese." You don't care if they were a project lead, a freelance consultant, or a former accountant. As long as they can fulfill those specific roles, they're in. This is the heart of Protocol-Oriented Programming (POP). We stop asking "What are you?" and start asking "What can you do?"

Stop Thinking in Family Trees

In a lot of the languages you might have used before Swift, the instinct is to build a deep hierarchy. You'd make a Vehicle class, then a MotorizedVehicle subclass, then a Car subclass. It feels organized at first, but it quickly becomes a nightmare. What happens when you need a Boat that is also Motorized, but also needs to share logic with a FloatingObject? You can't inherit from two classes in Swift. You hit a wall.

When I shifted my mindset to POP, I stopped drawing family trees and started drawing checklists. Instead of a Vehicle base class, I create protocols like Drivable, Floatable, and Fuelable. A Car simply checks the Drivable and Fuelable boxes. A JetSki checks Drivable, Floatable, and Fuelable. It's infinitely more flexible because you're composing behavior rather than inheriting it.

Building Capabilities, Not Hierarchies

Let's look at how this actually looks in code. I'll avoid the typical "Animal" example because it's overused. Let's think about a game system where different entities can be damaged or can move.

protocol Damageable {
    var health: Int { get set }
    func takeDamage(_ amount: Int)
}

protocol Movable {
    var position: CGPoint { get set }
    func move(to point: CGPoint)
}

// A Player is both movable and damageable
struct Player: Damageable, Movable {
    var health = 100
    var position = CGPoint.zero
    
    mutating func takeDamage(_ amount: Int) {
        health -= amount
    }
    
    mutating func move(to point: CGPoint) {
        position = point
    }
}

// A Wall is only damageable
struct Wall: Damageable {
    var health = 500
    
    mutating func takeDamage(_ amount: Int) {
        health -= amount
    }
}

Notice how Wall and Player share no common parent class, yet I can write a function that handles anything Damageable. I don't have to care if it's a player, a wall, or a breakable crate. I just care that it has a takeDamage method.

The Magic of Protocol Extensions

Now, you might be thinking, "Wait, if I have 10 different Damageable objects, do I have to write the takeDamage logic 10 times?" This is where most people get stuck and try to go back to classes. But in Swift, we have Protocol Extensions.

Protocol extensions allow us to provide a default implementation. It's like providing a standard operating procedure for anyone who signs up for that "job description."

extension Damageable {
    func printHealthStatus() {
        print("Current health is \(health).")
    }
    
    // We can even provide a default way to take damage
    mutating func takeDamage(_ amount: Int) {
        health -= amount
        print("Took \(amount) damage!")
    }
}

By adding this extension, the Wall and Player structs from earlier no longer need to implement takeDamage themselves unless they want to do something special (like adding armor calculations for the player). They get the default behavior for free. I've effectively created a "mixin" of functionality without the rigid baggage of a base class.

When to actually use this

I'll be honest with you: you don't need to make everything a protocol. Over-engineering is a real risk here. Use POP when you find yourself wanting to share behavior across types that aren't logically part of the same "family." If you find yourself creating a base class just to avoid repeating a few methods, stop. That's a huge red flag. Create a protocol, add an extension, and keep your types lean and independent.




📋 Practical Task

Building a Modular Smart Home System

You are designing a system for a smart home. Instead of creating a complex class hierarchy (e.g., ElectronicDevice -> Light), you will use a Protocol-Oriented approach to handle different capabilities.

Requirements:

  • Create a protocol Powerable with a boolean property isOn and a method togglePower(). Provide a default implementation for togglePower() in a protocol extension.
  • Create a protocol Dimmable with a property brightness (Int, 0-100) and a method setBrightness(to: Int).
  • Create a protocol Connectable with a property ipAddress and a method connectToWifi(). Provide a default implementation for connectToWifi() that prints "Connecting to network...".
  • Implement three structs:
    • SmartBulb: Should be Powerable, Dimmable, and Connectable.
    • SmartPlug: Should be Powerable and Connectable.
    • BasicLamp: Should only be Powerable.

Testing your logic: Create an array of Powerable objects containing one of each device. Loop through them and call togglePower() on each to prove that the protocol-oriented design allows you to treat different types uniformly based on their capabilities.

Rating
0 0

There are no comments for now.

to be the first to leave a comment.