← back to blog

High-Level vs. Low-Level Modules

2025-01-06

Swift Music

// High-Level Module
class MusicPlayer {
    private let songFetcher: SongFetcher

    init(songFetcher: SongFetcher) {
        self.songFetcher = songFetcher
    }

    func play() {
        let song = songFetcher.fetchNextSong()
        print("Now playing: \(song)")
    }
}

// Low-Level Modules
protocol SongFetcher {
    func fetchNextSong() -> String
}

class PlaylistSongFetcher: SongFetcher {
    func fetchNextSong() -> String {
        return "Song from the playlist"
    }
}

class NetworkSongFetcher: SongFetcher {
    func fetchNextSong() -> String {
        return "Song from the cloud"
    }
}