Proposal: Re-instate mandatory self for accessing instance properties and functions

Jumping in here as a newbie to the list. :)

Having so many symbols like @ all over the place kept me from learning and using Ruby and Perl. It just felt wrong and artificial.
A language quickly becomes more difficult to learn, use and understand when much of the code consists of symbols.

I love Swift for having such a simple & clear structure and syntax in most cases. Adding symbols for every instance access on self (which is a very common case) would oppose these benefits and make its learning curve steeper.

I agree wholeheartedly. Adding additional symbols to the language will
likely confuse newcomers and will inevitably lead to bike-shedding
(“@“ versus “self”).

Moreover, as much of my daily work is in Python (in addition to Obj-C
and increasingly more Swift!), I have a very strong affinity for
explicit over implicit. The optional “self” struck me from day 1 of my
learnings of Swift as a nice feature for convenience’s sake, but also
a bit risky in that ambiguous scoping issues could be a problem.

obj1.prop1 = X
obj1.prop2 = Y
...
obj1.prop10 = Z
superview1.addSubview(obj1)

Adding “self.” everywhere adds a significant amount of visual noise; I've tried _property and self.property access styles in Objective-C, and find the former one to be noticeably more readable.

Python enforces the usage of “self” for all instance variables and
methods, and—perhaps I’m biased—but I have never felt that it was
visual noise. On the contrary, it’s presence generally made code
_less_ noisy and easier to read.

We are fortunate because the Python mailing list debated this exact
issue in 2006 (albeit, in the reverse direction). I’ll quote from
PEP 3099 – Things that will Not Change in Python 3000 | peps.python.org (“Things that will Not
Change in Python 3000”):

Having self be explicit is a good thing . It makes the code clear by removing ambiguity about how a variable resolves. It also makes the difference between functions and methods small.

From “Draft proposal: Implicit self in Python 3.0”,

http://mail.python.org/pipermail/python-dev/2006-January/059468.html

For any who are curious to read through the whole thread (there are
good arguments for and against in there):

[Python-Dev] Draft proposal: Implicit self in Python 3.0,
https://mail.python.org/pipermail/python-dev/2006-January/059446.html

Dan

···

On Mon, Dec 14, 2015 at 1:32 PM, Marc Knaup via swift-evolution <swift-evolution@swift.org> wrote:

On Mon, Dec 14, 2015 at 8:17 PM, Andrey Tarantsov via swift-evolution <swift-evolution@swift.org> wrote:

Having so many symbols like @ all over the place kept me from learning and
using Ruby and Perl. It just felt wrong and artificial.
A language quickly becomes more difficult to learn, use and understand when
much of the code consists of symbols.

I love Swift for having such a simple & clear structure and syntax in most
cases. Adding symbols for every instance access on self (which is a very
common case) would oppose these benefits and make its learning curve
steeper.

···

On Mon, Dec 14, 2015 at 8:17 PM, Andrey Tarantsov via swift-evolution < swift-evolution@swift.org> wrote:

I agree with Ilya here:

> but they make code editing easier at the expense of readability.
Disagree. This really depends on the example. E.g. which is more readable:

    var length: Double { return sqrt(dx*dx + dy*dy) }

    var length: Double { return sqrt(@dx*@dx + @dy*@dy) }

    var length: Double { return sqrt(self.dx*self.dx + self.dy*self.dy) }

I find that this holds true in larger classes as well (or even more). I
have tons of view controllers and views that do stuff like:

obj1.prop1 = X
obj1.prop2 = Y
...
obj1.prop10 = Z
superview1.addSubview(obj1)

Adding “self.” everywhere adds a significant amount of visual noise; I've
tried _property and self.property access styles in Objective-C, and find
the former one to be noticeably more readable.

To be fair, there *are* cases when it's not immediately clear if
something is a property or a variable. That's why you can still add an
explicit self. if you want. Some of those are also probably code smells.

A.

_______________________________________________
swift-evolution mailing list
swift-evolution@swift.org
https://lists.swift.org/mailman/listinfo/swift-evolution

We are fortunate because the Python mailing list debated this exact
issue in 2006 (albeit, in the reverse direction). I’ll quote from
PEP 3099 – Things that will Not Change in Python 3000 | peps.python.org (“Things that will Not
Change in Python 3000”):

Having self be explicit is a good thing . It makes the code clear by removing ambiguity about how a variable resolves. It also makes the difference between functions and methods small.

That’s very interesting.

We are fortunate because the Python mailing list debated this exact
issue in 2006 (albeit, in the reverse direction). I’ll quote from
PEP 3099 – Things that will Not Change in Python 3000 | peps.python.org (“Things that will Not
Change in Python 3000”):

Having self be explicit is a good thing . It makes the code clear by removing ambiguity about how a variable resolves. It also makes the difference between functions and methods small.

Theoretically, if we were debating this on principle, I would agree with explicit self references.

However, I talk from experience using the relevant Apple frameworks writing dozens of apps. The UI code, which is more than a half of a typical app's code, consists of lines upon lines of simple object setup and manipulation, where (1) it is absolutely clear which names are properties and which are variables; (2) in many cases, it doesn't matter anyway (like maybe that tableView is an argument and not your property, but still the same object); (3) the code is fairly verbose as it is, and adding any extra syntactic elements obscures its intention.

And, perhaps more importantly, Xcode uses a different color to highlight property names. There's no need for further textual differentiation there.

A.

-1 from me.

I’d much prefer a way of name spacing free functions so that they don’t pollute global scope. That would help to reduce the potential ambiguity with implicit self too.

···

On 13 Dec 2015, at 15:32, David Hart via swift-evolution <swift-evolution@swift.org> wrote:

For the record I would also like it if the "globals must start with an uppercase letter" rule were enforced by the compiler (well, not in the playground, those aren't true globals).

+1, in the same vein, global a should stand out :)

I'd find it horrible when global variables & functions would suddenly start
with an uppercase letter.
Right now the distinction is VERY clear: Types start uppercase, anything
else lowercase.
It should stay that way and the compiler should warn about violations there.
As mentioned earlier the IDE can easily help with the distinction between
global and non-global symbols anyway.

Enum cases are still a problem here since they are values but start
uppercase. But I'm working on a proposal which covers that too.

In any case that's an unrelated topic and should be discussed separately.

···

On Sun, Dec 13, 2015 at 4:32 PM, David Hart via swift-evolution < swift-evolution@swift.org> wrote:

For the record I would also like it if the "globals must start with an
uppercase letter" rule were enforced by the compiler (well, not in the
playground, those aren't true globals).

+1, in the same vein, global a should stand out :)

On 13 Dec 2015, at 11:35, ilya <ilya.nikokoshev@gmail.com> wrote:

> It might seem obvious in a small piece of code like yours, but it
becomes less so in a class several hundred of lines long.

I'll be happy to take a look at the specific examples and see if perhaps
self-dot access will be useful there.
But even if we disagree you're still able to use self-dot access in any
place where you feel this to be beneficial without any changes in the
language.

> Why use a style guide when the language can enforce rules to eliminate
the ambiguity?

Because each project's situation can be unique. For the same reason
there's no need to rush to add concurrency at the language level without
considering other possibilities first.

For the record I would also like it if the "globals must start with an
uppercase letter" rule were enforced by the compiler (well, not in the
playground, those aren't true globals).

It still looks to me that if we make compiler enforce that and the
"instance names must not start with an uppercase letter" rule this
eliminates the ambiguity discussed in this thread.

On Sun, Dec 13, 2015 at 13:12 David Hart <david@hartbit.com> wrote:

struct Vector {
    var dx: Double
    var dy: Double
    var length: Double { return sqrt(dx*dx + dy*dy) }
}

vs

struct Vector {
    var dx: Double
    var dy: Double
    var length: Double { return sqrt(@dx*@dx + @dy*@dy) }
}

struct Vector {
    var dx: Double
    var dy: Double
    var length: Double { return sqrt(self.dx*self.dx + self.dy*self.dy) }
}

