I may have mentioned before that I have started to use the C# language. Overall it isn't bad - it uses static typing, which I have always found irksome, but the language is reasinably expressive and compact compared with something like Java or C++. Because it is heavily promoted by Microsoft there are any number of tutorial and example web sites, not all of them by programming experts.
Somehow the Java message that it's bad to allow direct access to instance and class attributes appears to have permeated the C# world, I have no idea why. I have just been reading
one of the better-written tutorials, which offers the following code as an example if instance creation and manipulation.
static void Main(string[] args)
{
Person Michael = new Person();
Person Mary = new Person();
// Specify some values for the instance variables
Michael.Age = 20;
Michael.HairColor = "Brown";
Mary.Age = 25;
Mary.HairColor = "Black";
// print the console's screen some of the variable's values
Console.WriteLine("Michael's age = {0}, and Mary's age = {1}",
Michael.Age, Mary.Age);
Console.ReadLine();
}
As code goes that isn't bad, and apart from the different comment styles and the declarations it could almost be Python. Unfortnately the author has tasted the Java Kool-Aid, and shortly after this example writes
So each object now contains different data. Note that we directly accessed the variables and we put any values we wanted, right? But wait there is a solution to this problem. We will use properties.
There is no attempt to explain what the "problem" is, and you will probably not be surprised to learn that the "solution" involves making the attributes private to the class and then providing public getter and setter methods for instance users. This turns a five-line class declaration into a 32-line one (though to be fair to the author, he does at least include checking code that demonstrates the value of properties in applying class-based logic during assignment).
I have now read any number of texts where instead of something like
class Person
{
public int Age;
public string HairColor;
}
that allows direct access to the instance variables by client code, readers are encouraged to write horrendous code like
class Person
{
private int age;
private string hairColor;
public int Age
{
get
{
return age;
}
set
{
age = value;
}
}
public string HairColor
{
get
{
return hairColor;
}
set
{
hairColor = value;
}
}
}
which actually offers no benefit over the short version at all. Python users are used to accessing attributes directly in their code, which clearly has performance benefits, and then implementing properties if and when they are required to add logic to the setting or retrieval of attribute values. I just wish that C# users could see that empty getters and setters offer no measurable benefit over direct access to attributes.