Last active
January 8, 2016 12:02
-
-
Save dwineman/d6c56ec0c0e2fdb761db to your computer and use it in GitHub Desktop.
Swift allows you to call instance methods from other instance methods with no scope prefix, indistinguishably from function calls. This leads to the dangerous situation of function calls being shadowed when identically-named instance methods are added to a base class.
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
// Derived class contains an instance method that calls a function foo() in its scope. | |
class Base {} | |
func foo() -> String { | |
return "function foo()" | |
} | |
class Derived: Base { | |
func bar() -> String { | |
return foo() | |
} | |
} | |
var f = Derived() | |
f.bar() // returns "function foo()" | |
// But later, perhaps in a subsequent framework version or a class extension, the base class | |
// is updated by adding an instance method also called foo(). | |
// The behavior of the derived class now changes, because method foo() shadows function foo(): | |
class Base { | |
func foo() -> String { | |
return "method Base.foo()" | |
} | |
} | |
f.bar() // returns "method Base.foo()" | |
// Unfortunately, you can't opt out of the danger by choosing not to use this feature. Any | |
// function call in a class with one or more superclasses or extensions you don't control | |
// is at risk. |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
This is a very good example of the fragile code, but I don't agree that it should be solved by changing instance name semantics.
Note how the code currently pollutes module namespace with a global function foo(). That's never a good idea, so resolving this problem, either by creating a suitable name for a public function or by hiding the implementation detail inside the class, immediately solves the original one:
or
The only way to even have a chance of creating this problem is by using a pattern where private helper functions are used inside a short implementation file and are given some throwaway names.
Still, this is a useful pattern and there's no reason to stop using it; just note that those functions are technically globals and so their names should start with an uppercase letter according to every Swift style guide I read: