tc39 / proposal-private-methods

Private methods and getter/setters for ES6 classes
https://arai-a.github.io/ecma262-compare/?pr=1668
345 stars 37 forks source link

How does the private fields interact with the Proxy? #34

Closed baptistemanson closed 6 years ago

baptistemanson commented 6 years ago

Hi all,

In Java, we can test private methods via Reflection. In PHP, we cannot test private methods. 30 PHP engineers in my company feel like in practice they need to test some private methods.

The usual consequences of a limitation like in PHP are:

The infamous "private" __SECRET_DOM_DO_NOT_USE_OR_YOU_WILL_BE_FIRED from React was used in Unit Testing as well if I'm not mistaken.

Is there any possibility to avoid this situation in JS? Like being able to access private methods with proxies/any other mean?

bakkot commented 6 years ago

No, this proposal does not expose any mechanism for accessing private state or methods from outside the class. The tradeoff between encapsulation and reflection was discussed at length, for example in this thread, and ultimately we came down on the side of encapsulation.

Incidentally, one of the major features of Java 9, modules, was motivated in large part by the goal of allowing authors to prevent consumers from accessing their private state via reflection.

jridgewell commented 6 years ago

The current “hard private” disallows this.

However, you’ll be able to use decorators to expose private fields publicly:


class Example {
  @visibleForTesting
  #x = 1
}
baptistemanson commented 6 years ago

Decorators seem to be pretty elegant for this. Thanks!

littledan commented 6 years ago

Closed as it seems like decorators resolve the concern satisfactorily. Thanks for explaining the existing proposals and plans, @bakkot and @jridgewell .