I have read that a variable should never do more than one thing. Overloading a variable to do more than one thing is bad.
Because of that I end up writing code like this: (With the customerFound variable)
bool customerFound = false;
Customer foundCustomer = null;
if (currentCustomer.IsLoaded)
{
if (customerIDToFind = currentCustomer.ID)
{
foundCustomer = currentCustomer;
customerFound = true;
}
}
else
{
foreach (Customer customer in allCustomers)
{
if (customerIDToFind = customer.ID)
{
foundCustomer = customer;
customerFound = true;
}
}
}
if (customerFound)
{
// Do something
}
But deep down inside, I sometimes want to write my code like this: (Without the customerFound variable)
Customer foundCustomer = null;
if (currentCustomer.IsLoaded)
{
if (customerIDToFind = currentCustomer.ID)
{
foundCustomer = currentCustomer;
}
}
else
{
foreach (Customer customer in allCustomers)
{
if (customerIDToFind = customer.ID)
{
foundCustomer = customer;
}
}
}
if (foundCustomer != null)
{
// Do something
}
Does this secret desires make me an evil programmer?
(i.e. is the second case really bad coding practice?)
I think you’ve misunderstood the advice. In that case, you’re only using the variable for one purpose – to store the customer being searched for. Your logic checks to see if the customer was found, but doesn’t change the purpose of the variable.
The “don’t use variables for more than one thing” is aimed at things like “temp” variables that store state for ten different things during the course of a function.