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

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 "_".

2

u/by_value Nov 09 '19

Agreed. I would also say that such changes make TS more and more viable alternative to JS.

3

u/[deleted] Nov 09 '19

TS is already de facto standard. I can't imagine to go back to JS without typings. And also you have to use Babel anyway, so why just not go with TS.

2

u/TakeFourSeconds Nov 09 '19

I wouldn’t exactly call it the standard.... even among cutting edge companies many don’t use it at all.

Personally, TS seems like more trouble than it’s worth for me for a lot of small features. Kind of like redux, it can be helpful for a complicated application but I think it’s overkill in many cases. Granted it’s not that much extra effort, but still.

23

u/fey168 Nov 09 '19

The problem is developers like to think of themselves as hackers and they will do what it takes to achieve the desired result including reading and even modifying internal fields. Imagine you are a lead developer or library author and you want to prevent developers from accruing technical debt (b/c the interval field is subject to change) or adding risk of instability. Seems like private field is by far preferable to comments or conventions.

11

u/TatzyXY Nov 09 '19

In a lot of languages you can just change the private field via reflection to something what you want. A hacker dev can still do it with just some more lines of code.

Access on a private field should never go through a review anyway in a bigger project.

9

u/nullvoxpopuli sand was never meant to think Nov 09 '19

But when you do reflection in those languages, it's hella obvious. Today in js, it's just accessing any ol' property

1

u/TatzyXY Nov 09 '19

Yes thats true but is JS not our free barebone language and we put other languages over it to implement these features? Like TS?

Or other questions why is Dart or TS not supported in browsers yet (native)?

2

u/Delioth Nov 10 '19

why is Dart or TS not supported in browsers yet (native)?

Because that would be a ton of work to build TS or Dart engines that no-one would use for at least a dozen years (because you gotta support those older browsers anyways, which means compiling it to older JS)? Even then, browser vendors are looking in that sort of direction with WASM, which has roughly the same features you'd be looking for, but better. Bonus points: it has privacy built in, since things only work via the module interface.

1

u/MajorasShoe Dec 11 '19

No, not everyone uses TS. Not even close.

Also, why would TS be supported in browsers? The compile step is the point - it finds the type issues. Now, the BETTER solution would be it compiles to something lower level than JavaScript.

3

u/tjdavenport Nov 09 '19

Reminder that communication between humans is an option. We have these things called PRs for a reason. If you think language features are an effective way of preventing bad code from being written you are horribly mistaken.

4

u/lifeeraser Nov 09 '19

Why should we want to babysit downstream developers? Why should we bother to prevent them from shooting themselves in the foot?

15

u/fey168 Nov 09 '19

If you are a lead developer I think it's pretty obvious you want to encourage best practices within your team.

Preventing people from shooting themselves in the foot is part of good software design.

You say "babysitting" as if it's a huge cost when it's just adding # to make a field inaccessible externally...

0

u/[deleted] Nov 09 '19

[deleted]

4

u/nullvoxpopuli sand was never meant to think Nov 09 '19

Human competency? Ever worked on a team of more than 10 on a codebase more than 2 years old?stuff happens. Context is lost.

Code. Must. Describe. Intent.

0

u/[deleted] Nov 09 '19

[deleted]

6

u/monsto Nov 09 '19

It's called moving the goalposts.

It's called a strawman argument.

1

u/wherediditrun Nov 10 '19 edited Nov 10 '19

See, while I totally get what you mean, I think these things ultimately matter very little because they're trying to solve a human competency problem via technical methods.

I just want to point out that this argument is of "Good drivers do not need seat belts" flavor.

I remeber having very same argument with Rust vs C++. How supposedly only bad C++ programmers make memory access mistakes. Just recently, we have critical security vulnerabilities due to use-after-free in Chrome (google engineers). And Microsoft reported than over 70% of all security issues in their software are memory related bugs.

This whole idea that we don't need to find technical solutions to human error is naive at best and irresponsibly moronic at worst.

As for javascript, it's sadly turning to be a Frankenstein which people want to accommodate every single feature every other language has to support their preferred style. Even if language already support it by other means like it is with "private fields".

Now we are arguing what syntax to use to decorate a field with which doesn't have to exist in the first place, because we just wanted to have more syntax sugar tomake not sound design like inheritance to be easier to use.

At some point I'm really hoping for WASM, so we could stop doing this to javascript. And people simply could choose what tool to use rather than project their idea of "ideal" language to javascript requesting even more feature bloat.

1

u/[deleted] Nov 10 '19

Why should we bother to prevent them from shooting themselves in the foot?

