Live data from Hacker News

Ask HN: Why do you make class members private?

news.ycombinator.com

81–90 of 117 posts

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

#81
post #78

Earlier quoted context omitted.

> A dedicated user can gain access to, and modify, everything. That may be so, but it is akin to using an undocumented system call. And good luck if that class ever gets refactored or turned into a service.

Indeed. My point was that "private" has all the strength of a "warranty void if removed" sticker.

That's a funny way of putting it, but yes, you are correct.

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

#82
As software projects grow, development really becomes an exercise in managing complexity. One of the benefits of encapsulating state and functionality into classes is to reduce the amount of coupling that can occur between components. By coupling, I mean the dependence of one component on the specific behavior or implementation details of another component.

There will always be some amount of coupling, but reducing it makes it much easier to reason in your mind about small sections of code. With good encapsulation, there are clear interfaces between components and it is difficult to use them incorrectly.

You could argue that if there are only a few or even one developer on a project, there is no harm in making everything public since everyone will just use the class "correctly". However, the "correct" way to use the class is not codified or enforced anywhere other than the minds of the developers, comments, or external documentation. All of these sources can easily fall out of sync with the actual code being written. The compiler/runtime should be used to enforce correct usage when possible. This greatly reduces the cognitive load on the developer/s since they know if the code compiles or runs without error, a whole class of bugs has already been eliminated.

I would argue that even if access controls were completely ineffective (they didn’t actually control access), they would still be useful as API documentation within the source code to point others and your future self to the set of variables and functions that should be used to interact with the class. There is a benefit to writing code that is itself expressive of intent without requiring additional documentation or knowledge.

Another reason to reduce coupling is to make it easier to re-implement a single component of the system. If the component was well encapsulated and has a clean and minimal public interface, the only restriction on the new implementation is to meet that same public interface. If the component was not well encapsulated, the new implementation may have to maintain a number of details from the previous implementation than no longer make sense just to maintain all of the unnecessary coupling that’s been created between the component and the code that uses it.

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

#83

Earlier quoted context omitted.

It's been a decade since I used C# but the corporate design pattern culture of that language back then turned me off of it forever. Everything looked like this: https://github.com/EnterpriseQualityCoding/FizzBuzzEnterpris... Maybe it's better now but the Java/C# practice of shoveling largely empty classes around with an IDE isn't something I'd point to as a good example.

Wow, what a repo. I can't even tell if the author is serious or this is some tinderbox-dry satire, bravo either way. I'm sad that I've worked with plenty of codebases that look exactly like that and I twitched a little bit browsing around. :)

You can see the exact equivalent in the Java world.

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

#84

To hide implementation details from class users. You ideally only want to have a documented interface and all implementation details should be opaque to class users. This can be quite tricky and usually classes will export some state, typically done through getters and setters. Then one day you decide you want to aggressively refactor that class. Now you can because the interface can stay the same even though you cou…

Can we acknowledge yet that the concept of classes as tiny programs with tiny APIs and private implementations has failed? Admittedly, my opinion is mainly based around working mostly in C++, but every codebase I work in of significant age is a knitted castle of interlocking classes with poorly thought out accessors and private variables. While the vision of carefully encapsulating implementation details is nice, in…

Sad to see this earnest post down-voted. Maybe you had to be more precise about the poor thought out nature of what you saw. In my experience you are right, in as much as developers whose notions of design only go so far as creating many small classes do not think enough about design...

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

#85
post #79

The reason is simple: to prevent objects from getting to an invalid state. The set of property values of an object is its state, and you can model every possible valid state and state transition. Not every state is valid. If you allow all variables to be touched willy-nilly, you allow an object to be put into an invalid state. The only variables and functions that should be public are those that cannot put an object…

> The only variables and functions that should be public are those that cannot put an object into an invalid state. That's an interesting one. So a reason to use private is to tell programmers that calling this function or changing this variable can leave the object in an invalid state? I guess invalid state then means that you can't call a public function on that object. It might not be clear what an invalid state i…

Invalid state means invalid state. Suppose (going with my bounded stack example from another reply to you) you initialize the stack with:

  a_bounded_stack = new BoundedStack(100);
There are various actions applied, correctly, through the interface (push, pop, and peek). Somewhere, you decide to manually alter the size of the stack but not through its interface (resize)

  a_bounded_stack.limit = 50;
