[swift-evolution] Final by default for classes and methods
Matthew Johnson
matthew at anandabits.com
Mon Dec 7 21:18:43 CST 2015
> Defaults of public sealed/final classes and final methods on a class by default are a tougher call. Either way you may have design issues go unnoticed until someone needs to subclass to get the behavior they want. So when you reach that point, should the system error on the side of rigid safety or dangerous flexibility?
This is a nice summary of the tradeoff. I strongly prefer safety myself and I believe the preference for safety fits well with the overall direction of Swift. If a library author discovers a design oversight and later decides they should have allowed for additional flexibility it is straightforward to allow for this without breaking existing client code.
Many of the examples cited in argument against final by default have to do with working around library or framework bugs. I understand the motivation to preserve this flexibility bur don't believe bug workarounds are a good way to make language design decisions. I also believe use of subclasses and overrides in ways the library author may not have intended to is a fragile technique that is likely to eventually cause as many problems as it solves. I have been programming a long time and have never run into a case where this technique was the only way or even the best way to accomplish the task at hand.
One additional motivation for making final the default that has not been discussed yet is the drive towards making Swift a protocol oriented language. IMO protocols should be the first tool considered when dynamic polymorphism is necessary. Inheritance should be reserved for cases where other approaches won't work (and we should seek to reduce the number of problems where that is the case). Making final the default for classes and methods would provide a subtle (or maybe not so subtle) hint in this direction.
I know the Swift team at Apple put a lot of thought into the defaults in Swift. I agree with most of them. Enabling subclassing and overriding by default is the one case where I think a significant mistake was made.
Matthew
More information about the swift-evolution
mailing list