It is a common practice in programming to create private properties only accessible from within an object - why? Is it for safety/security reasons?
1 Like
This article might help you with your answer: Implementing private and protected members in JavaScript
2 Likes
Hi carpben,
private attibuts are a pattern of object oriented programming.
In OOP you have encapsulation. This means that your object is hidden for the outside. To have access to your attributes you have Getters and Setters. This methods are a part of your API.
The reason is beacause it is safty
I made a fiddle for the example bellow
Example in C#:
class Person {
/**
* attributes
**/
private double height;
private double weigth;
private int age;
private string hairColour;
/**
* create Getters and Setters (in C# called Properties) with this syntax:
* public datatype Property {
* get { return attribute; }
* set { atributte = value } //value is a keyword in C#
* }
**/
public double Heigth { //is readonly
get { return height; }
}
public double Weigth { //can't read from outside
set { weigth = value; }
}
public int Age { //normal
get { return age; }
set { age = value; }
}
public string HairColour { //controlled set --> for securety
get { return hairColour; }
set {
if(hairColour != "red"){
hairColour = value;
}
}
}
/**
* Constructor
**/
public Person(double heigth, double weigth, int age, string hairColour) {
this.height = height;
this.weigth = weigth;
this.age = age;
this.hairColour = hairColour;
}
}
somewhere in your programm:
Person peter = new Person(1.90, 86, 21, "black"); //create a object of class Person called peter
peter.Height = 1.50; //error --> no set for height
Console.WriteLine(return peter.Weigth) //error --> no get
peter.HairColour = "red"; //error --> everything is allowed instead of red
1 Like
Thanks for your answer. I don’t know C, so I have a followup question - How would you change the weight of (the object) peter?