[swift-evolution] Proposal: Re-instate mandatory self for accessing instance properties and functions (David Hart)

Jeremy Pereira jeremy.j.pereira at googlemail.com
Thu Dec 17 03:54:46 CST 2015


> On 16 Dec 2015, at 17:20, James Dempsey via swift-evolution <swift-evolution at swift.org> wrote:
> 
>>> I think the mandatory self problem is analogous to never wanting to use x!, as! or try!. If you restrict yourself to always using self.whatever, it is not unusual to someone else, and if they leave off the compiler flag or pragma that enforces this, the code will still compile.
> 
> I think there is a fundamental difference between code that does / does not use x! as! or try! and code that may or may not require the use of self.
> 
> Even if you do not use x! as! or try! in your own code, you can easily read and understand code that does use those features.
> 
> But if you choose to enforce using self in your own code, suddenly you need to read and reason about code in two different ways.
> 
> In ‘mandatory self’ code, you can assume self is always being used and you cannot accidentally use something in local scope by mistake.  The ‘mandatory self’ removes a set of potential bugs you need to check for when reading code.  But when you encounter ’non enforced self’ code, you can’t make those assumptions and you need to check for those issues.

Well I always assume implicit self just as I did with Java, C++ and Objective-C (I don’t think I have ever seen any Objective-C code where the writer dutifully put "self->” in front of each ivar usage). 

I think the characterising the bugs you can see from using implicit self as “sneaky and hard to find” is incorrect. I have occasionally encountered shadowing bugs, but it usually takes me about 30 seconds to realise what has gone wrong. Retain cycles on the other hand...

> 
> Overall, I am +1 for the proposal of making self mandatory because I find the lack of 'mandatory self' makes the code less readable, less explicit as to intent and can also introduce subtle bugs.

Readability is usually a subjective issue. You find not having self as less readable, probably because your brain has learned to filter out all the “self”s. I find code with unnecessary “self”s in less readable because I think they are boilerplate that obscures the logic in most situations. Neither of those outlooks are right or wrong, it depends on what you are used to.

I think we have sort of lost sight of what we are trying to achieve with this proposal. The issue is local variables shadowing properties or global variables. The author of the proposal thinks that the best way to obviate this issue is to force his particular coding style on everybody. 

There are other ways to achieve the goal, for example Java has a warning that explicitly tells you when your local variable is shadowing an instance variable. Why wouldn’t that work? 


More information about the swift-evolution mailing list