Variables, methods and classes can receive various security levels. From my C# experience, there is:
public
internal
protected
protected internal
private
Now, I understand the use of making methods and classes private, or internal or protected, but what about variables? Even if I make a variable private, I can use a Property to call it from a different class.
I've always been thought that Properties are best-practice. So if I can use that, I don't need to call variables directly via an Instance.
Is there any reason not to make a variable private?
EDIT: I see some people talking about Properties as if they are nothing more than Glorified public variables
Quick reminder: public variables return just their value. With properties, you can do more. For instance:
public int AmountOfBooks{
get {
//code to check certain conditions
//maybe trigger an event while we're at it.
//and a few conditionals.
return this.amountOfBooks;
}
set {
//a few conditionals
//maybe trigger an event
this.amountOfBooks = value;
//and I can do even more... I think, never tried this.
}
}
Those of you who've read my profile know I'm a student. Using properties as "glorified public variables" is something I see a lot of fellow students do. The most common response when telling them they can do this is: "Is that allowed?"
Off the top of my head, I can think of two places where I would use public fields
for example, if you had a class with attribute id_code.
if the attribute is public I can set this variable with any type of value.
if you delcare this id_code private and you make a method for set it, you can make a rules about the format of id_code. And so the method:
this is a first simple example.