I don't agree with you because when reading your first example, I have to
make a mental gymnastic to find out if the variables are local/global
variables or if they are instance properties. It might seem obvious in a
small piece of code like yours, but it becomes less so in a class several
hundred of lines long.

On 13 Dec 2015, at 10:48, ilya <ilya.nikokoshev@gmail.com> wrote:

> For me, readability has always been more important, as we spend most of
our time reading than writing code.
Agree.

> but they make code editing easier at the expense of readability.
Disagree. This really depends on the example. E.g. which is more readable:

struct Vector {
    var dx: Double
    var dy: Double
    var length: Double { return sqrt(dx*dx + dy*dy) }
}

vs

struct Vector {
    var dx: Double
    var dy: Double
    var length: Double { return sqrt(@dx*@dx + @dy*@dy) }
}

struct Vector {
    var dx: Double
    var dy: Double
    var length: Double { return sqrt(self.dx*self.dx + self.dy*self.dy) }
}

On Sun, Dec 13, 2015 at 12:40 PM, David Hart <david@hartbit.com> wrote:

Hi Ilya,

Why use a style guide when the language can enforce rules to eliminate
the ambiguity?

On the other hand, it allows a logical explanation of how you can take
code from global scope and put it into an instance scope

This helps implementing patterns like "take a long function and make it
into a struct with a bunch of small functions instead".

Both of your previous points make sense but they make code editing
easier at the expense of readability. For me, readability has always been
more important, as we spend most of our time reading than writing code.

That's why I suggest using .x and .f() to mark implicit self.

I agree that that would potentially add confusion to the grammar. I've
always liked the @ and @@ prefixes of Ruby for accessing instance and class
properties, but I agree that symbols like that would feel a bit foreign in
Swift.

David

On 13 Dec 2015, at 10:16, ilya via swift-evolution < >>> swift-evolution@swift.org> wrote:

> But implicit self is confusing in a lot of code

On the other hand, it allows a logical explanation of how you can take
code from global scope and put it into an instance scope:

let greeting = "Hello"
let name = "Michael"

func greet() {
    print("\(greeting), \(name)")
}

seemlessly becomes

class Greeter {

    let greeting = "Hello"
    let name = "Michael"

    func greet() {
        print("\(greeting), \(name)")
    }

}

> can (and does) lead to shadowing bugs,

There are simple strategies that help to minimize the amount of
shadowing, e.g.

- only expose the minimum necessary amount of names in any scope
- break functions into small part so that it's easy to see all the local
name declarations
- not use any globals, or at least name them in a visually different way
(UppercaseCamelStyle)
- name properties and locals in a different way (classProperty,
local_var)

Even without a formal code style, if you tend to make property names
longer and local names shorter, your risk of shadowing goes down.

> .x and .f() to mark implicit self. I realize that this may conflict
with enum usage.

This will lead to a lot of ambiguity:

func f() {
    let x = NSOperation()
    .name = "Name" // is it x.name or self.name??
   ...
}

> If so, then use another marker. For instance :x or ^x or anything.

This is workable, but still I think this is one of the best points of
Swift – the existence of instance scope where names are simply written
as-is. This helps implementing patterns like "take a long function and make
it into a struct with a bunch of small functions instead".

> is very difficult to reason about in diffs or any other interface that
isn't an IDE (especially code review)

This is the point where I entirely agree, good code should be easily
read in any context.
Again, may I suggest you take a look into using a style guide to
differentiate visually between local and instance scope?

Ilya

On Sun, Dec 13, 2015 at 10:15 AM, Rob Napier via swift-evolution < >>> swift-evolution@swift.org> wrote:

I wanted to reopen this discussion that seems to have trailed off.
Requesting the return of self was my very first ask of Swift if I remember
correctly (Apple Developer Forums). Continued
work in Swift has both strengthened and modified that ask. Here are several
of the examples discussed before:

https://gist.github.com/schwa/94b11dc0a7a331f46b25
Spooky action at a distance when you don't use self · GitHub
Even more shenanigans when self is not required · GitHub
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. · GitHub

I get that it seems tedious to type (and read) "self." and I get that
"self." is currently a hint that self might be captured (but doesn't
actually mean that, since you can use self. without capturing, and
sometimes have to, very often in init, so really it's basically meaningless
for that use).

That's why I suggest using .x and .f() to mark implicit self. I realize
that this may conflict with enum usage. If so, then use another marker. For
instance :x or ^x or anything. But implicit self is confusing in a lot of
code, can (and does) lead to shadowing bugs, and is very difficult to
reason about in diffs or any other interface that isn't an IDE (especially
code review).

Thoughts, David? I agree with your basic proposal; I just want to amend
it.

-Rob

_______________________________________________
swift-evolution mailing list
swift-evolution@swift.org
https://lists.swift.org/mailman/listinfo/swift-evolution

_______________________________________________
swift-evolution mailing list
swift-evolution@swift.org
https://lists.swift.org/mailman/listinfo/swift-evolution

_______________________________________________
swift-evolution mailing list
swift-evolution@swift.org
https://lists.swift.org/mailman/listinfo/swift-evolution

I agree that referring to symbols in self explicitly does improve clarity in a few cases. But that comes at a high cost where the whole code gets polluted by and hidden between a lot placements of the self keyword. For me the benefits of omitting self for decluttering outweighs the occasional benefit of improved clarity by far.

It comes at a cost; I think we just disagree on how costly it is. I've been doing it in my own code for ages, Objective-C enforces it, has been even more verbose, and it's Okay as far as I'm concerned.

Also the clarity can be improved easily by the IDE in this case. The IDE can present instance symbols and global symbols visually distinct which removes any remaining ambiguity. So in good IDEs the benefit of requiring an explicit self would even be practically zero.

What are you thinking about? If you are thinking about coloring, we've had a long discussion about it earlier in the mailing list and a majority came to the conclusion that that's not good enough: many of us are colorblind, or slightly visually impared, or work in an editor that doesn't provide correct color syntaxing.

···

On 13 Dec 2015, at 14:55, Marc Knaup <marc@knaup.koeln> wrote:

I also prefer to keep self. optional.

In the past I wrote a lot code in Java and decided that I want to consistently use "this." in my code whenever possible. Eclipse even automatically inserted it for me every time I saved the file so I usually didn't have to write it on my own. Over time I noticed that while it did slightly improve clarity in *some* cases my code started looking like it consists of plenty of this keywords with some actual logic spread in between.

Then Swift was released and I began migrating our Objective-C app to Swift. I noticed that the common approach was to refer to self implicitly whenever possible instead of writing it explicitly and I followed that approach. Now our team has built two large Swift apps which are even broken down into plenty of modules. It happened very very rarely that I had to look up whether a variable access or function call was referring to a local symbol or to one in self. Most of the time it was clear by context.

I liked the result so much that I started writing and converting Java-code the same way and now omit this whenever possible.

*Bottom line:*
I agree that referring to symbols in self explicitly does improve clarity in a few cases. But that comes at a high cost where the whole code gets polluted by and hidden between a lot placements of the self keyword. For me the benefits of omitting self for decluttering outweighs the occasional benefit of improved clarity by far.

Also the clarity can be improved easily by the IDE in this case. The IDE can present instance symbols and global symbols visually distinct which removes any remaining ambiguity. So in good IDEs the benefit of requiring an explicit self would even be practically zero.

PS: Also note that this discussion of implicitly vs. explicitly would have to also extend to various other occasions like global vs. local vs. nested type names and even type inference, where a variable's type might also be unclear occasionally unless the IDE supports you.

On Sun, Dec 13, 2015 at 11:35 AM, ilya via swift-evolution <swift-evolution@swift.org> wrote:
> It might seem obvious in a small piece of code like yours, but it becomes less so in a class several hundred of lines long.

