Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

is it bad programming practice to call the same C# Property twice?

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?

like image 430
John Smith Avatar asked Feb 06 '13 23:02

John Smith


1 Answers

Never store what you can compute. Storing what you can compute will lead to subtle bugs when the computed value changes but you're still using the stored value. Only disobey this rule if your program is slow and this is the biggest reason why it's slow (hint: it probably isn't)

like image 70
Patashu Avatar answered Oct 13 '22 00:10

Patashu