- true private field (e.g. Java)
- naming convention only (e.g. Python)
- both naming convention that always means private, i.e. both true privacy and naming (e.g. Dart?, Go?)
- You don't like the idea of encapsulation?
Also, I am not sure if module level, rather than object / class level is also encapsulation?
Not sure if encapsulation encourages black box testing, and is against test coverage?
As I am using mostly TypeScript, which does have class with private field, but private is lost when transpiled to JavaScript -- so I am not sure whether to prefix with underscore? (I also had to use @internal
sometimes, which TypeScript itself doesn't support...)
I know there is another way, though -- local scope of variables and functions...
Top comments (1)
It is possible to have the equivalent of private fields inside a closure in plain old JavaScript. Consider the following example:
The same is also possible with prototypal inheritance. Why doesn't TypeScript use it? Because it expects its level of trust to come from the type checker. If you attempt to access a private field, it will emit a warning and fail to transpile your code. If you cannot trust the user of your TypeScript API, you need to hide your private fields yourself.
That being said, to answer your question: it depends on the use case. What is your rationale behind the encapsulation?
There might be some use cases in between. YMMV.