Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

what if i keep my class members are public?

Tags:

c++

python

In c++ instance variables are private by default,in Python variables are public by default

i have two questions regarding the same:-

1: why Python have all the members are public by default?

2: People say you should your member data should be private what if i make my data to be public? what are the disadvantages of this approch? why it is a bad design?

like image 218
anish Avatar asked Jan 20 '26 15:01

anish


2 Answers

You can use a leading underscore in the name to tell readers of the code that the name in question is an internal detail and they must not rely on it remaining in future versions. Such a convention is really all you need -- why weigh the language down with an enforcement mechanism?

Data, just like methods, should be public (named without a leading underscore) if they're part of your class's designed API which you intend to support going forward. In C++, or Java, that's unlikely to happen because if you want to change the data member into an accessor method, you're out of luck -- you'll have to break your API and every single client of the class will have to change.

In Python, and other languages supporting a property-like construct, that's not the case -- you can always replace a data member with a property which calls accessor methods transparently, the API does not change, nor does client code. So, in Python and other languages with property-like constructs (I believe .NET languages are like that, at source-code level though not necessarily at bytecode level), you may as well leave your data public when it's part of the API and no accessors are currently needed (you can always add accessor methods to later implementation releases if need be, and not break the API).

So it's not really a general OO issue, it's language specific: does a given language support a property-like construct. Python does.

like image 195
Alex Martelli Avatar answered Jan 22 '26 03:01

Alex Martelli


I can't comment on Python, but in C++, structs provide public access by default.

The primary reason you want a private part of your class is that, without one, it is impossible to guarantee your invariants are satisfied. If you have a string class, for instance, that is supposed to keep track of the length of the string, you need to be able to track insertions. But if the underlying char* member is public, you can't do that. Anybody can just come along and tack something onto the end, or overwrite your null terminator, or call delete[] on it, or whatever. When you call your length() member, you just have to hope for the best.

like image 45
Dennis Zickefoose Avatar answered Jan 22 '26 04:01

Dennis Zickefoose



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!