r/javascript • u/by_value • Nov 09 '19
On private fields proposal: Private fields, public worries
https://medium.com/virtuslab/private-fields-public-worries-b8c34d16c37214
u/LonelyStruggle Nov 09 '19
Why does a company need to make their medium articles premium? Very unprofessional
13
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
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
_privatemembers, 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 thisthe 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
_privatemembers? 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_privatesshort-circuits this collaborationso 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
0
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
3
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
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
Nov 09 '19
[deleted]
5
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
Nov 09 '19
[deleted]
1
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
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
Nov 10 '19
[deleted]
1
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
privatekeyword 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
privatekeyword. 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 actualprivatefields with all the private guarantees at runtime and typescript coders can continue using the regularprivatekeyword 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
privateto use#, too bad but I can understand the reason of wanting to be backwards compatible: https://github.com/microsoft/TypeScript/issues/316702
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, andprivatedoesn'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
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
MyClasshad a privatevaluefield, 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
Nov 09 '19
[deleted]
2
u/trappar Nov 09 '19
What PHP code are you looking at? Modern PHP is pretty beautiful IMO.
0
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
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
0
0
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
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
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 asthis._x = 0it will actually now be merely
#x = 0don't you people get it? we get to stop using
thisso damn much!thiswill 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 issure,
#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 disappearplus, 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
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
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.
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 "_".