Forum > Beginners

declaration public - private

(1/4) > >>

Nicole:
Something I saw that often, but never understood:
What are the reason / advantages to declare something public or private?

Handoko:

--- Quote ---It is considered good programming practice to make the scope of variables as narrow as feasible so that different parts of a program do not accidentally interact with each other by modifying each other's variables. Doing so also prevents action at a distance.
--- End quote ---
Source: https://en.wikipedia.org/wiki/Variable_%28computer_science%29#Scope_and_extent

If you only write programs that have hundred lines of code, you may not know the difference. But if you have a project of thousand lines of of code, using multiple files, you will know the difference.

I believe you meant public and private declaration in class. Basically they are similar to global/local variable. You can try to write a large project that has thousand lines of code and using only global variables. Do it and you'll know the code is extremely hard to maintain and debug. Same happens on class too. Make the visibility as low as possible, that will prevent you to make silly bugs, the code is more readable, easier to maintain and debug.

SymbolicFrank:
I tend to only make things private if I really don't want them to be used, like an inherited constructor. Everything else that shouldn't be used directly is protected, and if it is a method, most often virtual. So classes that inherit them can change them if needed.

Most often this is used to add extra functionality.

marcov:

--- Quote from: Handoko on July 26, 2022, 02:27:43 pm ---Make the visibility as low as possible, that will prevent you to make silly bugs, the code is more readable, easier to maintain and debug.

--- End quote ---

I think it is less (though not zero) useful for one programmer projects, and more that it conveys a certain intentions for code written by teams.

MarkMLl:

--- Quote from: marcov on July 26, 2022, 03:55:31 pm ---I think it is less (though not zero) useful for one programmer projects, and more that it conveys a certain intentions for code written by teams.

--- End quote ---

I'm afraid I disagree. Even a single-programmer project can benefit from being forced to explore /why/ something needs to be made public, and from being forced to check whether it was originally private due to e.g. the possibility of a race condition. In addition, since a one-person team doesn't have the option of coopting a colleague for even a cursory code review, the more he can get the development environment to help the better.

Quite frankly, and speaking with the experience of having done x86 protected-mode bare-metal work, I'd prefer to see more checks rather than fewer. For example, "this is a public function, but should only be called by members of this list of units (or threads etc.)".

MarkMLl

Navigation

[0] Message Index

[#] Next page

Go to full version