[swift-evolution] [Discussion] Enforcing Calling Super

Haravikk swift-evolution at haravikk.me
Thu Feb 25 16:02:46 CST 2016


> On 25 Feb 2016, at 15:47, Jeremy Pereira via swift-evolution <swift-evolution at swift.org> wrote:
> 
> In particular, it is absurd to enforce having the call to super as the first or last line of the method. That would stop me doing things like this:
> 
>    override func viewDidLoad()
>    {
>        print(“About to run super.viewDidLoad()”)
>        super.viewDidLoad()
>        print(“Finished super.viewDidLoad()”)
>    }
> 
> Then there’s the perfectly reasonable case like this:
> 
>    override func viewDidLoad()
>    {
>        functionThatCallsSuperViewDidLoad()
>    }
> 
> Why shouldn’t I be allowed to do that?

Because the parent class told you not to? I’ve said repeatedly on the subject now however that before/after constraints aren’t something that you should expect to see commonly, as they’re something that developers should only set if they are absolutely certain that they will be required. The way I see it they will be most commonly used in two particular cases:

Partial Implementation: For an abstract-style class, a provided partial implementation might only handle the preliminary setup or final handling of values, in which case it must be called first or last in order for an implementation to be completing it correctly.
Undefined State: If the parent class shares values and methods for sub-classes to use, but cannot guarantee a consistent state if they are called without the super method. Again this is really more likely to happen in types that are specifically intended for extension where order may be important, rather than a complete type that you just happen to decide to extend.

To reiterate, these should one of the less commonly used operations, and since the default is going to be to issue a warning then you aren’t prevented from doing anything.

It’s also possible that if the compiler can better detect “mutating” class methods then it would be possible for it to allow non-mutating code in front of a before condition, though could still potentially need to be warned against (in the undefined state you could be retrieving a value before it’s ready to be used). But once again, it’ll be a warning, so you can just ignore, and that’s assuming the condition is even being used, which shouldn’t be very common if it’s being used sensibly.
-------------- next part --------------
An HTML attachment was scrubbed...
URL: <https://lists.swift.org/pipermail/swift-evolution/attachments/20160225/2a351a5c/attachment.html>


More information about the swift-evolution mailing list