To give an example, I have seen a lot of C# code such as the following:
XmlNode n = GetXmlNode();
String[] attributes = new String[n.Attributes.Count];
for (int x = 0; x < n.Attributes.Count; x++)
{
//do something
}
Now, if this were java, we could write code similar to the following, but we would be guilty of calling the getAttributes() method twice, and if I am not mistaken there is a rule that says that instead of calling the same method multiple times, just declare a variable to hold a reference to the object returned by the method call and then use that variable as many times as necessary.
Node n = GetXmlNode();
String[] attributes = new String[n.getAttributes().getLength()];
for (int x = 0; x < n.getAttributes().getLength(); x++)
{
//do something
}
But since a C# property is just a getter method and a setter method encapsulated in one type member, does it follow that the same rule should be observed?
Or does the rule not apply in this case because it is “safe” to assume that calls to C# properties and Java get methods in standard libraries just return references to fields rather than perform intense labor?
It depends if there is some computation to get the value of property (I consider doing some larger computation in property getter as bad practice, but you can’t rely on that there is no such property).
The rule is: In most of the cases you will be ok calling property multiple times. …but who knows, who implemented that god damn performance killer property, just because it was available to do it in that way….
Good – automatic property
is compiled to getter/setter like in java:
You will get little or no performance hit calling such property multiple times. It is similar to calling basic getter/setter methods in java.
Bad – some computing is involved to get value of property
It is better to avoid calling such properties multiple times. (Regardless that such kind of properties should be refactored to methods, because they behave like one)