I'll be happy to take a look at the specific examples and see if perhaps self-dot access will be useful there.
But even if we disagree you're still able to use self-dot access in any place where you feel this to be beneficial without any changes in the language.

> Why use a style guide when the language can enforce rules to eliminate the ambiguity?

Because each project's situation can be unique. For the same reason there's no need to rush to add concurrency at the language level without considering other possibilities first.

For the record I would also like it if the "globals must start with an uppercase letter" rule were enforced by the compiler (well, not in the playground, those aren't true globals).

It still looks to me that if we make compiler enforce that and the "instance names must not start with an uppercase letter" rule this eliminates the ambiguity discussed in this thread.

On Sun, Dec 13, 2015 at 13:12 David Hart <david@hartbit.com> wrote:

struct Vector {
    var dx: Double
    var dy: Double
    var length: Double { return sqrt(dx*dx + dy*dy) }
}

vs

struct Vector {
    var dx: Double
    var dy: Double
    var length: Double { return sqrt(@dx*@dx + @dy*@dy) }
}

struct Vector {
    var dx: Double
    var dy: Double
    var length: Double { return sqrt(self.dx*self.dx + self.dy*self.dy) }
}

I don't agree with you because when reading your first example, I have to make a mental gymnastic to find out if the variables are local/global variables or if they are instance properties. It might seem obvious in a small piece of code like yours, but it becomes less so in a class several hundred of lines long.

On 13 Dec 2015, at 10:48, ilya <ilya.nikokoshev@gmail.com> wrote:

> For me, readability has always been more important, as we spend most of our time reading than writing code.
Agree.

> but they make code editing easier at the expense of readability.
Disagree. This really depends on the example. E.g. which is more readable:

struct Vector {
    var dx: Double
    var dy: Double
    var length: Double { return sqrt(dx*dx + dy*dy) }
}

vs

struct Vector {
    var dx: Double
    var dy: Double
    var length: Double { return sqrt(@dx*@dx + @dy*@dy) }
}

struct Vector {
    var dx: Double
    var dy: Double
    var length: Double { return sqrt(self.dx*self.dx + self.dy*self.dy) }
}

On Sun, Dec 13, 2015 at 12:40 PM, David Hart <david@hartbit.com> wrote:
Hi Ilya,

Why use a style guide when the language can enforce rules to eliminate the ambiguity?

On the other hand, it allows a logical explanation of how you can take code from global scope and put it into an instance scope

This helps implementing patterns like "take a long function and make it into a struct with a bunch of small functions instead".

Both of your previous points make sense but they make code editing easier at the expense of readability. For me, readability has always been more important, as we spend most of our time reading than writing code.

That's why I suggest using .x and .f() to mark implicit self.

I agree that that would potentially add confusion to the grammar. I've always liked the @ and @@ prefixes of Ruby for accessing instance and class properties, but I agree that symbols like that would feel a bit foreign in Swift.

David

On 13 Dec 2015, at 10:16, ilya via swift-evolution <swift-evolution@swift.org> wrote:

> But implicit self is confusing in a lot of code

On the other hand, it allows a logical explanation of how you can take code from global scope and put it into an instance scope:

let greeting = "Hello"
let name = "Michael"

func greet() {
    print("\(greeting), \(name)")
}

seemlessly becomes

class Greeter {

    let greeting = "Hello"
    let name = "Michael"

    func greet() {
        print("\(greeting), \(name)")
    }

}

> can (and does) lead to shadowing bugs,

There are simple strategies that help to minimize the amount of shadowing, e.g.

- only expose the minimum necessary amount of names in any scope
- break functions into small part so that it's easy to see all the local name declarations
- not use any globals, or at least name them in a visually different way (UppercaseCamelStyle)
- name properties and locals in a different way (classProperty, local_var)

Even without a formal code style, if you tend to make property names longer and local names shorter, your risk of shadowing goes down.

> .x and .f() to mark implicit self. I realize that this may conflict with enum usage.

This will lead to a lot of ambiguity:

func f() {
    let x = NSOperation()
    .name = "Name" // is it x.name or self.name??
   ...
}

> If so, then use another marker. For instance :x or ^x or anything.

This is workable, but still I think this is one of the best points of Swift – the existence of instance scope where names are simply written as-is. This helps implementing patterns like "take a long function and make it into a struct with a bunch of small functions instead".

> is very difficult to reason about in diffs or any other interface that isn't an IDE (especially code review)

This is the point where I entirely agree, good code should be easily read in any context.
Again, may I suggest you take a look into using a style guide to differentiate visually between local and instance scope?

Ilya

On Sun, Dec 13, 2015 at 10:15 AM, Rob Napier via swift-evolution <swift-evolution@swift.org> wrote:
I wanted to reopen this discussion that seems to have trailed off. Requesting the return of self was my very first ask of Swift if I remember correctly (Apple Developer Forums). Continued work in Swift has both strengthened and modified that ask. Here are several of the examples discussed before:

https://gist.github.com/schwa/94b11dc0a7a331f46b25
Spooky action at a distance when you don't use self · GitHub
Even more shenanigans when self is not required · GitHub
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. · GitHub

I get that it seems tedious to type (and read) "self." and I get that "self." is currently a hint that self might be captured (but doesn't actually mean that, since you can use self. without capturing, and sometimes have to, very often in init, so really it's basically meaningless for that use).

That's why I suggest using .x and .f() to mark implicit self. I realize that this may conflict with enum usage. If so, then use another marker. For instance :x or ^x or anything. But implicit self is confusing in a lot of code, can (and does) lead to shadowing bugs, and is very difficult to reason about in diffs or any other interface that isn't an IDE (especially code review).

Thoughts, David? I agree with your basic proposal; I just want to amend it.

-Rob

_______________________________________________
swift-evolution mailing list
swift-evolution@swift.org
https://lists.swift.org/mailman/listinfo/swift-evolution

_______________________________________________
swift-evolution mailing list
swift-evolution@swift.org
https://lists.swift.org/mailman/listinfo/swift-evolution

_______________________________________________
swift-evolution mailing list
swift-evolution@swift.org
https://lists.swift.org/mailman/listinfo/swift-evolution

Oh, one more point: in the UI code I mentioned, I often switch between a property and a variable (e.g. turning a locally-declared label into a field if I find myself needing to update it elsewhere), and it would be very irksome to have to go and update all the references.

Also, how often do you actually encounter a bug caused by confusion between properties and variables? I had maybe two property/argument collisions and one property/local var collision that I had to debug in my 1.5 years of swifting. Compared to that, writing "self." would be an everyday annoyance.

A.

···

On Dec 15, 2015, at 3:54 AM, Andrey Tarantsov via swift-evolution <swift-evolution@swift.org> wrote:

We are fortunate because the Python mailing list debated this exact
issue in 2006 (albeit, in the reverse direction). I’ll quote from
PEP 3099 – Things that will Not Change in Python 3000 | peps.python.org (“Things that will Not
Change in Python 3000”):

Having self be explicit is a good thing . It makes the code clear by removing ambiguity about how a variable resolves. It also makes the difference between functions and methods small.

Theoretically, if we were debating this on principle, I would agree with explicit self references.

However, I talk from experience using the relevant Apple frameworks writing dozens of apps. The UI code, which is more than a half of a typical app's code, consists of lines upon lines of simple object setup and manipulation, where (1) it is absolutely clear which names are properties and which are variables; (2) in many cases, it doesn't matter anyway (like maybe that tableView is an argument and not your property, but still the same object); (3) the code is fairly verbose as it is, and adding any extra syntactic elements obscures its intention.

And, perhaps more importantly, Xcode uses a different color to highlight property names. There's no need for further textual differentiation there.

A.

_______________________________________________
swift-evolution mailing list
swift-evolution@swift.org
https://lists.swift.org/mailman/listinfo/swift-evolution

For reference there was another discussion where Swift developers suggested
that editors can solve a similar problem:
https://lists.swift.org/pipermail/swift-evolution/Week-of-Mon-20151207/002040.html

We indeed disagree on cost. Objective-C is a terribly verbose language. I
already avoided a lot of self references there by using ivars directly.

Editors have more options than just color to visually distinguish elements
esp. for colorblind people. It could for example be underlined, thickened
or annotated with a symbol. If the editor isn't good that doing that then
an issue should be opened for the editor instead instead of changing the
language imho.

···

On Sun, Dec 13, 2015 at 4:46 PM, David Hart <david@hartbit.com> wrote:

I agree that referring to symbols in self explicitly does improve clarity
in a few cases. But that comes at a high cost where the whole code gets
polluted by and hidden between a lot placements of the self keyword. For me
the benefits of omitting self for decluttering outweighs the occasional
benefit of improved clarity by far.

It comes at a cost; I think we just disagree on how costly it is. I've
been doing it in my own code for ages, Objective-C enforces it, has been
even more verbose, and it's Okay as far as I'm concerned.

Also the clarity can be improved easily by the IDE in this case. The IDE
can present instance symbols and global symbols visually distinct which
removes any remaining ambiguity. So in good IDEs the benefit of requiring
an explicit self would even be practically zero.

What are you thinking about? If you are thinking about coloring, we've had
a long discussion about it earlier in the mailing list and a majority came
to the conclusion that that's not good enough: many of us are colorblind,
or slightly visually impared, or work in an editor that doesn't provide
correct color syntaxing.

On 13 Dec 2015, at 14:55, Marc Knaup <marc@knaup.koeln> wrote:

I also prefer to keep self. optional.

In the past I wrote a lot code in Java and decided that I want to
consistently use "this." in my code whenever possible. Eclipse even
automatically inserted it for me every time I saved the file so I usually
didn't have to write it on my own. Over time I noticed that while it did
slightly improve clarity in *some* cases my code started looking like it
consists of plenty of this keywords with some actual logic spread in
between.

Then Swift was released and I began migrating our Objective-C app to
Swift. I noticed that the common approach was to refer to self implicitly
whenever possible instead of writing it explicitly and I followed that
approach. Now our team has built two large Swift apps which are even broken
down into plenty of modules. It happened very very rarely that I had to
look up whether a variable access or function call was referring to a local
symbol or to one in self. Most of the time it was clear by context.

I liked the result so much that I started writing and converting Java-code
the same way and now omit this whenever possible.

*Bottom line:*
I agree that referring to symbols in self explicitly does improve clarity
in a few cases. But that comes at a high cost where the whole code gets
polluted by and hidden between a lot placements of the self keyword. For
me the benefits of omitting self for decluttering outweighs the
occasional benefit of improved clarity by far.

Also the clarity can be improved easily by the IDE in this case. The IDE
can present instance symbols and global symbols visually distinct which
removes any remaining ambiguity. So in good IDEs the benefit of requiring
an explicit self would even be practically zero.

PS: Also note that this discussion of implicitly vs. explicitly would have
to also extend to various other occasions like global vs. local vs. nested
type names and even type inference, where a variable's type might also be
unclear occasionally unless the IDE supports you.

On Sun, Dec 13, 2015 at 11:35 AM, ilya via swift-evolution < > swift-evolution@swift.org> wrote:

> It might seem obvious in a small piece of code like yours, but it
becomes less so in a class several hundred of lines long.

I'll be happy to take a look at the specific examples and see if perhaps
self-dot access will be useful there.
But even if we disagree you're still able to use self-dot access in any
place where you feel this to be beneficial without any changes in the
language.

> Why use a style guide when the language can enforce rules to eliminate
the ambiguity?

Because each project's situation can be unique. For the same reason
there's no need to rush to add concurrency at the language level without
considering other possibilities first.

For the record I would also like it if the "globals must start with an
uppercase letter" rule were enforced by the compiler (well, not in the
playground, those aren't true globals).

It still looks to me that if we make compiler enforce that and the
"instance names must not start with an uppercase letter" rule this
eliminates the ambiguity discussed in this thread.

On Sun, Dec 13, 2015 at 13:12 David Hart <david@hartbit.com> wrote:

struct Vector {
    var dx: Double
    var dy: Double
    var length: Double { return sqrt(dx*dx + dy*dy) }
}

vs

struct Vector {
    var dx: Double
    var dy: Double
    var length: Double { return sqrt(@dx*@dx + @dy*@dy) }
}

struct Vector {
    var dx: Double
    var dy: Double
    var length: Double { return sqrt(self.dx*self.dx + self.dy*self.dy) }
}

I don't agree with you because when reading your first example, I have
to make a mental gymnastic to find out if the variables are local/global
variables or if they are instance properties. It might seem obvious in a
small piece of code like yours, but it becomes less so in a class several
hundred of lines long.

On 13 Dec 2015, at 10:48, ilya <ilya.nikokoshev@gmail.com> wrote:

> For me, readability has always been more important, as we spend most
of our time reading than writing code.
Agree.

> but they make code editing easier at the expense of readability.
Disagree. This really depends on the example. E.g. which is more
readable:

struct Vector {
    var dx: Double
    var dy: Double
    var length: Double { return sqrt(dx*dx + dy*dy) }
}

vs

struct Vector {
    var dx: Double
    var dy: Double
    var length: Double { return sqrt(@dx*@dx + @dy*@dy) }
}

struct Vector {
    var dx: Double
    var dy: Double
    var length: Double { return sqrt(self.dx*self.dx + self.dy*self.dy) }
}

On Sun, Dec 13, 2015 at 12:40 PM, David Hart <david@hartbit.com> wrote:

Hi Ilya,

Why use a style guide when the language can enforce rules to eliminate
the ambiguity?

On the other hand, it allows a logical explanation of how you can take
code from global scope and put it into an instance scope

This helps implementing patterns like "take a long function and make it
into a struct with a bunch of small functions instead".

Both of your previous points make sense but they make code editing
easier at the expense of readability. For me, readability has always been
more important, as we spend most of our time reading than writing code.

That's why I suggest using .x and .f() to mark implicit self.

I agree that that would potentially add confusion to the grammar. I've
always liked the @ and @@ prefixes of Ruby for accessing instance and class
properties, but I agree that symbols like that would feel a bit foreign in
Swift.

David

On 13 Dec 2015, at 10:16, ilya via swift-evolution < >>>> swift-evolution@swift.org> wrote:

> But implicit self is confusing in a lot of code

On the other hand, it allows a logical explanation of how you can take
code from global scope and put it into an instance scope:

let greeting = "Hello"
let name = "Michael"

func greet() {
    print("\(greeting), \(name)")
}

seemlessly becomes

class Greeter {

    let greeting = "Hello"
    let name = "Michael"

    func greet() {
        print("\(greeting), \(name)")
    }

}

> can (and does) lead to shadowing bugs,

There are simple strategies that help to minimize the amount of
shadowing, e.g.

- only expose the minimum necessary amount of names in any scope
- break functions into small part so that it's easy to see all the
local name declarations
- not use any globals, or at least name them in a visually different
way (UppercaseCamelStyle)
- name properties and locals in a different way (classProperty,
local_var)

Even without a formal code style, if you tend to make property names
longer and local names shorter, your risk of shadowing goes down.

> .x and .f() to mark implicit self. I realize that this may conflict
with enum usage.

This will lead to a lot of ambiguity:

func f() {
    let x = NSOperation()
    .name = "Name" // is it x.name or self.name??
   ...
}

> If so, then use another marker. For instance :x or ^x or anything.

This is workable, but still I think this is one of the best points of
Swift – the existence of instance scope where names are simply written
as-is. This helps implementing patterns like "take a long function and make
it into a struct with a bunch of small functions instead".

> is very difficult to reason about in diffs or any other interface
that isn't an IDE (especially code review)

This is the point where I entirely agree, good code should be easily
read in any context.
Again, may I suggest you take a look into using a style guide to
differentiate visually between local and instance scope?

Ilya

On Sun, Dec 13, 2015 at 10:15 AM, Rob Napier via swift-evolution < >>>> swift-evolution@swift.org> wrote:

I wanted to reopen this discussion that seems to have trailed off.
Requesting the return of self was my very first ask of Swift if I remember
correctly (Apple Developer Forums). Continued
work in Swift has both strengthened and modified that ask. Here are several
of the examples discussed before:

https://gist.github.com/schwa/94b11dc0a7a331f46b25
Spooky action at a distance when you don't use self · GitHub
Even more shenanigans when self is not required · GitHub
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. · GitHub

I get that it seems tedious to type (and read) "self." and I get that
"self." is currently a hint that self might be captured (but doesn't
actually mean that, since you can use self. without capturing, and
sometimes have to, very often in init, so really it's basically meaningless
for that use).

That's why I suggest using .x and .f() to mark implicit self. I
realize that this may conflict with enum usage. If so, then use another
marker. For instance :x or ^x or anything. But implicit self is confusing
in a lot of code, can (and does) lead to shadowing bugs, and is very
difficult to reason about in diffs or any other interface that isn't an IDE
(especially code review).

Thoughts, David? I agree with your basic proposal; I just want to
amend it.

-Rob

_______________________________________________
swift-evolution mailing list
swift-evolution@swift.org
https://lists.swift.org/mailman/listinfo/swift-evolution

_______________________________________________
swift-evolution mailing list
swift-evolution@swift.org
https://lists.swift.org/mailman/listinfo/swift-evolution

_______________________________________________
swift-evolution mailing list
swift-evolution@swift.org
https://lists.swift.org/mailman/listinfo/swift-evolution

I'd find it horrible when global variables & functions would suddenly

start with an uppercase letter.

Uhm, that's part of the style guide for existing C- and
Objective-C-functions, and by extension in current Swift apps, that target
iOS.

They are of course ugly, and the best way to get rid of those is to move
gradually all of the free functions and constants into types. And then
those names will be accessible via the UpperCaseType.lowerCaseSomething
convention. Hopefully Apple does that to the system framworks as well:

CGContextRef UIGraphicsGetCurrentContext() -> CGContext.currentContext

etc.

···

On Sun, Dec 13, 2015 at 6:38 PM, Marc Knaup <marc@knaup.koeln> wrote:

I'd find it horrible when global variables & functions would suddenly
start with an uppercase letter.
Right now the distinction is VERY clear: Types start uppercase, anything
else lowercase.
It should stay that way and the compiler should warn about violations
there.
As mentioned earlier the IDE can easily help with the distinction between
global and non-global symbols anyway.

Enum cases are still a problem here since they are values but start
uppercase. But I'm working on a proposal which covers that too.

In any case that's an unrelated topic and should be discussed separately.

On Sun, Dec 13, 2015 at 4:32 PM, David Hart via swift-evolution < > swift-evolution@swift.org> wrote:

For the record I would also like it if the "globals must start with an
uppercase letter" rule were enforced by the compiler (well, not in the
playground, those aren't true globals).

+1, in the same vein, global a should stand out :)

