Private Methods vs. Functions question


#1

So, I got past a few exercises on private methods but still can't take this question of my head. It may be a dumb question, but still....

Instead of writing several lines to access a private method, why not use a normal function? Or even, why not write a normal method instead of a private one in the first place?
I understand the difference between functions and methods (methods are specific to class, they access data within objects).

But truly I don't understand the purpose of private methods, if someone could explain it to me, I'd be eternally grateful.

Edit:
Maybe if I can get specific help, I'm stuck in exercise 25. Private Methods, and don't understand it at all....


#2

You make a lot of great points and your confusion is an indication that you actually DO understand the purpose of privacy to a degree.

Privacy matters most if you're creating software that other people will be able to use in their projects to achieve certain things. You want them to be able to use your code without accessing internal variables that would break things. Maybe you wrote a program that will parse text and apply correct french language accents to words (bear with me).

You want this software to be easy to use so you provide some concise, public methods that the users of your software will call to do the work. Typically these methods manipulate data in a specific predictable way. They'll probably utilize a bunch of private functions to access private variables and do the real work. In essence you're hiding the complexity behind an easy to use veil.

You DON'T want the users of your program to interfere with those hidden processes so you make them private, inaccessible from the outside.

The problem here is that JavaScript does not come with a built in way to explicitly write private functions so you start to work with closures to achieve something similar.

Honestly, I don't like the exercises that you're referencing. They don't seem to do a good job explaining the need or use of private members but they try and hopefully soon we'll see a rollout of the new Javascript course!


#3

Oh thank you very much!
To me, your example was way easier to understand, since it looks like a real life problem...
Now it makes sense to me.
I mean, I get the reason why Codecademy make incredibly simple, yet weird examples. However, I greatly miss "real-life-like" problems in this JS course, specially in this Introduction to Objects II.
Anyway...
You helped me a lot, sir! Great answer :slight_smile:


#4

This topic was automatically closed 7 days after the last reply. New replies are no longer allowed.