[swift-evolution] Replace the override keyword by 'extend' and 'replace' or add an annotation like @SuppressSuperCall
Florian Liefers
florian at liefers.com
Wed Feb 17 03:23:24 CST 2016
Hi Recardo,
this will only work for calls inside the superclass, but for calls from outside the class you have no control. If one calls Foo().someMethod() directly, _someMethod is not executed.
— Florian
> Am 16.02.2016 um 23:43 schrieb Ricardo Parada <rparada at mac.com>:
>
> Hi Florian,
>
> I have always taken care of this problem in other languages without recurring to specialized language features. For example:
>
> class Foo {
> func _someMethod() {
> // Do something important
> …
>
> // Now give subclassers a chance to do something
> someMethod()
> }
>
> func someMethod() {
> // Default does nothing
> }
> }
>
> This way you are in control when someone else overrides someMethod since _someMethod() does the important stuff first and then calls someMethod() to allow those extending the class to do something.
>
> Also, I can modify _someMethod() and move the “Do something important” part to be after the call to someMethod().
>
>
>
>
>> On Feb 15, 2016, at 3:57 PM, Florian Liefers via swift-evolution <swift-evolution at swift.org> wrote:
>>
>> Hi!
>>
>> I would like to suggest to replace the override keyword for functions by something like extend and replace or to add an annotation like @SuppressSuperCall (don’t know a good name for it).
>> The reason for this is, that it might happen, that one forgets to call the super’s implementation in an overridden function or if one reads the code it might not be obvious why the super’s implementation is not called:
>>
>> class View {
>> func viewDidLoad() {
>> // does something
>> }
>> }
>>
>> class Button: View {
>> override func viewDidLoad() {
>> super.viewDidLoad() // <— this might be forgotten
>> // do something other
>> }
>> }
>>
>> The compiler will accept if one overrides a superclass’s function but does not call the superclass’s implementation which is often ok. The developer should clearly state that he doesn’t want to call the superclass’s implementation, otherwise the compiler should throw an error.
>>
>> // Example for extending a function
>> class Button: View {
>> extend func viewDidLoad() {
>> super.viewDidLoad()
>> // do something
>> }
>>
>> extend func viewDidAppear() {
>> // do something
>> } // <— the compiler should throw an error here.
>> }
>>
>> // Example for replacing a function
>> class Geometry {
>> func volume() -> Double {
>> return 0;
>> }
>> }
>>
>> class Cube: Geometry {
>> var length: Double = 0.0
>> replace func volume() -> Double {
>> let v = length * length * length
>> return v
>> }
>> }
>>
>> Cheers,
>> Florian
>> _______________________________________________
>> swift-evolution mailing list
>> swift-evolution at swift.org
>> https://lists.swift.org/mailman/listinfo/swift-evolution
>
More information about the swift-evolution
mailing list