On 13 Dec 2015, at 11:35, ilya <ilya.nikokoshev@gmail.com> wrote:

> It might seem obvious in a small piece of code like yours, but it
becomes less so in a class several hundred of lines long.

I'll be happy to take a look at the specific examples and see if perhaps
self-dot access will be useful there.
But even if we disagree you're still able to use self-dot access in any
place where you feel this to be beneficial without any changes in the
language.

> Why use a style guide when the language can enforce rules to eliminate
the ambiguity?

Because each project's situation can be unique. For the same reason
there's no need to rush to add concurrency at the language level without
considering other possibilities first.

For the record I would also like it if the "globals must start with an
uppercase letter" rule were enforced by the compiler (well, not in the
playground, those aren't true globals).

It still looks to me that if we make compiler enforce that and the
"instance names must not start with an uppercase letter" rule this
eliminates the ambiguity discussed in this thread.

On Sun, Dec 13, 2015 at 13:12 David Hart <david@hartbit.com> wrote:

struct Vector {
    var dx: Double
    var dy: Double
    var length: Double { return sqrt(dx*dx + dy*dy) }
}

vs

struct Vector {
    var dx: Double
    var dy: Double
    var length: Double { return sqrt(@dx*@dx + @dy*@dy) }
}

struct Vector {
    var dx: Double
    var dy: Double
    var length: Double { return sqrt(self.dx*self.dx + self.dy*self.dy) }
}

I don't agree with you because when reading your first example, I have
to make a mental gymnastic to find out if the variables are local/global
variables or if they are instance properties. It might seem obvious in a
small piece of code like yours, but it becomes less so in a class several
hundred of lines long.

On 13 Dec 2015, at 10:48, ilya <ilya.nikokoshev@gmail.com> wrote:

> For me, readability has always been more important, as we spend most
of our time reading than writing code.
Agree.

> but they make code editing easier at the expense of readability.
Disagree. This really depends on the example. E.g. which is more
readable:

struct Vector {
    var dx: Double
    var dy: Double
    var length: Double { return sqrt(dx*dx + dy*dy) }
}

vs

struct Vector {
    var dx: Double
    var dy: Double
    var length: Double { return sqrt(@dx*@dx + @dy*@dy) }
}

struct Vector {
    var dx: Double
    var dy: Double
    var length: Double { return sqrt(self.dx*self.dx + self.dy*self.dy) }
}

On Sun, Dec 13, 2015 at 12:40 PM, David Hart <david@hartbit.com> wrote:

Hi Ilya,

Why use a style guide when the language can enforce rules to eliminate
the ambiguity?

On the other hand, it allows a logical explanation of how you can take
code from global scope and put it into an instance scope

This helps implementing patterns like "take a long function and make it
into a struct with a bunch of small functions instead".

Both of your previous points make sense but they make code editing
easier at the expense of readability. For me, readability has always been
more important, as we spend most of our time reading than writing code.

That's why I suggest using .x and .f() to mark implicit self.

I agree that that would potentially add confusion to the grammar. I've
always liked the @ and @@ prefixes of Ruby for accessing instance and class
properties, but I agree that symbols like that would feel a bit foreign in
Swift.

David

On 13 Dec 2015, at 10:16, ilya via swift-evolution < >>>> swift-evolution@swift.org> wrote:

> But implicit self is confusing in a lot of code

On the other hand, it allows a logical explanation of how you can take
code from global scope and put it into an instance scope:

let greeting = "Hello"
let name = "Michael"

func greet() {
    print("\(greeting), \(name)")
}

seemlessly becomes

class Greeter {

    let greeting = "Hello"
    let name = "Michael"

    func greet() {
        print("\(greeting), \(name)")
    }

}

> can (and does) lead to shadowing bugs,

There are simple strategies that help to minimize the amount of
shadowing, e.g.

- only expose the minimum necessary amount of names in any scope
- break functions into small part so that it's easy to see all the
local name declarations
- not use any globals, or at least name them in a visually different
way (UppercaseCamelStyle)
- name properties and locals in a different way (classProperty,
local_var)

Even without a formal code style, if you tend to make property names
longer and local names shorter, your risk of shadowing goes down.

> .x and .f() to mark implicit self. I realize that this may conflict
with enum usage.

This will lead to a lot of ambiguity:

func f() {
    let x = NSOperation()
    .name = "Name" // is it x.name or self.name??
   ...
}

> If so, then use another marker. For instance :x or ^x or anything.

This is workable, but still I think this is one of the best points of
Swift – the existence of instance scope where names are simply written
as-is. This helps implementing patterns like "take a long function and make
it into a struct with a bunch of small functions instead".

> is very difficult to reason about in diffs or any other interface
that isn't an IDE (especially code review)

This is the point where I entirely agree, good code should be easily
read in any context.
Again, may I suggest you take a look into using a style guide to
differentiate visually between local and instance scope?

Ilya

On Sun, Dec 13, 2015 at 10:15 AM, Rob Napier via swift-evolution < >>>> swift-evolution@swift.org> wrote:

