Search code examples
swiftunit-testingnamingswift-protocols

Conventions for Swift protocols


I have a class called NetworkInterface - and I want to make this class testable. The way to do this in Swift means I should extract a protocol from it? My quandry is, what do I call this protocol? I don't want to call it NetworkInterface as that then takes the 'good name' for the protocol and then what would I call my NetworkInterface class? I've seen a pattern where people give the protocol the nice name and then call the class something horrible like DefaultNetworkInterface but I don't like this either.

Should I call the protocol NetworkInterfaceProtocol and then the class NetworkInterface? What would be conventional here?

Here is the code I have so far, but I'm not convinced my names are conventional.

protocol NetworkInterfaceProtocol {
    func ip4() -> String?
}

struct NetworkInterface: NetworkInterfaceProtocol {
    let interfaceName: String

    func ip4() -> String? {
    ....
    }
}

Solution

  • The only convention for protocol naming by Swift.org is to use noun, able, ible or ing where applicable. reference here

    So one practice is to break down the entity into smaller describable parts and name them like:

    protocol IP4Representable {
        func ip4() -> String?
    }
    
    protocol IP6Representable {
        func ip6() -> String?
    }
    

    And then using it like:

    extension NetworkInterface: IP4Representable & IP6Representable { ... }
    

    You can also merge them in the way the Codable does like:

    typealias IPRepresentable = IP4Representable & IP6Representable
    
    extension NetworkInterface: IPRepresentable { ... }
    

    Indeed you can have bigger chunks based on the needs and it does not have to be a 'single function only' in each protocol.

    I hope you got the idea.