kodecocodes/swift-style-guide

Using of Self

sima-11 opened this issue · 5 comments

Hi there,

First of all, thanks for putting together a style guide for us to follow. Think it's great and very useful in many ways.

However, I myself am holding a point against whether to explicitly use self to refer a local variable or call a function. My point is that we should use it, because it can be clearer whether something sits within a class (locally) or not (globally, singletons, etc.) by just looking at its colour highlighting.

Although Swift support implicitly referring to self, it probably doesn't necessarily mean it would be best practice to do so?

My opinion: if you need self in order to see if something is local or an instance variable, then your method or your class is too big.

For me, recognizing that you have explicit self capture in closures is too valuable to hide with a style that uses self everywhere.

That said, this ship has already sailed for the RW style guide. It would take a major sea change in opinion to overturn it.

@hollance @rayfix
Thanks for the reply.

My thought is that when people join a team with a relatively large codebase, or review code others' code, explicitly use of self will make things much easier to follow, especially when people in the team have various levels of coding skills.

I personally can't see (or haven't seen) the value of having explicit self capture in closures. On the contrary, only explicitly use self in closures makes the coding style a bit inconsistent.

I agree with Apple's reasoning behind rejecting SE-0009 Require self for accessing instance members.

* Mandatory “self.” introduces a significant amount of verbosity that does not justify itself with added clarity. While it is true that mandatory “self.” may prevent a class of bugs, the cost of eliminating those bugs is fairly high in terms of visual clutter, which goes against the generally uncluttered feel of Swift. Paul Cantrell put it well in his review https://lists.swift.org/pipermail/swift-evolution/Week-of-Mon-20151214/002910.html when he said, “anything that is widely repeated becomes invisible.” Swift aims to avoid such boilerplate and repetition in its design, a principle also espoused by the Swift API Design Guidelines https://swift.org/documentation/api-design-guidelines.html.

It's better to try improving clarity by writing smaller methods and classes (as @hollance also hinted). The use of self in closures makes more sense to me because of weak/strong referencing of self.

Hey @RobertGummesson,

Thank you for adding the reference. I totally agree with what is mentioned, which expresses a more neutral perspective of whether or not to explicitly use self. and explained the pros/cons.

To me, the wording "avoid using self" is a bit too strong. As RayWenderlich has a such significant influence in the community, I think it would be more appropriate to explain the pros/cons in the style guide and let the developers decide by themselves.