Let's say I have some code like the following, and that processData
gets executed hundreds or even thousands of times per minute:
class DataProcessor {
private:
DataValidator* validator;
bool atLeastOneDataPoint;
bool dataIsValid(Data* dataToValidate) {
return validator->validate(dataToValidate);
}
public:
// ...
void processData(Data* dataToProcess) {
if (dataIsValid(dataToProcess) || !atLeastOneDataPoint) {
// process data
// ...
atLeastOneDataPoint = true;
}
}
// ...
}
As can be inferred from its name, atLeastOneDataPoint
is a variable that really only needs to get set once, yet in the code above it is set every single time processData
is called after the first data point. Naturally, I could change the assignment line to this:
if (!atLeastOneDataPoint) atLeastOneDataPoint = true;
But that would simply replace a bunch of unnecessary assignments with a bunch of unnecessary Boolean checks.
I'm not concerned about the performance of this code; really I'm just bothered by the idea of doing something so totally unnecessary. Is there a standard way of setting one-time switches such as this, that is more intuitively "proper" in design?
As for whether or not even caring about this makes me a bad programmer: let's leave that discussion for another day, please.