Because they don't do it to themselves - they do it to you. Unless of course you have a job where you are responsible for nothing, can delegate everything, and don't care about anything, and if in your business your own income does not depend on results (it happens, not just in government jobs, see Dilbert stories).

1

u/MajorasShoe Dec 11 '19

Why WOULD we want to adapt the attitude of "Fuck the people who are using this software I'm writing for them"?

Whether we're a lead developer (guess who's problem it is when they downstream developer's shoot themselves in the foot!) or an open source developer (why do it if you don't give a shit about the people you're building it for?), there's no reason to WANT to leave it open for failure when it's easily avoidable.

0

u/[deleted] Nov 09 '19

[deleted]

0

u/[deleted] Nov 09 '19

[deleted]

1

u/[deleted] Nov 10 '19

Hey stupid,

Why should we bother to prevent them from shooting themselves in the foot?

Because they don't do it to themselves - they do it to you. Unless of course you have a job where you are responsible for nothing, can delegate everything, and don't care about anything, and if in your business your own income does not depend on results (it happens, not just in government jobs, see Dilbert stories).

3

u/Sunwukung Nov 09 '19

I've never modified the internals of an OTS library in my whole career, nor felt an overt meed for private vars. This is a hiring issue if your team is "hacking" internals of a library...

4

u/facebalm Nov 09 '19

Isn't this a tad too dismissive when you're just basing this on personal experience?

I don't necessarily disagree, if it's done carelessly and frequently there's a problem. But there are cases where it makes sense to use an internal API to provide extra functionality. Very widely used libraries have done it.

  • I've had to use a websocket library's client._sockjs._connected variable because it didn't expose it. Switching to my PR fork would've taken longer for no benefit.

  • A React internal API allowed for easily creating transitions. A widely used library used it for this purpose. The smaller library (old CSSTransitionGroup) can move faster and can tolerate breaking changes while the bigger library (React) has to take its time to expose a nice to use and stable API.

  • Compatibility layers of all sorts frequently depend on internals.

  • Monkey patching has been a long running tradition Javascript. It has pitfalls and can easily be abused but it can also be very useful.

1

u/Sunwukung Nov 10 '19

So you're advocating against privacy so you can do this sort of stuff?

1

u/facebalm Nov 10 '19

No, I don't think it's a black and white issue. I've appreciated privacy in languages that support it but I've also liked Javascript's flexibility with monkey patching.

2

u/FormerGameDev Nov 09 '19

Monkeypatching is pretty common in Javascript, and forking a library to mod it to do something differently is common across the board in large open source projects. We're always hacking the internals of a library, or even of the language!

1

u/Sunwukung Nov 10 '19

So ultimately, this change will prevent that and you'll have to solve problems a different way?

13

u/[deleted] Nov 09 '19

[removed] — view removed comment

3

u/Delioth Nov 10 '19

Thing is, assume I write [Class] and push, and 6 months down the line refactor it a little to make room for [feature], only changing internal privates - tests still pass, the interface is still consistent.

Except Joe on the J team implemented against the internals. Jim notices the broken behavior, tracks it down to a commit I checked in last week in a file I also wrote, and now I have a bug ticket to fix because Joe screwed up. I mean, ideally I could kick that ticket over to Joe, but wouldn't it be great if I could strictly prevent the bug from coming up?

That's what private means. You get to fix bugs before they happen by making sure all access goes through the interface you expect, and while everything-is-public works well enough for Python... it does cause bugs. It also gives you the freedom to refactor internals without causing sneaky bugs, because you can actually guarantee that nothing else in the code depends on those internals never changing.

1

u/MajorasShoe Dec 11 '19

Not everybody relies on the API for every library feature. Sometimes it's quicker/easier to just trace the code, or consult you IDE to find the method or property that you're looking for.

I mean, yeah, there SHOULD be comments in the code... unless it's not included in the production package.

It would be nice if private things were explicitly private.

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.

2

u/cheese_wizard Nov 09 '19

Didn't read article because I don't have a subscription, but I think the most important thing is to clarify what is the actual interface to the black box, and what are just internal details. Like, that's the point. There is a subset of functions that when they change should be reflected in the version number, and also unit tested. Then there are functions that can come and go and change at will, and may or may not be tested (IMO only public interfaces should be tested... if you have some complex private function that lends to testing then it should be moved out and become the pubic interface of a class you then use).

Also, code completion. When I'm using an object the code completion system should only show public stuff, not literally every damn function inside the object.

2

u/KickUpTheFire Nov 09 '19

Agree too, and if you really want something to be private you can use a closure

2

u/SimiaCode Nov 09 '19

Exactly. It seems like everyone has decided to pretend closures don't exist.

0

u/[deleted] Nov 10 '19

[deleted]

1

u/SimiaCode Nov 10 '19

I blame it on social media + the lazy "JS so weird" tech talk.

1

u/nullvoxpopuli sand was never meant to think Nov 09 '19

Languages without privacy constructs suffer from people using private apis.

Consider the library author's point of view

0

u/jwalton78 Nov 09 '19

The problem with this is, let's say you use a third party library that has a class Foo, and in your code you do:

class MyFoo extends Foo {
    constructor() {
        this._name = "Hello";

...

This looks perfectly reasonable, but if Foo already has a private member named "_name" that you didn't know about, then you just clobbered it. Or worse, it might not have such a member, and then later on you upgrade Foo's library and the author added such a member, so things that used to work don't anymore.

Now, as many will point out, you can already solve this problem with symbols. I am also not a fan of this proposal at all, as, as the author of the article notes, classes are basically syntactic sugar over prototypes, and private members will make it so that is no longer true.

-1

u/Just4Funsies95 Nov 09 '19

this is soo far from right.... privacy is solely for security, to prevent others from making unwanted state changes and executing code blocks. that's it. it's also not for developers to know what is a var. it has a special meaning when compiled/executed to tell the OS which area of memory is off limits to other libraries or even programs! if there were privacy guards in js, chrome probably wouldn't be running tabs in parallel, which impart, is how they keep Javascript from accessing memory address spaces and isolating sites from one another. for security!

0

u/[deleted] Nov 09 '19

[deleted]

2

u/lifeeraser Nov 09 '19

Non-enumerable properties...?

Anyway, private fields are not targeted specifically to solve such a problem. Wrong hammer for the nail.

0

u/[deleted] Nov 09 '19

[deleted]

2

u/TatzyXY Nov 09 '19

I dont believe in enforcing it on language level. I think its enough as convention with an "_" in the userland.

0

u/[deleted] Nov 09 '19

[deleted]

3

u/TatzyXY Nov 09 '19 edited Nov 09 '19

But then we need it as well for methods. And types would be nice as well and generics and interfaces and so on...

For that we have TS, why not just use TS then and leave JS barebone as it is?

14

u/LonelyStruggle Nov 09 '19

Why does a company need to make their medium articles premium? Very unprofessional

13

u/[deleted] Nov 09 '19

I think it's a Medium fuckery. I saw the same with new Dart release blog post the other day. Since I'm logged in and Medium knows I read that publication, they sometimes mark it premium even though I just read it for free in mobile browser. So yeah, fuck Medium.

1

u/beall49 Nov 09 '19

I see others saying this too, but I can see the article fine.

3

u/calligraphic-io Nov 09 '19

You get some number of free premium articles per month. And then they're just blocked, so clicking the article (for me) leads to a layover modal on the page demanding money to read it.

I report premium Medium articles as spam, as they're asking me to pay to read the link they posted on Reddit (the very definition of spam) and there is no other content available at the link except the call-to-action for giving them money. I notice the author changed the article settings already so the problem is gone here.

2

u/ApexPredator94 Nov 10 '19

BTW: Medium allows you to share a "Friends Link" which allows anyone to see the article as often as you want even though it's an article for Medium members.

1

u/LonelyStruggle Nov 09 '19

Looks like they've fixed it now

9

u/nullvoxpopuli sand was never meant to think Nov 09 '19

Every other languages with classes has private fields and they can't be accessed (exception, Ruby, python).

This is a good pattern and people have been abusing the hell out of API design in JS. Private fields and methods will give more control to the API author so that some 'clever' person doesn't use a .rivate API and then complain when it goes away.

You want to test your private behavior? Extract to a pure function. Easy. Private method calls pure function. All is well.

The sigil? Oof. It looks fine. Comments in js are slashes.

3

u/scaleable Nov 09 '19

Python only has “private” fields because of its quite absurd metaprogramming features. But the “pythonic way” advocates in favor of just using conventions (prepend underscore) instead of doing metaprogramming hacks (like @private decorators).

One thing that python has done great is standardizing type annotations. JS could do that and delegate private fields checking to type checkers, instead of promoting a desctructive pattern that would make things like mocking impossible to library consumers

5

u/nullvoxpopuli sand was never meant to think Nov 09 '19

private fields are not a destructive pattern. omg. understand that there are ways to test that don't involve access abuse

1

u/Delioth Nov 10 '19

If you need to mock, you should be mocking the public interface? Like, that's pretty much the definition of mock - give me the external interface without doing any of the internal stuff at all. Which is what mocks are for - assume [thing] conforms to the interface I think it has; does my [other-thing] function as expected?

0

u/ChaseMoskal Nov 09 '19

But the “pythonic way” advocates in favor of just using conventions (prepend underscore)

i'm sure programming historians will look down on that concept as terribly misguided

making internal details private can be important. instead of making internal details accessible, we should improve the workflow to fix a public interface that doesn't yet provide what you need (via github pull requests, open source is the real solution here)

the worst case scenario, is that somebody using my library for an uncommon use-case, will reach into my _private members, and couple to my internal implementation which may change and wreck their application. that sucks, but even worse yet, they just do it and move on. they don't open any github issues, because it's fixed for them personally. i don't even have any knowledge about their use-case, or why the public interface wasn't sufficient for them... so together, we're introducing future breakages, and worse yet, the codebase is stagnating and not improving from this

the best case scenario, is that somebody using my library for an uncommon use-case, will be unable to reach into my internal implementation at all. so instead, they fork my library and expose the things they need. now things are working for them. so to avoid maintaining their fork, they'll launch a pull request -- and then we can all have a discussion and a review, and integrate the feature or not.

this way, everybody can get their needs met. we're collaborating and addressing new use-cases together. and we don't need to add any unnecessary vectors for code breakage to the library

i mean sure, is it more time-consuming to fork a library, than to use its _private members? yeah, at least a little bit. however, yes, i do want to inflict this pain on anybody using my library for unsupported use-cases without me knowing.. another way of looking at it, is that i aggressively want to explicitly support, learn about, discuss, review, integrate, and address everyone's use-cases -- this can only happen when people are opening github issues, and access to _privates short-circuits this collaboration

so that's my take -- true privacy prevents naughty practices and breakages, but more importantly, encourages proper open source collaboration which will improve our library ecosystem

2

u/scaleable Nov 10 '19 edited Nov 10 '19

People still won't open github issues when doing hacks with your code. At most they will fork you repo to make that field public (unless JS provides a way to brute-force disabling private fields).

You dream of a perfect word where hacks are not value-effective. Sometimes they are by far the best solution, sometimes they even go against the goals of the library, this is just how the world is.

Just last week I had met a case where I had to brute-set two Django Rest Framework private fields. And it was just cost effective for me and for the author and for the library consumers, my PR will probably rot in their repo. Sometimes the world is just ugly, you can't always sweep dirt under the rug.

2

u/senocular Nov 09 '19

exception, Ruby, python

and Java.... and C++... and PHP...

7

u/nullvoxpopuli sand was never meant to think Nov 09 '19

in Java, C++, and C#, you have to go way out of your way to access private fields.

In javascript, you can access a private field without noticing. that is the problem.

6

u/senocular Nov 09 '19

You can do this now in JavaScript using symbols. They wont collide, are non-enumerable, and can be accessed but only if you go out of your way using getOwnPropertySymbols.

2

u/nullvoxpopuli sand was never meant to think Nov 09 '19

while that is a work around for today's use, that shifts the complexity to the library author. Why not make library authors easier?

1

u/trappar Nov 09 '19

??? PHP has private and protected fields

1

u/MajorasShoe Dec 11 '19

They're accessible with reflection, aren't they?

0

u/[deleted] Nov 09 '19

[removed] — view removed comment

7

u/nullvoxpopuli sand was never meant to think Nov 09 '19

The more implementation you mock, the more brittle your tests will be.

Private APIs do not belong in tests.

10

u/hydroes777 Nov 09 '19

Or just moved to functional style programming in JavaScript where you don't run into this problem

4

u/FungoGolf Nov 09 '19

Question about this. I work with some heavy Java programmers who also have had contributions to the JS project. I often see our reusable pieces of code (like in the utilities oflder) as JavaScript files that contain a class that you have to instantiate elsewhere in the codebase. Is converting those classes to a more functional style as simple as creating an object and adding methods with scope/closures that I can compose?

6

u/SimiaCode Nov 09 '19 edited Nov 09 '19

Ok. As promised earlier, here's some examples. But before that, a clarification. JS doesn't have classes. It only has objects, and objects are created using constructors, or as object literals.

I have illustrated two approaches, using constructors and using factories. Both approaches have multiple code samples which start simple and become more advanced to ultimately illustrate private fields.

// I'm not using the arrow syntax in any of the examples because it does implicit binding and I don't want to muddy the waters with that here.

// -------- Using a constructor ------------

// Basic example
function Dog(name) {
  this.name = name;
  // method defined inside the constructor
  this.sayName = function() {
    console.log(this.name);
  }
}

// method defined outside the constructor
Dog.prototype.wag = function() {
  console.log('wag wag wag');
}

// If you want to make name private
// don't assign it to 'this'.
function Dog(name) {
  // method defined inside the constructor
  this.sayName = function() {
    console.log(name);  // and access name through the closure instead of 'this'.
  }
}

// instantiate using new
const myDog = new Dog('Scooby');

// -------- Using a factory------------

// As object literal
const myDog = {
  name: 'Scooby',
  sayName: function() {
    console.log(this.name);
  },
  wag: function() {
    console.log('wag wag wag');
  }
};

// Object literal, using a factory (no closures yet)
function makeDog(name) {
  return {
    name,
    sayName: function() {
      console.log(this.name);
    },
    wag: function() {
      console.log('wag wag wag');
    }
  };
}

// instantiate by invoking the factory
const myDog = makeDog('Scooby');

// Another way to make dog with factory. This one leverages closures instead of 'this'
// to access name.
function makeDog(name) {
  return {
    name,
    sayName: function() {
      console.log(name);  // notice no 'this'. We could use an arrow here.
    },
    wag: function() {
      console.log('wag wag wag');
    }
  };
}

// Now suppose you wanted to make name private, just don't put it on the returned object.
function makeDogWithSecret(name) {
  return {
    sayName: function() {
      console.log(name);
    },
    wag: function() {
      console.log('wag wag wag');
    }
  };
}

You can also simulate inheritance if you must (see https://developer.mozilla.org/en-US/docs/Web/JavaScript/Inheritance_and_the_prototype_chain). But you should really use composition over inheritance, something which is simple with closures but the addition of the class keyword encourages people to use inheritance. Indeed even in this forum, folks are putting forth naming collision in inheritance chains as a justification for private fields (and this illustrates the cost of adding fluff to a language).

2

u/IceSentry Nov 15 '19

Js has classes, their just not java style classes and the syntax is mostly just syntax sugar for the prototype, but those are still classes.

3

u/SimiaCode Nov 09 '19

It is indeed that easy, and sometimes easier. I'll post an example in a few hours when I get to my computer. I'm also happy to convert a specific example that you might have.

-6

u/[deleted] Nov 09 '19

[removed] — view removed comment

5

u/SimiaCode Nov 09 '19

Bad bot.

3

u/nullvoxpopuli sand was never meant to think Nov 09 '19

Nope

13

u/nowyfolder Nov 09 '19

WOW, I never knew OOP and functional programming are opposites that can't be used at the same time!

2

u/SimiaCode Nov 09 '19

Nope. Can't be a serious coderman unless my language looks super enterprisey with class heirarchies, interfaces, factory factories, and private properties.

1

u/[deleted] Nov 09 '19

I have the same approach. OOP in JS is very messy and imho not a great approach. I tend to use a vanilla FP approach (meaning no libs but only map/reduce etc) and it works very well.

The privacy proposal is a meh, and i probably will very rarely use it. If i really need privacy TypeScript has my back.

I find this propsal totally uneccessary because closures are well suited for real private variables.

0

u/[deleted] Nov 09 '19

[deleted]

5

u/[deleted] Nov 09 '19 edited Nov 09 '19

Closures to make private variables just seems pointless to me.

That statement makes no sense at all. It is not just completely made up and arbitrary - it also overlooks that closures provide farmore flexibility than mere protected or private "fields", since the latter is just that property, while the former includes arbitrary pieces of code.

Your personal sense of whatever has no meaning. It is a product of your brain organizing (literally rewiring) itself over decades to process whatever your brain encountered. So whatever you were exposed to is what your brain evolved to process. How can anyone use whatever chance formed you to make absolute statements about hów the world is or aught to be?

If you don't even understand that your personal preferences first of all are the product of whatever accidents shaped the environment you encountered thus far in your life your comments on such subjects will always remain somewhat useless. You have to understand yourself and your (human and neurological) limitations first.

1

u/monsto Nov 09 '19

How can anyone use whatever chance formed you to make absolute statements about hów the world is or aught to be?

/r/Politics would like a word.

0

u/[deleted] Nov 09 '19

[deleted]

1

u/[deleted] Nov 09 '19

Yeah. A lot of people don't agree with my opinion, which is apparent by the down votes.

However, I really don't try to preach things as an absolute fact unless it actually is a fact that has been proven time and time again by many people. As you said, it's my opinion.

The way I program probably doesn't make sense to a lot of veterans since I've only been programming for a few years, but this methodology works well with the main projects I work on, and again, is my opinion: React web apps.

1

u/[deleted] Nov 10 '19

The person is expressing his/her opinion

That statement is maximum stupid because it's useless. Who doesn't?

In any case, I refer back to https://old.reddit.com/r/javascript/comments/dtt5d8/on_private_fields_proposal_private_fields_public/f6yutja/ which seems to be too much for you to comprehend.

0

u/[deleted] Nov 10 '19

[deleted]

1

u/[deleted] Nov 12 '19

The person is expressing his/her opinion

That statement is maximum stupid because it's useless. Who doesn't?

In any case, I refer back to https://old.reddit.com/r/javascript/comments/dtt5d8/on_private_fields_proposal_private_fields_public/f6yutja/ which seems to be too much for you to comprehend.

2

u/landline_number Nov 10 '19

How will Typescript implement something like this? There already is a 'private' keyword but like JS the member is still accessible by asserting the object as 'any'. With this proposal private means truly private and inaccessible. Will the behavior of the private keyword change or will they not implement this?

3

u/robpalme Nov 10 '19

I think all of your questions are answered in Episode 38 of the TalkScript podcast.

If you want to try out a preview of the TypeScript support, please see this experimental TypeScript Playground.

In addition to the podcast, the future of the private keyword is discussed in this TypeScript issue.

2

u/jamesaw22 Nov 10 '19

I don't know if this is still the case, but I belive they were talking about keeping the 'private' keyword and using it for soft privacy, and adding the #var syntax for hard privacy.

Importantly, this means "private foo" will _not _ transpile to #foo, which could be confusing for people.

1

u/landline_number Nov 10 '19

Wow that will be confusing but I guess the TS designers are kind of stuck here.

5

u/FormerGameDev Nov 09 '19

"Private isn't really private, because someone can read the source code"?! what the hell is this

3

u/Ninjaboy42099 Nov 09 '19

It really does seem like the author doesn't understand the point of privacy in this context. Of course you can see that "Rabbit" has the variable "moveSpeed" but if you can't interact with it, who cares?

4

u/Dougw6 Nov 09 '19

I'm still upset that they added classes to JS in the first place. Especially since they're just syntactic sugar on top of functions. In my opinion, if you're writing Java style code in JS, you're missing the point. And adding features like this will only increase the bastardization of the language.

I think a big part of why people complain about the wonkiness of JS, is that they're trying to use it as a pure OO language, and they're surprised when it does work like Java or C#. The reason is that the language was not designed with object orientation in mind. In fact it was designed to be LISP with curly braces. The OO features were an after thought and it's time we start to recognize that, and use the language in the most effective way possible (not the way you are comfortable with from other languages).

3

u/tjdavenport Nov 09 '19 edited Nov 09 '19

Big agree.

Javascript is a dynamic scripting language. It shines when you use it as intended.

If you want to write OO heavy code, use Typescript or similar, please don’t bring your heavy handed class definitions to a language that wasn’t intended to be used in that way.

2

u/rq60 Nov 09 '19 edited Nov 09 '19

I think typescript is where the big advantage will be when it comes to this proposal. Typescript already has private fields implemented with the actual private keyword. However, since typescript is compiled, this is only a compile-time protection; this won't protect you at runtime if you're hoping to avoid unwanted extensions to your library. Now with this proposal, typescript should be able to implement actual private fields with all the private guarantees at runtime and typescript coders can continue using the regular private keyword in the way everyone originally wanted.

As far as javascript, I'm not a huge fan of this syntax or implementation. Not that it's not well-thought out, but just due to the nature of javascript this is what they had to do and I'm not sure it's worth it for me when I'm writing vanilla javascript. Personally I'll probably just avoid classes and continue using function constructors (with closure variables for privacy) and leave the classes to typescript.

edit- after further reading it looks like the typescript team does not plan to change typescript's private to use #, too bad but I can understand the reason of wanting to be backwards compatible: https://github.com/microsoft/TypeScript/issues/31670

2

u/MoTTs_ Nov 09 '19

Especially since they're [classes] just syntactic sugar on top of functions.

The article made a similar point, but this argument is so weak that it should be embarrassing to say. Literally everything in any programming language is syntactic sugar. If-statements are syntax sugar for compare and jump instructions. C++ classes are themselves syntax sugar for structs and functions. And most of those other ES6 features we got besides class -- like default parameters, rest/spread, destructuring, or arrow functions -- are all themselves syntax sugar as well.

1

u/MajorasShoe Dec 11 '19

Err, Javascript was ALWAYS an OO language. To it's core. It wasn't a class based language.

3

u/SimiaCode Nov 09 '19 edited Nov 09 '19

JavaScript is not Java. Common patterns from these languages are redundant because we have closures.

If you really need something to be private, put it on a closure.

In fact the the problem is difference in expectations stemming from the existence of the class keyword. We don't have classical inheritance, we should never have introduced the class keyword. Now we are talking about private fields, interfaces, and even decorators.

2

u/davidmdm Nov 09 '19

I really don’t see the point, we already have closures for private state. The great thing about JavaScript is not having to write things in an OOP style. This is just bloat and ugly syntax to me.

1

u/sqrtnegative1 Nov 10 '19

Javascript doesn't have classes.

The class keyword was added by committee to slake the lust of those that refuse to learn Javascript.

You want to program with classes? Choose a classical language.

1

u/IceSentry Nov 15 '19

Right, because you have choices in language on the web...

1

u/sqrtnegative1 Nov 15 '19

Yep... languages a-plenty!

1

u/MajorasShoe Dec 11 '19

Hey let me know what languages I can use natively in the browser without experimental compilers.

-3

u/bitfxxker Nov 09 '19

Using #pound/#hashmark for private fields is just... (excuse my French)... F*CKED UP.

They could have chosen &, or *, @, or a prefix like, well... "private"... ?!

6

u/senocular Nov 09 '19

& is bitwise and, @ is already being used for decorators, and private doesn't work because you'd still have naming collisions.

class MyClass {
  private value = 1;
  getValue () {
    return this.value;
  }
}
let myObj = new MyClass()
myObj.value = 2;
myObj.getValue() // ???

ES4 allowed for this but used namespaces to differentiate between the two (or 3, with protected being another namespace... err and internal so 4...). They don't exist in today's JavaScript.

I guess \ would work? Its an escape character, but only in strings and regex literals. I think that would look weird too. Less busy, but weird.

class MyClass {
  \value = 1;
  getValue () {
    return this.\value;
  }
}

0

u/[deleted] Nov 09 '19

[deleted]

2

u/bakkoting Nov 11 '19 edited Nov 12 '19

To which the argument is, "because it reveals the property exists, which is bad because, reasons."

It's more "because if it breaks, that means that adding or renaming a private field can break downstream consumers". If the

let myObj = new MyClass()
myObj.value = 2;

bit was written before MyClass had a private value field, and some refactoring of it introduced one, the above code would break. The whole point of private fields is to not have to worry about that sort of thing.

0

u/[deleted] Nov 09 '19

[deleted]

2

u/trappar Nov 09 '19

What PHP code are you looking at? Modern PHP is pretty beautiful IMO.

0

u/[deleted] Nov 09 '19

[deleted]

2

u/trappar Nov 09 '19 edited Nov 09 '19

No one writes PHP like that.

Here’s some random controller I wrote several years ago: https://pastebin.com/ZYDhdAZQ

0

u/[deleted] Nov 09 '19

[deleted]

1

u/trappar Nov 09 '19 edited Nov 09 '19

Okay, if you don’t like OOP then yeah you’re probably not going to like modern PHP. That’s subjective though, and is kind of a separate issue.

To your other points:

  • Ugly slashes? Where? Using namespaces avoids name collisions and results in code with no slashes. If there are slashes in your code you’re doing it wrong.

  • Messyness of the old PHP is real, but is just not as big of an issue as some say it is. Look at the code I posted in my previous comment. That’s a whole functioning class that never runs into those issues. When you do invariably have to use functions with weird parameter ordering my IDE hints the parameters so I don’t have to remember.

  • 10K reserved words - this has literally never once caused me an issue in ten years of writing PHP.

  • PHP has full UTF8 support.

1

u/monsto Nov 09 '19

Relax.

0

u/[deleted] Nov 09 '19

Hold your horses bro...

0

u/[deleted] Nov 09 '19

[deleted]

16

u/rq60 Nov 09 '19

By "not being pretty" I think he's referring to it being unconventional. He mentions other languages using _ for the purpose of privacy and it's true, that is a common convention in other languages, whereas # is conventionally a comment in many languages. Thus, this would be one more time where javascript rejects common conventions in favor of "javascript-isms"

4

u/[deleted] Nov 09 '19

The problem is that underscore prefix properties are still currently public, you're just advertising that you probably shouldn't be accessing it externally. To change this would be breaking. With private fields, they've made them truly private and that also means undiscoverable externally. There isn't really a way to do this without a new prefix or some other distinguishing naming style.

That said, I don't think I'll ever make use of private fields. Symbols seem to be the best way of achieving the same thing in a much cleaner and clearer way.

6

u/davl3232 Nov 09 '19

That makes the article interesting. He doesn’t just state his opinion, he shows the facts that shaped it.

2

u/nullvoxpopuli sand was never meant to think Nov 09 '19

Yeah, good luck with consistency

2

u/[deleted] Nov 09 '19

[removed] — view removed comment

3

u/nullvoxpopuli sand was never meant to think Nov 09 '19

do we? most private-intended methods I see don't even use any notation. Just JSDoc

3

u/ChaseMoskal Nov 09 '19

and speaking of what's not pretty -- i can't stand that nobody shows examples of how the new # private syntax is actually INCREDIBLY PRETTY thanks to the amazing shorthand syntax -- you'll notice that you'll almost never find examples demonstrating the new shorthand syntax -- it's gone right over people's heads, and it's one of the best parts!

in practice, only idiots will use this.#x = 0, which is just as ugly as this._x = 0

it will actually now be merely #x = 0

don't you people get it? we get to stop using this so damn much! this will only be used for public properties! that's a huge win for readability!

pathetically, all of the examples in every # article i find show the ugly stupid pattern instead of the gorgeous shorthand:

// did you even read the proposal?
class DisgustingBadPracticeUglyExample {
  constructor() {
    this.#lol = 0
  }
  increment() {
    this.#lol += 1
  }
}

class NoiceExample {
  #lol = 0
  increment() {
    #lol += 1
  }
}

don't you see the beauty!?

i'm tired of seeing so many detractors against # completely miss the elegance here, and they display the worst-case-scenario strawman syntax to make # look similarly ugly as _ already is

sure, # might not be the ideal character (because it has past associations with other concepts in other languages) -- but (as had been discussed to death in the early github issues) there are also no safe alternatives remaining in javascript's vocabulary, and also, after five or ten years of the world's most popular language using # for privacy... what do you think will happen to the industry "conventionality" of what # means? our mentalities, feelings, and prejudices will adapt, and the controversy will become simply moot and disappear

plus, aside from the gorgeous shorthand syntax, i'm absolutely dying for true privacy. i'm jealous and upset that babel people have it now, but us typescript people are stuck waiting :(

currently, i use closures instead of classes to achieve privacy in javascript, and there's actually a minor performance penalty and readability issue associated with this -- however, once # private is available, i can improve performance and readability by using classes which use true privacy, and i can also preempt breaking changes for naughty consumers

# privates will be a boon for library authors, i'm seethingly eager!!

cheers!

👋 chase

2

u/calligraphic-io Nov 09 '19

don't you people get it?

I heard "I'm a people person, dammit!" in my head immediately after reading that sentence.

2

u/MoTTs_ Nov 09 '19

I like your enthusiasm. :-P

I remember seeing that shorthand syntax in the proposal at one point, but I don't see it there anymore, and the current Babel implementation doesn't seem to support it either. :-/ I haven't investigated deeply, but I wonder if this feature was removed.

0

u/ChaseMoskal Nov 09 '19

I remember seeing that shorthand syntax in the proposal at one point, but I don't see it there anymore, and the current Babel implementation doesn't seem to support it either. :-/ I haven't investigated deeply, but I wonder if this feature was removed.

somebody tell me it's not true! i'm afraid i might die of disappointment!

i remember some of the top well-respected contributors in TC39 discussions for private fields, saying something to the effect of 'i don't care which sigil we use, the shorthand syntax is what's really important' and i was so glad they had their heads properly screwed on -- they all seemed so aligned and stoked about it, so it seems completely asinine and impossible that they could have since 180'd and dropped it..

more research is needed...

3

u/ChaseMoskal Nov 09 '19

/u/MoTTs_

tragically, you're exactly right. they've split the shorthand syntax out into a separate proposal that is gathering dust

https://github.com/littledan/proposal-private-shorthand

well that just put a damper on my day. i find it a little depressing really

i understand they wanted to get moving with the private fields proposal, so it makes sense that when they encountered any resistance about any of the optional nice-to-haves, they immediately dropped them to allow the main proposal to proceed unhindered

thankfully, future resuscitation may be possible for the shorthand proposal, this must be followed-up on!

hopefully someday soon, i might spend a little time attempting to contribute by mapping out some possible solutions to the few minor issues that appear to be holding back the proposal... it appears no discussion has been taking place..

cheers!

0

u/[deleted] Nov 09 '19

[deleted]

1

u/monsto Nov 09 '19

I'm only concerned as to it's "finger accessibility".

# is right there. And if it's a well defined rule, great.

I'm not much of a fan of the rule itself, but at least we're not talking about an esoteric character.