10 ms·
Public and private class fields
- deleted 8y ago[deleted]
- bokchoi 8y agoWow, the '#' prefix is so ugly.
- ape4 8y agoAgree. `public` and `private` keywords would be much better.
- cpeterso 8y agopublic and private are already reserved keywords in JavaScript strict mode, so there should be no issue with web compatibility. https://mathiasbynens.be/notes/reserved-keywords https://mathiasbynens.be/notes/reserved-keywords
- sjroot 8y agoThis syntax is...odd. It is not expressive and comes off as a "language hack." The only people who would understand it are those who happen to stumble on this article. Frankly, if this is an issue that you are concerned about, you should really invest the time to learn (and possibly migrate to) TypeScript. Specifically, see their class documentation which already has support for `public`, `private`, and `protected` [1]. (Edit: read @denisw's reply regarding TS. I make this suggestion specifically for TS's compile-time assistance regarding private field access.) It actually kind of boggles my mind that V8 engineers sat down and agreed that this would be a good design decision. Granted, the article says that they are proposals—is there any way to provide feedback on this? (Edit: https://github.com/tc39/proposal-class-fields/blob/master/PRIVATE_SYNTAX_FAQ.md#why-arent-declarations-private-x https://github.com/tc39/proposal-class-fields/blob/master/PR...) [1] https://www.typescriptlang.org/docs/handbook/classes.html https://www.typescriptlang.org/docs/handbook/classes.html
- denisw 8y agoOne important thing to note here is that this goes much further than `private` in TypeScript. The latter is purely a compile-time illusion. If you write `private x`, your objects' x property is still publically accessible and modifiable as far as the JS runtime is concerned. any other. It‘s just the TypeScript compiler that gives you an error if you access x, and only if it happens to have the type information it needs to do so (if the object ends up in an `any` variable, all bets are off). This means TypeScript's "private" properties also shows up in the return value of Object.keys() etc. So it‘s a pretty leaky abstraction. This proposal, on the other hand, tries to solve the much harder problem of of bringing true private instance variables to JS. This means making it impossible to access these variables from outside the project. To do this, they had to introduce a complete new "private namespace" that is different from the `this.<name>` one, because the latter is already reserved for the visible-to-everyone properties (messing with that would have serious compatibility implications). Hence the `#foo` syntax.
- sjroot 8y agoThat is a very important clarification and I imagine TypeScript will leverage this new feature. That said, I still don't like the #. I think that will be the biggest issue with adoption (at least based on feedback on this post). Would the spec have to come up with another symbol if they wanted to implement `protected` behavior? Alternatively: `this.private.value`, `definitelyNotThis.value`
- jamestimmins 8y agoDoes this mean that with TypeScript someone could still see private values if they used their developer console on the browser, but with this approach that would be impossible?
- james-mcelwain 8y agoAccess modifiers in TS are compile time only checks. This change is not about visibility in dev tools. I'd imagine you'll still be able to see and mutate private fields in dev console, just like you can in a Java debugger, etc. This change is for libraries, so that if someone consumes a TS library, for example, they can't monkey patch or otherwise touch private fields at runtime.
- mkozlows 8y agoThis is Exhibit N for the "the class keyword is ruining Javascript" prosecution. If you want a "private variable" you just use a closure. let incrementer = () => { let x = 0; return { value: () => x, increment: () => x++ }; }; It's like the OO people are determined to forget about the functional concepts that made JS great.
- Theodeus 8y agoI agree.
- sjroot 8y agoI was in the process of writing a reply that argued against this (mainly because it is not as readable as a class implementation), but I sort of agree with you as well. That said, considering how widespread JavaScript is at this point, I think it is in their best interest to cater to more than one programming style.
- josephg 8y ago> That said, considering how widespread JavaScript is at this point, I think it is in their best interest to cater to more than one programming style. No! Stop! Bolting 6 different programming paradigms into a language doesn’t make it easier to learn. It makes it harder, because every programmer who learns JavaScript needs to learn all of the tools of the language so they can read the code written by others. More language features / paradigms make JS less accessible. It is a terrible idea if your goal is to help people learn JS.
- sjroot 8y agoI agree with you, but if they are going to pick one paradigm to build new features for, it is certainly going to be OOP (for better or worse).
- ihuman 8y agoWhat are some other examples of the class keyword ruining Javascript?
- ihuman 8y agoI don't understand why public fields need the underscore prefix. Aren't all fields public by default? Why do you need to add a prefix to "hide" public fields?
- mikewhy 8y agoThey don't, that's just the example they chose. Prefixing variables / functions with the underscore has long been a signal for "this is private" in languages that don't provide the functionality.
- sjroot 8y agoThis is true, but the whole point of this article is to introduce a new way of handling private class members.
- sjroot 8y agoI think the idea is to distinguish them from class getter functions? I don't really understand it either.
- dberg 8y agoMaybe I’m old school but instead of private it looks like they accidentally commented out a variable. # does not feel idiomatic to me.
- sbr464 8y agoI agree, also, it definitely doesn’t help readability. That being said, the underlying private feature is appreciated.
- 21 8y agoWhy not use the private/public keywords like in TypeScript? Was this # thing voted by the community or something?
- lucideer 8y agoThe justification is that they needed a unique accessor, because: - attempting to access a non-existent private property using `this.prop` would create a public property "prop" in JS, which they claim would be a source of bugs. - they also wanted to allow creating a public property on a subclass with the same name as a private property on a parent class—having the accessors the same could be confusing. That said, they could still have had keywords for definition with an alternative accessor. # is definitely not idiomatic; it's extremely ugly.
- mathias 8y agoThe article links to the explanation by the proposal champions: https://github.com/tc39/proposal-class-fields/blob/master/PRIVATE_SYNTAX_FAQ.md#why-arent-declarations-private-x https://github.com/tc39/proposal-class-fields/blob/master/PR...
- a13n 8y agoCan't we just use a private keyword like other languages? Why the # symbol. Just seems random and confusing. Also, will there be a way to do protected?
- catpolice 8y agoFirst, like the other commenters, I'm not in love with the perlish # syntax. I'm not sure why it was wise/necessary to add a previously illegal character as a prefix, rather than adding a "private" keyword, but I'm sure there's some reason. Second, the example affords an opportunity to rant about a pet peeve of mine. "Now ask yourself, how would you implement this class in JavaScript?" I wouldn't. Listen folks: unless you're doing some weird/temporary debugging or you need to add some meta-functionality (e.g. logging) to an API that reeallly can't change, don't write getters/setters. If accessing or setting a property needs to do computation or have side effects, refactor so that it's done explicitly by calling a method. Anything that lets you attach invisible effects to normal syntax is an anti-pattern because it makes your code behave differently than it appears to, and therefore it's harder to reason about from the outside.
- werkjohann 8y agoI'm curious, is JS your primary language? Getters and setters have been around since ~2010 (other languages also make heavy use of them, like Obj-C). I suspect that you only see this as "invisible" because you first learned a language that didn't have getters/setters (and if you started with modern JS, or Obj-C the fact that properties aren't "dumb" would just be a given). Thoughts?
- deleted 8y ago[deleted]
- catpolice 8y agoI've been using languages with getters and setters for long enough to be familiar with them. There was a time that I thought they were useful and used them in my own code. But I've been burned enough, and thought enough about language design that I've come to avoid them. I say they're "invisible" because of the property illustrated by these two statements: foo.bar = 0; foo.baz = 0; One of these gets compiled/JIT-ed into a few assembly instructions and the other calls an O(n^2) function (with side effects) on a giant tree structure that foo is a part of. You can't guess which is which from looking at those, unless you've read the source for the foo class and memorized which properties are behind setters. They're "invisible" because you can't see when you're using one. A good property for code to have is that you can infer its semantics from its syntax with as little outside information as possible. When you read a line of code, you should get reliable clues about what that makes the computer do. You might not need to know /all/ the details - e.g. a method call encapsulates the details of an operation but the name (and documentation) give you a good idea of what's happening. The problem with getters and setters is that they do more than abstract away details, they cloak potentially important semantic information about code in ways that can be misleading. By contrast, if I read: foo.setBar(0); foo.baz = 0; I might not know all the details about what setBar does, but at least I have a clue that it's more complicated than the following line. I've been burned IRL by this kind of thing - I've seen very expensive getters mysteriously ruin hot loops (making what looked like a linear operation into an O(n^3) operation) and developers pulling their hair out because of setters that silently rejected values and all sorts associated headaches. Working in settings where they came up semi-frequently made me feel like complexity could be hidden anywhere, and reduced my confidence that I understood code that I read. JS and other languages with reflection have a whole host of associated issues. If a field gets refactored into a getter, it's suddenly not enumerable and will silently fall out of a lot of copy operations. Suppose you want to find every place that the setter gets called, so you grep for `.bar = ` but did you remember the myriad of other ways that setter could get called (e.g. foo["bar"] =, foo[someVariable] =, Object.assign, etc.)? In my experience, unless you have some extremely strong reason why you can't refactor or some very well-defined standards about when to use them, they're not worth the trouble they bring when code suddenly stops behaving the way you expect it to.
- RandomInteger4 8y agoWhat problem do private fields solve?
- jarvuschris 8y agoWhen you're building a component that will be used as part of larger applications, possibly written by other people, declaring things as private lets you cordon off internal parts of the component so that it's safer to change them in the future without breaking the applications using it Someone trying to make an application work that is looking at your classes in a debugger is going to poke at whatever inside details they can see that helps them get their job done quicker. Now if you change that their application breaks when they update. Not good for anyone. Privates make it easier for component developers to get things done without worrying about breaking users, and makes it easier for users to upgrade their components without it breaking as much
- RandomInteger4 8y agoWouldn't it be simpler to have a Terms of Service that voids the warranty of code being misused by bypassing the given API? I mean, not every software problem has to be solved with software.
- mothsonasloth 8y agoSince ES6 it seems like the language is having an identity crisis. Trying to cherry pick OO concepts here and there. If Javascript is determined to become fully object oriented, then it might as well just adopt the tried and true concepts in C++/Java for encapsulation. This just seems like a painful and less verbose way of forcing encapsulation. I can appreciate Ruby and Python users might not be happy with this convention but this is going to end up in tears I think, maybe not PHP level but still...a mess!
- camgunz 8y agoAccessing it outside its class body shouldn't be a SyntaxError.
- Twisol 8y agoIt makes me wonder what would happen if they tried `counter[“#value”]`. Hopefully still an error, but also hopefully not SyntaxError, because it certainly isn’t one.
- oaiey 8y agoI always understood that some of the JS language quirks are due to their humble beginnings. Nowadays however I expect professional decision making. In 2018 I expect that a language which in many other regards follows the C++ language syntax style (semi colon, curly braces, double equality, ...) follow also expectations like that private fields are declared with a private keyword and not some strange new syntax form. Disappointed!
- Twirrim 8y agoMaybe I'm misunderstanding something here. This reads like Google is now attempting to dictate the direction Javascript goes in, by implementing proposals before they've become standards, and shipping them in their browser. Given the dominance of the browser engine, it effectively sets the direction of the language, particularly if people start to use it (which they will). This is feeling like IE6 all over again. We're getting non-standard implementations of standards, that will further encourage websites to be "Chrome only".
- mkozlows 8y agoImplementing proposals before they become standards is totally normal and a good way to prove out the proposal. Google's implemented tons of proposals, and generally pulled out the ones that didn't become standardized.
- magicalist 8y ago> implementing proposals before they've become standards, and shipping them in their browser. Is that like commenting before knowing how the TC-39 standardization process works? :P The proposals are Stage 3. To reach Stage 4 and be complete, there have to be actual, multiple implementations shipping[1]. As the spec page notes, implementations are also almost done in both Firefox[2] and Safari[3]. [1] https://tc39.github.io/process-document/ https://tc39.github.io/process-document/ [2] https://bugzilla.mozilla.org/show_bug.cgi?id=1499448 https://bugzilla.mozilla.org/show_bug.cgi?id=1499448 [3] https://bugs.webkit.org/show_bug.cgi?id=174212 https://bugs.webkit.org/show_bug.cgi?id=174212
- dragonwriter 8y ago> This reads like Google is now attempting to dictate the direction Javascript goes in, by implementing proposals before they've become standards, and shipping them in their browser. You seem to be proposing a Catch-22 that would freeze JavaScript forever: no one should implement a feature before it is a standard, but completing the process to become a standard requires implementations to exist. Therefore, no new feature can ever be implemented or become part of the standard.
- kevindqc 8y agoThe JS syntax seems to become weirder and weirder to me lol. ::, |> and now #
- BillinghamJ 8y agoThat's the unfortunate reality of web compatibility ️
- vikingcaffiene 8y agoNot gonna mince words. The hashtag syntax is hot garbage. If you need this kind of functionality just use a super set language like TypeScript. It looks and behaves exactly like you would expect.
- BillinghamJ 8y agoAlthough TypeScript is intended to be a superset of JS, it isn't always. There have been occasions where JS features were not usable via TS due to existing incompatibles/differences in implementation of new JS syntax. Really it is a different language.
- becausereasons 8y agoI've seen very few people outside of TC39 express a need for "truly private" fields in JS, and I've seen ever fewer offer positive comments about the syntax. On the other hand, I've seen a good amount of bellyaching about it. I think cramming a fairly unpopular proposal (the #) into a genuinely popular one (class fields) and calling it a day is going to make some folks pretty unhappy. ...at any rate, I was unimpressed with the sigil when I first saw it, and that hasn't changed. I've resigned myself to throwing it in the bin of JS features that I won't be using, like `with`, `eval` and `==`.
- aaaaaaaaaab 8y agoTLDR: Another layer on an already enormous pile of dung, aka the world’s most popular programming language! It’s not even ironic at this point.
- dang 8y agoPlease keep programming language flamewars off HN, regardless of how bad a language is or feels. https://news.ycombinator.com/newsguidelines.html https://news.ycombinator.com/newsguidelines.html
- shiado 8y agoHow does this work with JSON.stringify? Could I convert an object to a string and then scan the string to get the value of the private fields? (I am not great at the details of JS correct me here)
- Roboprog 8y agoThat’s actually a pretty good question. It’s probably in the spec, which is probably long :-)
- lioeters 8y agoLooks like JSON.stringify will not reveal a private field, based on this line from the spec: "What do you mean by "encapsulation" / "hard private"? It means that private fields are purely internal: no JS code outside of a class can detect or affect the existence, name, or value of any private field of instances of said class.." https://github.com/tc39/proposal-class-fields/blob/master/PRIVATE_SYNTAX_FAQ.md#what-do-you-mean-by-encapsulation--hard-private https://github.com/tc39/proposal-class-fields/blob/master/PR...
- jeklj 8y agoI am not sure it is possible any longer for JS to avoid getting larded up with a bunch of features from other languages, due to the popularity it has achieved. But one of the things I used to like about it was its relatively constrained feature set. (I would almost say simplicity, but some of the wackier aspects of the language prevent me from going that far.) Now we have things I’m not sure anyone even uses like Symbols. (Please don’t tell me I can just constrain the code I write to the subset of features I care about. We all read more code than we write.)
- drzaiusx11 8y agoHere's the issue where dropping '#' syntax is being discussed: https://github.com/tc39/proposal-class-fields/issues/177 https://github.com/tc39/proposal-class-fields/issues/177
- ajkjk 8y agoIf they were going to use a new syntax for private members, why not a minus sign: class { -privatefield }? At least there's some precedent for that, and it's already a token in the grammar which currently has no meaning inside a class declaration. Also: another poster added that private members should just be closed over in functions. Well, I don't find it productive to condemn classes as as a concept, but if JS already has classes being syntactic sugar for a type of methods, it makes sense that private members would be sugar for closed-over variables also.
- randomsearch 8y agoTo reiterate what others said, choosing an unusual syntax that is non-obvious motivated by a synthetic example to solve a problem already solved by many other languages in better ways almost raises the suspicion that we’re deliberately trying to make JS even worse... to kill it? Or is this just indicative of the process that got us to this mess in the first place? A more reasonable policy for JS would be to (a) contain it - no more changes, no more extending its use outside of its current surface, (b) the development of an alternative approach that would - crucially - support competing languages so that we don’t get stuck in this way again, (c) gradually shrinking eliminating JS with a goal to complete retirement.
- BillinghamJ 8y agoYou know a lot of people actually like JS right? The second paragraph you wrote seems to indicate that you believe people only use JS because they're forced to - since browsers don't support anything else. That's not the case. People choose to use JS in all sorts of places where they could make use of many other options. Development of the JS spec is complicated somewhat by the strict rules of web compatibility. But imo the benefits of that compatibility guarantee far outweigh the downsides. Having slightly ugly/unusual syntax is not a major issue.
- randomsearch 8y agoYou’re right, I have assumed that people only use JS because they have to. Happy to be convinced otherwise - please respond: Other places - I guess you mean Node, and VS Code and Electron etc? I’ve always assumed that was either because of the available skill set (web devs know JS, so make their tools on JS) or to reuse JS on the web and elsewhere. So not because it’s a good language, but because people know it or solutions exists in it. Is that what you meant? To me, Node (for example) makes sense only if your devs don’t know other languages or you want to hire cheaply - I’d always go for a “proper” (better designed, more stable, elegant, robust) language on the backend given the choice.
- BillinghamJ 8y ago
- fsnarskiy 8y agoWhy? I feel like the person who proposed this is relatively young and newer to coding. The reason why i say this is the functionality he is proposing can already be done using one of the myriad of JavaScript design patterns - https://addyosmani.com/resources/essentialjsdesignpatterns/book/ https://addyosmani.com/resources/essentialjsdesignpatterns/b... It can already be done in a clean and easy way with a an anonymous self executing function - (function(){//EVERYTHING HERE IS PRIVATE SCOPE})(); this also has massive added benefits to execution time and variable name resolutions. Learn more about variable scopes and how powerful JavaScript is. Also recognize that JavaScript is much closer to a functional programming language than a typical Object oriented language. If u are going to try and make JavaScript objects try and behave like classes that you know and love from java, you are gonna have a BAD time. its going to take way longer to code, gonna be hard to maintain and reason about it. Try instead to write asynchronous event driven code where functions pass data around rather then data passing functions around. Also it is really dumb trying to set private/public fields in JavaScript code that runs in the browser, i can still easily access all the variables through a debugger or running in a custom environment( like Selenium). and if your concern is about keeping that data safe in a server environment.. well then your really shouldn't rely on private/public to keep you safe and put in actual user role management and access at the application level, and one of the best way to do that is utilize a graph database to store and resolve complex user roles and permissions in your application.
- BillinghamJ 8y agoMaking classes (or equivalent) in the way you propose - ie "make use of closures for private instance fields" - does not work well. It requires allocating a new copy of each of the class's methods every time the class is instantisted, working around the prototype system. If we're arguing about crappy misuse/abuse of JS and "doing it wrong", surely this is far worse?
- Roboprog 8y agoI would be interesting to see exactly how much stuff is copied by the various implementations in such cases. There are obviously some stack or other data frames that have to be captured somehow, but the code itself should in principle be something the VM makes a single copy of with references to in each object using it as a property. (Internally within a Function type reference, separate trackers for the instructions vs the bound data)
- danShumway 8y agoAm I the only person who's really stinking annoyed that Chromium is just randomly shipping features that haven't gone through the W3C? Didn't we learn anything from the early days of CSS and browser flags? Didn't we learn anything from flexbox? Don't call it a proposal if you already have plans to ship it. Private fields haven't been accepted as a standard yet. They should not be shipped except behind a browser flag.
- Roboprog 8y agohttps://en.m.wikipedia.org/wiki/WHATWG https://en.m.wikipedia.org/wiki/WHATWG Good or bad, that is the governing body the browser makers honor.
- danShumway 8y agoFair point; I get mixed up, since both organizations are pretty active and proposals are often submitted to both. Regardless, even in this case this proposal is being submitted to TC39[0]. It's in stage 3 of 4[1]. Stage 3 proposals should not be shipped on by default. There still may be spec changes between a stage 3 and stage 4 proposal. [0]: https://github.com/tc39/proposal-class-fields https://github.com/tc39/proposal-class-fields [1]: https://tc39.github.io/process-document/ https://tc39.github.io/process-document/
- Roboprog 8y agoGotcha. Didn’t know about TC39 for the ES language concern distinct from web / browser stuff.
- BillinghamJ 8y agoFirst, the definition of JS has nothing to do with W3C. (Also for HTML, nobody really cares what W3C thinks anyway) Second, the rules of how JS is standardised is that changes are actually not allowed to go into the final spec until at least two major players implement support. So this is _exactly_ how it's meant to be done. A substantial amount of discussion and consideration has already happened prior to this point, as well as implementations into transpilers (eg Babel) which people have been using for some time. This comment explains a bit further: https://news.ycombinator.com/item?id=18676717 https://news.ycombinator.com/item?id=18676717
- horstschneider 8y agoPrivate fields in ECMAScript now look like commented out class attributes in Python. Cumbersome for someone who unfortunately has to program in both (guess which of those two makes it unfortunate :D)
- atombender 8y agoA huge (from my perspective, at least) unsolved problem with the private members proposal is that you can't use it to build immutable objects, not realistically. Without private members I can write something like: class Fruit { constructor(props = {}) { Object.assign(this, props) Object.freeze(this) } withSize(size) { return new Fruit({...this, size}) } } Now I can do: fruit = new Fruit({kind: 'apple'}) // Later: saveFruitToDatabase(fruit.withSize(20)) This pattern works great, overall, though it isn't performant. With private members, you'd think you could declare them and also update objects using transformations. But private members don't work with Object.assign(), .entries() etc., and aren't introspectively at all. So you can't write withSize() to do partial updates without spelling out all the field names, every time. Turns out it's quite hard to write robust, performant immutable code in JS. (Yes, I know immutable.js has Record. However, it's not compatible with getters and setters.)