Is it bad programming practice to call the same C # property twice?
To give an example, I've seen a lot of C # code like 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 it is java, we could write code similar to the following, but we would be guilty of calling the method getAttributes()
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 the object reference 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 and a setter enclosed in a single type member, should the same rule be followed?
Or does the rule not apply in this case because it is "safe" to assume that C # property calls and Java getters in standard libraries just return field references rather than doing the hard work?
source to share
It depends if there is some kind of computation to get the property value (I think it is bad practice to do a larger computation in the getter of the property, but you cannot rely on the fact that there is no such property).
Rule: . In most cases, you will need to call the property multiple times ... but who knows who implemented this damn performance just because it was available to do it that way ...
Good is an automatic property
public string MyValueProperty { get; set; }
compiled to getter / setter like in java:
private string myValueProperty;
public string MyValueProperty
{
get{
return myValueProperty;
}
set{
this.myValueProperty = value;
}
}
You will get little or no performance by naming this property multiple times. This is similar to calling basic getter / setter methods in java.
Bad - for calculating property value
some calculations are involved,public string MyLongTimeToGetValueProperty
{
get
{
var res = DoSomeComputation();
return res;
}
}
It is best to avoid calling these properties multiple times. (Regardless, such properties should be refactored into methods as they behave like one)
source to share
Never store what you can calculate. Storing what you can calculate will lead to subtle errors when you change the value of the calculated value, but you are still using the stored value. Just don't obey this rule if your program is slow, which is the biggest reason it is slow (hint: it may not be).
source to share
Whenever possible, use it a second time after being assigned the first time you access it.
In your example, you can program the following:
XmlNode n = GetXmlNode();
String[] attributes = new String[n.Attributes.Count];
for (int x = 0; x < attributes.GetUpperBound(0) + 1; x++)
{
//do something
}
source to share