But you forget (someone came by with cookies) to actually shrink the backing array and also to change "top". So now you end up with this state:

  a_bounded_stack
    limit = 50
    array.size = 100
    top = 60
Oops, top is not allowed to be larger than limit, and array.size is supposed to be equal to limit. That is an invalid state, people can still use the public interface (push, pop, peek), but who knows what they'll get back.

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

#86

We do it because that's how it's always been done. There is no why of OOP, there is only do.

> There is no why of OOP, there is only do. You really think that in the 50+ years of OOP and modular programming no one has considered why ? That they've really just thrown shit at the wall and seen what stuck and never considered what to throw at the wall or why it stuck?

I’m sure lots of people have considered it. But lots of people can be wrong, myself included.

We do it because it’s largely automated by IDEs now. I strongly suspect that if IDEs didn’t make it so easy to do, we basically wouldn’t bother with it. Python does OOP just fine without real visibility control.

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

#87
post #79

The reason is simple: to prevent objects from getting to an invalid state. The set of property values of an object is its state, and you can model every possible valid state and state transition. Not every state is valid. If you allow all variables to be touched willy-nilly, you allow an object to be put into an invalid state. The only variables and functions that should be public are those that cannot put an object…

> The only variables and functions that should be public are those that cannot put an object into an invalid state. That's an interesting one. So a reason to use private is to tell programmers that calling this function or changing this variable can leave the object in an invalid state? I guess invalid state then means that you can't call a public function on that object. It might not be clear what an invalid state i…

If it's intended to be in that state, then it's valid.

But following the example: if you made the player's health a public property, code could straight up just set it to a negative number. The game engine this is running in may not properly support a negative health value. If instead it was set using a public method, there can be added checks to lower bound health to zero. And depending on the architecture, all of the post death animation stuff could also be handled as a check in that function call.

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

#88
When I write a private class, I'm declaring to the world: These are the methods now available, their expected inputs, and their return types.

Anything I do inside that class that isn't marked public is an implementation detail, and might change. Given time, likely will change! But if it's not marked public, then if you want to access something in there, you'll need to think through the implications of making it public, either a new method of by adding to an existing method.

If I come along later and want to change things about those methods, I can do that freely, so long as I maintain the same input types and return types.

Internally I can change a counter from an Int to an Long, and it doesn't matter to anybody. Internally I can change the way I'm assembling a String, and that's fine. Internally I can move the definition for an interim variable to a separate function with its own tests, and that's fine. So long as I maintain the input types and return types, all is good.

If the fields and methods were public, on the other hand, then other classes might be accessing them directly, and now any change has to be negotiated with all callers. The counter needs to be changed from an Int to a Long? If it's public, you'll need to make sure that no other classes anywhere are referring to that counter and expecting it to be an Int.

Side effects are generally unwanted, and marking things as public is making everything in an implementation a side effect.

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

#89
Intent.

It says "don't call me". That might be because it might be refactored without notice, or might break the intended use of the Class.

Even in languages without formal class access control, there is convention for labelling something as externally unsafe. It's an important part of sharing code.

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

#90
post #62

Earlier quoted context omitted.

1. So the reason here to use private is as a way to tell programmers to not use a thing in too many places because then it will be hard to change in all those places if you need to change the private member? 2. First, remember that I am only interested in code that everyone has write access to so even if something is private, everyone can still change it. "This makes the class/module author responsible for controllin…

1. It's private, only internal routines can use it. You aren't telling anyone to avoid using it, you are constraining where it can be used. You can use it directly in every internal routine if you want, that's not a problem. But no one outside the class/module can directly access it so if you change it (in whatever fashion) then those outside users will not be impacted because they are only dependent on the public in…

1.

So it's not to make it easier to change things? Otherwise what's the difference, in difficulty to change things, between using a member in 20 places outside of the class and 20 places inside the class? It's the same amount of code to change if you change the member.

> But no one outside the class/module can directly access it

Everyone can access all the code.

> those outside users will not be impacted

What do you mean that they will not be impacted? If I change the internal array and all the places where it's used, nobody might even notice it. Or is the assumption that one team can only change inside the class and other teams can only change outside of the class? Remember that we assume that everyone has access to the all the code.

2.

> it's about places and the number of them.

So again, is private a way to tell programmers to reduce the number of places they use the member in so that it will be easier to change it?

Post reply on HN