I wanted to reopen this discussion that seems to have trailed off.
Requesting the return of self was my very first ask of Swift if I remember
correctly (Apple Developer Forums). Continued
work in Swift has both strengthened and modified that ask. Here are several
of the examples discussed before:

https://gist.github.com/schwa/94b11dc0a7a331f46b25
Spooky action at a distance when you don't use self · GitHub
Even more shenanigans when self is not required · GitHub
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. · GitHub

I get that it seems tedious to type (and read) "self." and I get that
"self." is currently a hint that self might be captured (but doesn't
actually mean that, since you can use self. without capturing, and
sometimes have to, very often in init, so really it's basically meaningless
for that use).

That's why I suggest using .x and .f() to mark implicit self. I
realize that this may conflict with enum usage. If so, then use another
marker. For instance :x or ^x or anything. But implicit self is confusing
in a lot of code, can (and does) lead to shadowing bugs, and is very
difficult to reason about in diffs or any other interface that isn't an IDE
(especially code review).

Thoughts, David? I agree with your basic proposal; I just want to
amend it.

-Rob

_______________________________________________
swift-evolution mailing list
swift-evolution@swift.org
https://lists.swift.org/mailman/listinfo/swift-evolution

_______________________________________________
swift-evolution mailing list
swift-evolution@swift.org
https://lists.swift.org/mailman/listinfo/swift-evolution

_______________________________________________
swift-evolution mailing list
swift-evolution@swift.org
https://lists.swift.org/mailman/listinfo/swift-evolution

Swift.print() is a good example vs NSView's print()

I like things the way they are, and would rather use code highlights, linting tools, and in-house style standards rather than remove implicit self. That said, I could argue both sides.

-- E

···

On Dec 14, 2015, at 4:05 PM, Stephen Celis via swift-evolution <swift-evolution@swift.org> wrote:

On Mon, Dec 14, 2015 at 5:35 PM, Dan Loewenherz via swift-evolution <swift-evolution@swift.org <mailto:swift-evolution@swift.org>> wrote:

2. How can one reference a function with the same name as an instance
method in the class from which you’re referencing from? E.g., in the above
example, I believe that the “add” function is unreachable from within the class
(please correct me if I’m wrong).

FWIW, I like implicit self but have been bit by this several times before. You can use the current module's name to reference the free function, but the error messaging you'll face beforehand doesn't make it easy to get to that solution.

Stephen
_______________________________________________
swift-evolution mailing list
swift-evolution@swift.org
https://lists.swift.org/mailman/listinfo/swift-evolution

Oh, one more point: in the UI code I mentioned, I often switch between a property and a variable (e.g. turning a locally-declared label into a field if I find myself needing to update it elsewhere), and it would be very irksome to have to go and update all the references.

Also, how often do you actually encounter a bug caused by confusion between properties and variables? I had maybe two property/argument collisions and one property/local var collision that I had to debug in my 1.5 years of swifting. Compared to that, writing “self.” would be an everyday annoyance.

The difference is that one of the options puts the onus of
“correctness” on the developer, and the other puts it on the compiler.
As infallible as I might be, I prefer to think less about this sort of
thing and let the compiler do it for me. I guess I don’t see writing
“self.” as an annoyance since I’m very much used to it in Objective-C.

I think it’s a matter of habit. Personally, I think reading code and
having to decide which scope every reference refers to is a similar
cognitive annoyance (which I’ve attempted to reduce in my own
codebases by adopting the explicit style), whereas if I know “self.”
is the *only* way to reference an instance property or function, then
there’s no ambiguity and my brain can rest easy.

Re: hard to track to bugs, a somewhat contrived example follows (but
based in reality as many methods might hypothetically re-use the name
of an out-of-scope function for more specific behavior):

    func add(a: Int, b: Int) -> Int {
        return a + b
    }

    class Add {
        func add(a: Int, b: Int) -> Int {
            return a + b + 1
        }

        func aPlusB(a: Int, b: Int) → Int {
            return add(a, b: b);
        }
    }

1. Without trying this out in a playground, how many Swift users could
be expected to know—unambiguously—the output of “aPlusB(1, 1)”?
2. How can one reference a function with the same name as an instance
method in the class from which you’re referencing from? E.g., in the above
example, I believe that the “add” function is unreachable from within the class
(please correct me if I’m wrong).

> However, I talk from experience using the relevant Apple frameworks writing dozens of apps. The UI code, which is more than a half of a typical app’s code, consists of lines upon lines of simple object setup and manipulation, where (1) it is absolutely clear which names are properties and which are variables; (2) in many cases, it doesn't matter anyway (like maybe that tableView is an argument and not your property, but still the same object); (3) the code is fairly verbose as it is, and adding any extra syntactic elements obscures its intention.

Like you, I have shipped dozens of apps. But mostly all (save for 2
which are currently in development) are written in Objective-C, which
forces an explicit self when referencing properties. Coming from that,
I’ve found the lack of it in Swift often causes me to re-read my code
more times than I should when trying to reason about what variable is
being referenced and which is not (especially in initializers).

I’ve also always been in the “always use properties over instance
variables” camp in Objective-C (e.g., self.tableView > _tableView), so
that, combined with my Python experience, no doubt colors my opinions
here. :)

···

On Mon, Dec 14, 2015 at 3:59 PM, Andrey Tarantsov <andrey@tarantsov.com> wrote:

> On Dec 15, 2015, at 3:54 AM, Andrey Tarantsov via swift-evolution <swift-evolution@swift.org> wrote:
> And, perhaps more importantly, Xcode uses a different color to highlight property names. There’s no need for further textual differentiation there.

Very true. However, Xcode is just one of many environments in which
Swift is used. While I use Xcode all the time, I don’t think a core
language decision should be guided by its syntax highlighting
implementation (i.e., the IDE should adjust to fit the language, not
the other way around).

Dan

FWIW, I like implicit self but have been bit by this several times before.
You can use the current module's name to reference the free function, but
the error messaging you'll face beforehand doesn't make it easy to get to
that solution.

Stephen

···

On Mon, Dec 14, 2015 at 5:35 PM, Dan Loewenherz via swift-evolution < swift-evolution@swift.org> wrote:

2. How can one reference a function with the same name as an instance
method in the class from which you’re referencing from? E.g., in the above
example, I believe that the “add” function is unreachable from within the
class
(please correct me if I’m wrong).

(2) in many cases, it doesn't matter anyway (like maybe that tableView is an argument and not your property, but still the same object);

That’s actually a very good example.

Most of the time, your UIViewController or UITableViewController’s self.tableView is the same object as UITableViewDelegate’s tableView method argument. But I’ve had several cases in my app development career where that UIViewController was also used for updating a different tableView (for example a tableView used for search) which uses the same delegate, but where it is paramount to use the argument variable and not the instance variable.

I’ve actually had a bug due to that where code review was very quick because cellForRowAtIndexPath was using self.tableView instead of tableView and we saw it straight away.

(3) the code is fairly verbose as it is, and adding any extra syntactic elements obscures its intention.

Like many before, I think this is a question of taste. In our team, we don’t find it particularly verbose and we actually think it clarifies intention.

And, perhaps more importantly, Xcode uses a different color to highlight property names. There's no need for further textual differentiation there.

Like already said early in the discussion: some code review tools don’t show good enough color syntaxing, and even when in Xcode, I (and several others) are colourblind enough not to see the difference in those colours.

David.

···

On 14 Dec 2015, at 22:59, Andrey Tarantsov via swift-evolution <swift-evolution@swift.org> wrote:

Oh, one more point: in the UI code I mentioned, I often switch between a property and a variable (e.g. turning a locally-declared label into a field if I find myself needing to update it elsewhere), and it would be very irksome to have to go and update all the references.

Also, how often do you actually encounter a bug caused by confusion between properties and variables? I had maybe two property/argument collisions and one property/local var collision that I had to debug in my 1.5 years of swifting. Compared to that, writing "self." would be an everyday annoyance.

