[swift-evolution] [Review] SE-0117: Default classes to be non-subclassable publicly

Károly Lőrentey karoly at lorentey.hu
Sat Jul 9 15:49:40 CDT 2016


> On 2016. Jul 9., at 18:04, Tino Heth via swift-evolution <swift-evolution at swift.org> wrote:
>> Of course it can be done either way.  But there are significant ecosystem robustness advantages to making sealed the default and comparatively few downsides.  Most libraries are open source (so can be modified directly or via PR if necessary)
> First:
> The claim about robustness sounds like a fact, despite being just an opinion (feel free to correct me if you have any evidence at all). We should stay honest with our predictions.

It has been standard advice in the Java community for at least 15 years to always prohibit external subclassing unless the class has been designed and documented to be safely subclassable, precisely because of the numerous problems that are caused by unforeseen subclassing.

> Second:
> Do you really believe there will be positive impact on open-source libraries?
> My forecast is that closed by default will dramatically increase trivial pull request where developers ask for unsealing so that they can do as they like… and I've no idea why somebody could come up with the idea that forking is desirable.

I may be unusually careful in my API design, but I don't see how opening a class to inheritance could ever be a trivial pull request. 

Enabling open subclassing involves the creation of customization hooks: a formal list of methods that subclasses are allowed to override to modify the behavior of the superclass. These methods need to be designed and their override requirements precisely documented. 

Inheritance breaks encapsulation, making the API contract a lot more complicated to describe, understand and verify. The public API becomes tainted with implementation details that were previously private: for example, the exact sequence of overridable methods called by each public function becomes de facto part of the public interface. Adding/reordering/removing calls to overridable methods can (and, if your package is popular and/or unlucky enough, will) break your clients.

Trying to write unit tests to verify a subclassing interface is an exercise in frustration; but unless you have adequate coverage, you can't really expect package maintainers not to accidentally break the subclassing contract in any future release.

Subclassing is an important tool in Swift's toolbox, but it takes considerable effort to prepare a class for inheritance. It is not OK to just slap on an "open" keyword and call it done; and it is unsafe to let it happen purely by accident.

Karoly
@lorentey


More information about the swift-evolution mailing list