When to copy to variable or not

Bernie

Well-known member
Joined
Aug 13, 2007
Messages
98
Programming Experience
3-5
As a general guideline, when do you want to copy a value to a variable vs reading it directly from the database.

For example; I have a datareader giving me the response to a database query. There is a field called PersonID. I'm testing for all odd numbers and then writing those PersonID fields to a file and outputing them to a display.

Would you copy the PersonID value for the current record into a local variable before manipulating it or would you just us the datareader reference to it?

I was always told if you touch it more than once, then assign it to a variable. But this goes back many years ago. What would be a good guideline with ADO and .Net?

Bernie
 
I still follow the old advice you were given, especially if the variable is looked up via some kind of indexed property:

myReader("PersonID")
 
I thought I'd join the debate ;)

You should target clarity. Performance doesn't matter until optimization phase. If your code is

VB.NET:
notifyNewTotal((subTotal + getShippingCost()) * (1 - getPromotionPercentage() / 100) * (1 + getTaxPercentage() / 100), orderType, shippingAddress)

Then yeah, add that new variable even if it's used only once! A variable called "total" could carry much more meaning than this whole calculation.

VB.NET:
dim total as Decimal = (subTotal + getShippingCost()) * (1 - getPromotionPercentage() / 100) * (1 + getTaxPercentage() / 100)
notifyNewTotal(total, orderType, shippingAddress)

However, if you're using customerReader("CustomerName"), the expression is just as clear as any variable name you could come up for it. It is simple enough to stay as it is.

The main idea behind my reasoning is that conventions or performance are negligible most of the time. Code clarity is almost always more important! Or more simply, CPU cycle is cheap, going to therapy isn't.
 
Last edited:
Back
Top