In python we use a leading _
to make object attributes implicitly “private”. If we want to give people set/get access we can use the @property
decorator. Or, if setting/getting is allowed and trivial, we can just make the attribute “public” by omitting the leading _
.
My colleague and I were debating about two competing philosophies:
A: “my approach in general is to have all attributes private by default. They are escalated to public when we explicitly want the API user to get/set it”
B: “another approach could be to put make attributes private when we explicitly don’t want people to use them, but default to public with the understanding that people know they shouldn’t mess with them”
I don’t have one single clear question to ask to this community. I’d just like to get thoughts. I’d accept an answer that gives more clarity into how to think of the problem.
2
Being public requires careful design and maintenance. Don’t accept that responsibility casually.
By maintenance I mostly mean not changing what you make public in any way that would break client code. Preserving that while allowing the ability to flex other things is what I mean by careful design.
My thanks to
Basilevs for asking me to flesh that out.
However, sometimes you just need to dump some data across a boundary (which is why you can’t just move all methods to where the data is in OOP fashion). In those cases sometimes we use what is (sadly) called a Data Transfer Object (DTO). This data structure makes all it’s fields public. For some, the way to meet the ‘careful design’ requirement here is to make sure the DTO has no behavioral methods. You use it by passing it into things. Mostly something else’s constructor. When used that way it qualifies as a Parameter Object.
When I say no behavioral methods I mean if it has methods at all they’re pure getters and setters that only move data. This keeps it’s focus on being a data structure that other (real) objects use.
With that in mind, when not creating a DTO, when building a behavior object, then sure, default to private. Because being public is work.
12
I’d say neither.
In Python, you don’t want to make things public that should be private (like in C++) but you also don’t want to make things private that should be public. Because if you don’t make some user-relevant property public, the users of your class will just access the private attribute. And then your “private” attribute will become part of the de-facto public API. Your users will just teach each other “if you need to know the filkiness of an Esnesnon
instance, you’ll need to do esnesnon._filkiness
. Yeah it’s not documented, but it works.”
Of course there are very good reasons why you don’t want to expose every attribute of every class, which is why I would advocate evaluating the need for underscore prefixing on a case-by-case basis.