DEV Community

Pacharapol Withayasakpunt
Pacharapol Withayasakpunt

Posted on

What's the best way to do encapsulation?

  • 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)

lexlohr profile image
Alex Lohr

It is possible to have the equivalent of private fields inside a closure in plain old JavaScript. Consider the following example:

function guessMyAge(privateAge) {
  return function(guessedAge) {
    return guessedAge === privateAge
      ? 'right'
      guessedAge < privateAge
        ? 'more'
        : 'less'

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?

  • tidy API: naming convention will suffice. At least all the private stuff will be at the top of the list and can easily be filtered. If need be you can make them non-enumerable.
  • security concerns: true private fields are the way to go.

There might be some use cases in between. YMMV.