A.

On Dec 15, 2015, at 3:54 AM, Andrey Tarantsov via swift-evolution <swift-evolution@swift.org> wrote:

We are fortunate because the Python mailing list debated this exact
issue in 2006 (albeit, in the reverse direction). I’ll quote from
PEP 3099 – Things that will Not Change in Python 3000 | peps.python.org (“Things that will Not
Change in Python 3000”):

Having self be explicit is a good thing . It makes the code clear by removing ambiguity about how a variable resolves. It also makes the difference between functions and methods small.

Theoretically, if we were debating this on principle, I would agree with explicit self references.

However, I talk from experience using the relevant Apple frameworks writing dozens of apps. The UI code, which is more than a half of a typical app's code, consists of lines upon lines of simple object setup and manipulation, where (1) it is absolutely clear which names are properties and which are variables; (2) in many cases, it doesn't matter anyway (like maybe that tableView is an argument and not your property, but still the same object); (3) the code is fairly verbose as it is, and adding any extra syntactic elements obscures its intention.

And, perhaps more importantly, Xcode uses a different color to highlight property names. There's no need for further textual differentiation there.

A.

_______________________________________________
swift-evolution mailing list
swift-evolution@swift.org
https://lists.swift.org/mailman/listinfo/swift-evolution

_______________________________________________
swift-evolution mailing list
swift-evolution@swift.org
https://lists.swift.org/mailman/listinfo/swift-evolution

My two cents: I don't think that "there will be more work for the
programmer" is necessarily a reason to not implement a feature. Granted, we
don't want to end up like Java 7 where I dreaded doing some things that
would be dead simple in Swift--but Swift already has a lot of
expressiveness and conciseness built in. Explicit self won't kill
that. Mandatory
'self' for ivar and method access brings a tiny bit of programmer overhead
(honestly, . is the easiest key to hit. You do it all the time, both in
plain english and in code) and prevents some issues that will nag at you
and waste days.

Java is almost hellish when it comes to conciseness but you don't hear
anyone saying "at least we have implicit 'this'!"

I'm sure there were people presenting that exact argument when
optionals/enforced nullability was first introduced into other languages:
"Ugh, now I have to null-check everything? What a pain!"

Although I am a strong believer in the programmer-facing aspects of a
language needing to be good, I think that this decision should come down to
the relative long-term pros/cons: use for refactoring, protecting against
mistakes, etc. One thing that programmers are notoriously bad at doing is
overcoming the immediate want to put less effort toward something, in order
to accept something that will be useful long-term. That is why so many
people don't unit test: can't see past the upfront cost to create
maintainability.

I accept that people will continue to say "I can't be bothered to type
'self.'", but I just wanted to get this out there. It's really not that big
a deal--unless you're talking about readability rather than five keystrokes
on a method access. Keystrokes aren't the bottleneck in effective
programming.

···

On Mon, Dec 14, 2015 at 6:05 PM Stephen Celis via swift-evolution < swift-evolution@swift.org> wrote:

On Mon, Dec 14, 2015 at 5:35 PM, Dan Loewenherz via swift-evolution < > swift-evolution@swift.org> wrote:

2. How can one reference a function with the same name as an instance
method in the class from which you’re referencing from? E.g., in the above
example, I believe that the “add” function is unreachable from within the
class
(please correct me if I’m wrong).

FWIW, I like implicit self but have been bit by this several times before.
You can use the current module's name to reference the free function, but
the error messaging you'll face beforehand doesn't make it easy to get to
that solution.

Stephen
_______________________________________________
swift-evolution mailing list
swift-evolution@swift.org
https://lists.swift.org/mailman/listinfo/swift-evolution

Most of the time, your UIViewController or UITableViewController’s self.tableView is the same object as UITableViewDelegate’s tableView method argument. But I’ve had several cases in my app development career where that UIViewController was also used for updating a different tableView (for example a tableView used for search) which uses the same delegate, but where it is paramount to use the argument variable and not the instance variable.

I’ve actually had a bug due to that where code review was very quick because cellForRowAtIndexPath was using self.tableView instead of tableView and we saw it straight away.

Like I've mentioned, I also had a couple bugs like that, but I'll take that bug rate over the day-to-day requirement to use self.

(3) the code is fairly verbose as it is, and adding any extra syntactic elements obscures its intention.

Like many before, I think this is a question of taste. In our team, we don’t find it particularly verbose and we actually think it clarifies intention.

I guess you can get used to it? To me, self-access to properties in Objective-C is super-obtrusive, and I've been preferring fields for everything.

Now, I've expressed my opinion, and I have no idea how to resolve an issue that basically boils down to one's taste (I don't buy the extra-bug-a-year being a compelling argument), so I'll let you guys continue with the discussion. :-)

A.

Personally, I am against using mandatory self. I have coded a lot of Python, and I find it quite annoying to have to type (and read) “self.” everywhere. It’s a balance, of course:

“self.” everywhere means you can see what’s an instance member and what’s a local variable. That’s generally a good thing. But it also means a lot of filler text in your code, which makes reading and writing slower. That’s not so good. It’s a balance, and in this case my experience from C# (and, as mentioned, Python) is that I much prefer C#’s non-mandatory use of “this”/“self".

I see that this proposal is going to be reviewed as SE-0009, and I am a bit concerned that not all arguments are being considered because of the contents of the proposal text: The only counter argument mentioned in the proposal has to do with capturing semantics in closures. This is fine, but why isn’t the counter argument of verbosity being mentioned? This has been brought up on the list as well.

Also, the “Community Responses” section exclusively lists positive feedback. Is that how it’s supposed to be with the SE process? If not, where are the arguments from people who are -1 on the proposal?

I really hope the review team considers:
- The negative responses on this list as well. Also consider that many Swift developers are not on this list; I doubt it’s representative, either, being dominated by “language interested” developers.
- The rather large amount of changes to existing code required.

-Sune

I don't think (Objective-)C styling guides apply to Swift and they
shouldn't.

It's true a lot of existing MacOS/iOS API is using uppercase for global
functions but that's mostly because there weren't many different options at
that time and in that language. They will likely be improved or replaced
over time.

https://developer.apple.com/library/mac/documentation/Swift/Reference/Swift_StandardLibrary_Functions/index.html
I won't like to see all these global functions start uppercase instead.

Btw your example should read UIGraphics.currentContext instead. It's part
of UIKit, not Core Graphics.
But yes, that's the best way to fix it instead of relying on uppercase
letters.
The global namespace should have as little functions and variables as
possible anyway.

···

On Sun, Dec 13, 2015 at 4:51 PM, ilya <ilya.nikokoshev@gmail.com> wrote:

> I'd find it horrible when global variables & functions would suddenly
start with an uppercase letter.

Uhm, that's part of the style guide for existing C- and
Objective-C-functions, and by extension in current Swift apps, that target
iOS.

They are of course ugly, and the best way to get rid of those is to move
gradually all of the free functions and constants into types. And then
those names will be accessible via the UpperCaseType.lowerCaseSomething
convention. Hopefully Apple does that to the system framworks as well:

CGContextRef UIGraphicsGetCurrentContext() -> CGContext.currentContext

etc.

On Sun, Dec 13, 2015 at 6:38 PM, Marc Knaup <marc@knaup.koeln> wrote:

I'd find it horrible when global variables & functions would suddenly
start with an uppercase letter.
Right now the distinction is VERY clear: Types start uppercase, anything
else lowercase.
It should stay that way and the compiler should warn about violations
there.
As mentioned earlier the IDE can easily help with the distinction between
global and non-global symbols anyway.

Enum cases are still a problem here since they are values but start
uppercase. But I'm working on a proposal which covers that too.

In any case that's an unrelated topic and should be discussed separately.

On Sun, Dec 13, 2015 at 4:32 PM, David Hart via swift-evolution < >> swift-evolution@swift.org> wrote:

