Jan 12, 2012

A case in favor of private variables and functions

I just read "A case against private variables and functions in JavaScript" by Miller Medeiros, and honestly I'm not sure what to think about it. I understand the reasons that made him change his mind, but I also think that encapsulation is one of the most important pillars of OOP.

In short, his point is to favor public variables and functions over private so anybody can jump in and hack his way into whatever he wants to do. Obviously, if I have a private member you can't change its value from the outside, so you will be screwed...

But that's exactly what I'm trying to do.

Marking a member variable or function "private" is a design decision as important as properly organizing your class hierarchy. You can't just go "all private until I need public". It's way more complicated than that. Mastering it requires experience and knowledge, and there's no a rule of thumb to do it.

Going the other way around (fuck it, let's make everything public!) it's even worse. Giving everybody control over the internal state of a class is the worst decision we can make (no, we are not grown ups). I've been around for enough time to know what happens when developers start messing with the values of public fields. Suddenly things stop working and nobody can figure out why.

Resuming, you should pay special attention to what you make public on your classes: if you want other developers to overwrite the behavior of your functions, then fine, make them public. If something is interesting only for your class, then make it private. Never ever sacrifice encapsulation because of what could happen tomorrow.

As a bonus, IMO variables should never be public. If you want to grant access to the value of a variable outside your class, create a function to access it.

I know what Miller is doing in his code, and I think he is doing it perfectly fine. Problem is that he might was a little bit bold in some paragraphs of his post. Or maybe I freaked out when I read the title. Who knows.