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.
You're asking about and demonstrating 2 different things.
I like your second code variant better, you have 1 variable not 2 that are co-dependent. The first piece of code may have more problems as you have more state to manage to signify the same exact thing.
I think the root thing that you're asking about is: Is it ok to use a magic value instead of a separate variable? It depends on your situation, but if you are guaranteed that the magic value (null in this case) can't be used otherwise to signify anything else, then go ahead.
When you would use the first variant of code that you gave:
If you can have a null value even if an object is found, and you need to distinguish that between actually finding a customer or not, then you should use the 2 variable variant.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With