Default Implementation in Protocols

I found it useful to follow this to it's likely end.

If you add default function implementation, I think it follows that also adding them to properties, static functions, static properties, and initializers will be either innevitable, or constantly called for by users. This will enable protocols like this:

protocol Animal {

    static var entityName: String = "Animal"
    var name: String = "Unknown"

    init(name: String) {
        self.name = name
    }
    
    func makeNoise() {
        print("bark")
    }
    
    static func doAThing() {
        print("I did a thing!")
    }
}

Looks an awful lot like a concrete Type...

Further, with current semantics, you cannot call Animal.doAThing() or Animal.entityName. If they have an implementation within the protocol, they look even more like they should be accessible.

It's right there! why can't I access it?

It's something some users already want and can be confused by. In that environment the case against it will be esoteric and unsatisfying, so I think it's likely protocols will have a static-accessible interface when a default implementation is available.

So in this world, the practical differences between a protocol and a class will more/less narrow to not being able to instantiate protocols directly, and structs/protocols not being able to adhere to classes.

In the environment I can even see the "right" way to do things being to write almost everything in protocols, and have classes/structs basically just be a definition of a group of protocols with almost no actual code, moving closer to a trait/mixin model.

While an interesting possibility (at to me), it's a very different norm from the way Swift is currently used and should be moved toward intentially. Not from wanting a convenient way to write default implementations.

I'm unsure of a better way to approach this specifically while leaving protocols alone. However given the desire for Abstract Classes and the Increasing usage of Type Erasure, I think the effort should go toward finding a solution that satisfies as many of the current pain points around protocols (including default implementations) as possible.

7 Likes