For the record I would also like it if the "globals must start with an
uppercase letter" rule were enforced by the compiler (well, not in the
playground, those aren't true globals).

+1, in the same vein, global a should stand out :)

On 13 Dec 2015, at 11:35, ilya <ilya.nikokoshev@gmail.com> wrote:

> It might seem obvious in a small piece of code like yours, but it
becomes less so in a class several hundred of lines long.

I'll be happy to take a look at the specific examples and see if perhaps
self-dot access will be useful there.
But even if we disagree you're still able to use self-dot access in any
place where you feel this to be beneficial without any changes in the
language.

> Why use a style guide when the language can enforce rules to eliminate
the ambiguity?

Because each project's situation can be unique. For the same reason
there's no need to rush to add concurrency at the language level without
considering other possibilities first.

For the record I would also like it if the "globals must start with an
uppercase letter" rule were enforced by the compiler (well, not in the
playground, those aren't true globals).

It still looks to me that if we make compiler enforce that and the
"instance names must not start with an uppercase letter" rule this
eliminates the ambiguity discussed in this thread.

On Sun, Dec 13, 2015 at 13:12 David Hart <david@hartbit.com> wrote:

struct Vector {
    var dx: Double
    var dy: Double
    var length: Double { return sqrt(dx*dx + dy*dy) }
}

vs

struct Vector {
    var dx: Double
    var dy: Double
    var length: Double { return sqrt(@dx*@dx + @dy*@dy) }
}

struct Vector {
    var dx: Double
    var dy: Double
    var length: Double { return sqrt(self.dx*self.dx + self.dy*self.dy)
}
}

I don't agree with you because when reading your first example, I have
to make a mental gymnastic to find out if the variables are local/global
variables or if they are instance properties. It might seem obvious in a
small piece of code like yours, but it becomes less so in a class several
hundred of lines long.

On 13 Dec 2015, at 10:48, ilya <ilya.nikokoshev@gmail.com> wrote:

> For me, readability has always been more important, as we spend most
of our time reading than writing code.
Agree.

> but they make code editing easier at the expense of readability.
Disagree. This really depends on the example. E.g. which is more
readable:

struct Vector {
    var dx: Double
    var dy: Double
    var length: Double { return sqrt(dx*dx + dy*dy) }
}

vs

struct Vector {
    var dx: Double
    var dy: Double
    var length: Double { return sqrt(@dx*@dx + @dy*@dy) }
}

struct Vector {
    var dx: Double
    var dy: Double
    var length: Double { return sqrt(self.dx*self.dx + self.dy*self.dy)
}
}

On Sun, Dec 13, 2015 at 12:40 PM, David Hart <david@hartbit.com> wrote:

Hi Ilya,

Why use a style guide when the language can enforce rules to eliminate
the ambiguity?

On the other hand, it allows a logical explanation of how you can take
code from global scope and put it into an instance scope

This helps implementing patterns like "take a long function and make
it into a struct with a bunch of small functions instead".

Both of your previous points make sense but they make code editing
easier at the expense of readability. For me, readability has always been
more important, as we spend most of our time reading than writing code.

That's why I suggest using .x and .f() to mark implicit self.

I agree that that would potentially add confusion to the grammar. I've
always liked the @ and @@ prefixes of Ruby for accessing instance and class
properties, but I agree that symbols like that would feel a bit foreign in
Swift.

David

On 13 Dec 2015, at 10:16, ilya via swift-evolution < >>>>> swift-evolution@swift.org> wrote:

> But implicit self is confusing in a lot of code

On the other hand, it allows a logical explanation of how you can take
code from global scope and put it into an instance scope:

let greeting = "Hello"
let name = "Michael"

func greet() {
    print("\(greeting), \(name)")
}

seemlessly becomes

class Greeter {

    let greeting = "Hello"
    let name = "Michael"

    func greet() {
        print("\(greeting), \(name)")
    }

}

> can (and does) lead to shadowing bugs,

There are simple strategies that help to minimize the amount of
shadowing, e.g.

- only expose the minimum necessary amount of names in any scope
- break functions into small part so that it's easy to see all the
local name declarations
- not use any globals, or at least name them in a visually different
way (UppercaseCamelStyle)
- name properties and locals in a different way (classProperty,
local_var)

Even without a formal code style, if you tend to make property names
longer and local names shorter, your risk of shadowing goes down.

> .x and .f() to mark implicit self. I realize that this may conflict
with enum usage.

This will lead to a lot of ambiguity:

func f() {
    let x = NSOperation()
    .name = "Name" // is it x.name or self.name??
   ...
}

> If so, then use another marker. For instance :x or ^x or anything.

This is workable, but still I think this is one of the best points of
Swift – the existence of instance scope where names are simply written
as-is. This helps implementing patterns like "take a long function and make
it into a struct with a bunch of small functions instead".

> is very difficult to reason about in diffs or any other interface
that isn't an IDE (especially code review)

This is the point where I entirely agree, good code should be easily
read in any context.
Again, may I suggest you take a look into using a style guide to
differentiate visually between local and instance scope?

Ilya

On Sun, Dec 13, 2015 at 10:15 AM, Rob Napier via swift-evolution < >>>>> swift-evolution@swift.org> wrote:

I wanted to reopen this discussion that seems to have trailed off.
Requesting the return of self was my very first ask of Swift if I remember
correctly (Apple Developer Forums). Continued
work in Swift has both strengthened and modified that ask. Here are several
of the examples discussed before:

https://gist.github.com/schwa/94b11dc0a7a331f46b25
Spooky action at a distance when you don't use self · GitHub
Even more shenanigans when self is not required · GitHub
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. · GitHub

I get that it seems tedious to type (and read) "self." and I get that
"self." is currently a hint that self might be captured (but doesn't
actually mean that, since you can use self. without capturing, and
sometimes have to, very often in init, so really it's basically meaningless
for that use).

That's why I suggest using .x and .f() to mark implicit self. I
realize that this may conflict with enum usage. If so, then use another
marker. For instance :x or ^x or anything. But implicit self is confusing
in a lot of code, can (and does) lead to shadowing bugs, and is very
difficult to reason about in diffs or any other interface that isn't an IDE
(especially code review).

Thoughts, David? I agree with your basic proposal; I just want to
amend it.

-Rob

_______________________________________________
swift-evolution mailing list
swift-evolution@swift.org
https://lists.swift.org/mailman/listinfo/swift-evolution

_______________________________________________
swift-evolution mailing list
swift-evolution@swift.org
https://lists.swift.org/mailman/listinfo/swift-evolution

_______________________________________________
swift-evolution mailing list
swift-evolution@swift.org
https://lists.swift.org/mailman/listinfo/swift-evolution

Note that the `self.property` access in Objective-C was not the preferred design.

The first choice was for bare `property` to work. That turned out to be ambiguous too often because of identically-named ivars. Swift doesn't have that problem.

The second choice was for bare `property` to access the property, requiring `self->ivar` to access an identically-named ivar. That was not feasible because it was incompatible with too much existing source code. Swift doesn't have that problem either.

Requiring `self.property` was the third choice.

···

On Dec 14, 2015, at 2:59 PM, Andrey Tarantsov via swift-evolution <swift-evolution@swift.org> wrote:

To me, self-access to properties in Objective-C is super-obtrusive, and I've been preferring fields for everything.

--
Greg Parker gparker@apple.com Runtime Wrangler

Note that the `self.property` access in Objective-C was not the preferred design.

The first choice was for bare `property` to work. That turned out to be ambiguous too often because of identically-named ivars. Swift doesn't have that problem.

The second choice was for bare `property` to access the property, requiring `self->ivar` to access an identically-named ivar. That was not feasible because it was incompatible with too much existing source code. Swift doesn't have that problem either.

Requiring `self.property` was the third choice.

Greg, these kinds of historical insights alone make 945 unread messages in my inbox worth it. Thank you!

A.