mardi 18 février 2020

Access to private variable dependant from source code visibility. Is the javascript code always visible for the client/user in web development?

I am experimenting with the language and the new WeakMap. I am trying to implement encapsulation with WeakMap with the following example code:

  const wm = new WeakMap();

  class User {
    constructor(id,name){
      this.idProperty   = Symbol('id');
      this.nameProperty = Symbol('name');
      this.setId(id);
      this.setName(name);
    }

   setPrivate(property , value){
     let v = wm.get(this) || {};
     v[property] = value;
     wm.set(this,v);
   }

    setId(id){
      this.setPrivate(this.idProperty , id);
    }

    setName(name){
      this.setPrivate(this.nameProperty , name);
    }

    getId(){
      return wm.get(this)[this.idProperty];
    }

    getName(){
      return wm.get(this)[this.nameProperty];
    }
  }

  const user = new User(123,"Giuseppe");
  console.log(user.getId());
  console.log(user.getName());
  user.setId(456);
  console.log(user.getId());
  console.log(user.getName());

Private variables should only be accessed with set and get methods.

However with:

wm.get(user)[user.idProperty];

namely a reference to the object instance and to the WeakMap structure I can access the private variable. Bad pattern! But I'm coming from C/C++/Java world and in that field the code related to the class is compiled and thus the user/client can see alone the object code and the implementation of the class will remain hidden. Namely in those languages the client don't know that behind the scene there is idProperty therefore he can't access with wm.get(user)[user.idProperty]; In the Javascript world I'm wondering if is the same or not. Javascript is interpreted, thus the client/user can see the source code? (In the client-side the source code should be visible, but it doesn't server-side. )

(I know that above pattern is not the best pattern for encapsulation, and closure and other are there for this aim. The question is related to the "Life cycle , access and distribution" of the javascript code and no to how implement encapsulation)

Aucun commentaire:

Enregistrer un commentaire