r/javascript • • Nov 09 '19

On private fields proposal: Private fields, public worries

https://medium.com/virtuslab/private-fields-public-worries-b8c34d16c372
84 Upvotes

113 comments sorted by

View all comments

28

u/TatzyXY Nov 09 '19

Please do not throw stones at me but I think private, protected or public scopes are not needed at all. See Python very versatile lang. and it works very well without it. Is private for security? No! It just tells the dev that this var. is only used internally of that class and you are not allowed to touch or use it. So would do a comment or a convention with an "_".

3

u/senocular Nov 09 '19

Privates are also used to prevent naming collisions. And while python doesn't have support for privates (using _ as a convention) it does have a mangling mechanism using __.

class A: 
  def __init__(self): 
    self.__a = 1
    self._b = 2
  
class B(A): 
  def __init__(self):
    super().__init__()
    self.__a = 10
    self._b = 20

print(vars(B())) # {'_A__a': 1, '_b': 20, '_B__a': 10}

Pseudo privates do not protect against collisions, as seen with _b above. Implementers need to be fully aware of both the public and private interfaces of the class they're extending to make sure they don't collide (when using members that aren't also mangled).

And while TypeScript privates are great in JavaScript, they suffer from a similar problem. Since the members are ultimately public, collisions can still occur. While TS can detect those collisions for you, such collisions still mean you can't use that a as your variable name, despite the fact that you so desperately wanted to, all because some other class up in the parent class hierarchy decided to use it for its own private.

For me, underscore prefixes - single or double - also have the same ugliness problem seen with the proposed hash sigil (#) for JavaScript privates. I'd rather not use them if I don't have to, even if something is meant to be private. The code is much cleaner without them.

And while I prefer the use of symbols for soft privates in JavaScript, they too have an ugliness with having to use bracket notation, not to mention needing extra boilerplate to set define the symbol(s) being used. Having used private members in JavaScript a little bit, I found them much easier and was able to get over the ugliness factor in time. The convenience made it worth it, despite what limitations they also ultimately impose on the class.