Live data from Hacker News

Ask HN: Why do you make class members private?

news.ycombinator.com

1–10 of 117 posts

Ask HN: Why do you make class members private?

#1
I know this is something that a lot of people do without thinking about it. So let's think about it.

I want to know the main reasons for making variables and functions in a class private. How is it better? What can happen if you don't do it?

Here are a few possible reasons that I can think of that someone could have:

* You have been taught to do it so you just do it without thinking.

* It reduces the number of files you have to search in if you want to find all uses of a member.

* The member is hard to understand so you want to discourage people from using it.

To clarify, I'm only talking about code in the same project that everyone has access to. I'm not talking about defining an API for other people to use that don't have access to the code, like when you make a library.

Re: Ask HN: Why do you make class members private?

#5
Variables should not be accessed directly outside of the object (encapsulation principle) and thus should all be private as a general rule.

Then, you will probably divide up the code into a number of separate methods for better structured code. All the methods that are purely internal and not part of the public API should be private if only to enforce the public API, this is also the encapsulation principle.

Re: Ask HN: Why do you make class members private?

#9
post #2

"With a sufficient number of users of an API , it does not matter what you promise in the contract: all observable behaviors of your system will be depended on by somebody."

Corollary:

If your programming language supports reflection, people will depend on private properties and methods regardless of what you do.

Re: Ask HN: Why do you make class members private?

#10
post #9
post #2

"With a sufficient number of users of an API , it does not matter what you promise in the contract: all observable behaviors of your system will be depended on by somebody."

Corollary: If your programming language supports reflection, people will depend on private properties and methods regardless of what you do.

People who can't accomplish something with an API because things are kept private won't be users.
Post reply on HN