wnagrodzki / iOSProgrammingGuidelines

2 stars 0 forks source link

Sharing helper methods via protocol extension #30

Closed wnagrodzki closed 4 years ago

wnagrodzki commented 5 years ago

Place shared helper methods in extension of dedicated separate protocol.

// MyProtocol.swift

protocol MyProtocol {
    func method()
}

protocol MyProtocolBase { }

extension MyProtocolBase {

    func helperMethod() { }
}
// MyProtocolImplA.swift

class MyProtocolImplA: MyProtocol {

    func method() {
        // helperMethod() can be called here due to MyProtocolBase conformance
    }
}

extension MyProtocolImplA: MyProtocolBase { }
// MyProtocolImplB.swift

class MyProtocolImplB: MyProtocol {

    func method() {
        // helperMethod() can be called here due to MyProtocolBase conformance
    }
}

extension MyProtocolImplB: MyProtocolBase { }

This is to avoid exposing helper methods in the main protocol and thus polluting it.

wnagrodzki commented 4 years ago

@pwetrifork @Moskacz Is it acceptable to be included?

pwetrifork commented 4 years ago

Looks ok to me, but I would put helper methods in extensions on XXXBase protocols. This way these wouldn't be visible to the main protocol clients (wouldn’t pollute autocomplete lists etc.).

pwetrifork commented 4 years ago

Turns out they wouldn’t be visible either way but I still prefer them on base, as this is the protocol intended to be used by the implementation while the main protocol is for clients.

wnagrodzki commented 4 years ago

Points taken, code updated.

Moskacz commented 4 years ago

Looks ok. Maybe we could add MySecondProtocolImpl class to the example? This way it would be more clear what we try to achieve.

wnagrodzki commented 4 years ago

@pwetrifork @Moskacz Code updated. Do you have a better proposition for name of MyProtocolBase?