Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Javascript: should I be hiding my implementations?

As a C# programmer, I have a bit of a habit of making things private that can and should be private, and I always get a weird feeling when a JS type exposes all its private parts to me (and that feeling is not 'aroused'). Say I have a type that has a draw method, which internally calls drawBackground and drawForeground, which make no sense to be called on their own. How should I implement this?

Option 1

Foo = function(){
  this.draw();  
};

Foo.prototype.draw = function(){
  this.drawBackground();
  this.drawForeground();
};

Foo.prototype.drawBackground = function(){};
Foo.prototype.drawForeground = function(){};

Option 2

Foo = (function(){

  var constructor = function(){
    this.draw();
  };

  var drawBackground = function(){};
  var drawForeground = function(){};

  constructor.prototype.draw = function(){
    drawBackground.call(this);
    drawForeground.call(this);
  };

  return constructor;

})();

The difference, of course, being that in the first example, the drawBackground and drawForeground methods are part of the public API, while they are hidden to the outside in the second one. Is that desirable? Which one should I prefer? Am I wrong to apply my C# habits to Javascript and should I make everything extensible and override-able in Javascript? And what are the performance implications of the .call(this)?

like image 324
JulianR Avatar asked Jul 10 '10 21:07

JulianR


1 Answers

There's a well known quote amongst Perl developers that comes from the (in)famous Camel book: "A Perl module would prefer that you stay out of its living room because you weren't invited, not because it has a shotgun.". The philosophy being, if you as the developer of a library want to distinguish between your public and private API, that's great. Do that and document it. The caller of your code should know which is which, but also be free to act like an idiot if they decide to and call things you don't think they should call. From an OO background, that's heretical, but with scripting languages, that's how they roll.

The answer to this is a bit subjective, but I'll tell you that when I'm writing JavaScript and have methods or variables that would be private if I were coding in .NET, I just prefix them with something like "prv_" or "p_" or just "_"... whatever floats your boat. That way, you've told your users that this stuff is meant to be private and could change out from under them. And that way, if they choose to call your private methods anyway, that iffy code will stick out like a sore thumb.

like image 139
mattmc3 Avatar answered Nov 15 '22 16:11

mattmc3