Purpose of private modifier | Sololearn: Learn to code for FREE!
¡Nuevo curso! ¡Todo programador debería aprender IA Generativa!
Prueba una lección gratuita
+ 5

Purpose of private modifier

Whats the point of having a private int when it is changeable by another public int. i mean isn't this the purpose of a private modifier?... to remain unchanged...

5th Mar 2017, 3:29 PM
Amir Hossein Karimi
Amir Hossein Karimi - avatar
7 Respuestas
+ 12
The purpose of making a variable private isn't to make it unchangeable. It is to make sure that the variable itself can only be modified by, and through that specific class.
5th Mar 2017, 4:02 PM
Hatsy Rei
Hatsy Rei - avatar
+ 12
That's basically the purpose of setters. Although other classes may be able to change the private variable of another class via the public setter, it means that the only means of modifying the private variable is through that specific setter. This may not seem to be a big deal, but when you are working on a huge project, this saves the programmer a lot of work when it comes to debugging, because it is easy to track which block of code is throwing the error.
5th Mar 2017, 4:13 PM
Hatsy Rei
Hatsy Rei - avatar
+ 8
What Hatsy Reid said + in a setter you can also validate the argument, throw an error if it's invalid and set it only if it is valid.
5th Mar 2017, 4:20 PM
Tashi N
Tashi N - avatar
+ 2
got it. thanks for the information <3
5th Mar 2017, 4:17 PM
Amir Hossein Karimi
Amir Hossein Karimi - avatar
+ 2
yea I just realised it in the next lesson. tnx
5th Mar 2017, 4:21 PM
Amir Hossein Karimi
Amir Hossein Karimi - avatar
+ 1
even when [public string Name(get; set;)] is called from another class? I mean other classes have access to a public code and they can change the private int trough this code.
5th Mar 2017, 4:11 PM
Amir Hossein Karimi
Amir Hossein Karimi - avatar
+ 1
In short, public property is "door" with filter to capsulated code. Like a gates with guardians in a castle walls. Imo.
10th Jan 2018, 11:26 AM
Paul Double
Paul Double - avatar