A function (or any discrete block of code) can be considered as having various forms of "correctness" or "safety", for example if a function does not access or mutate any shared-state (or does so safely, e.g. using locks) then it is deemed "thread-safe". In C++, a function is "const-correct" if only the absolute minimum parameters lack the const
modifier, and "type-safety" means the function does not rely on late-binding or dynamic behavior which could cause member-access fail at runtime.
Now consider a function which takes the value of "now", e.g. System.DateTime.UtcNow
in .NET:
public static Resource CreateResource() {
Resource ret = new Resource();
ret.Created = DateTime.UtcNow;
ret.Modified = DateTime.UtcNow;
return ret;
}
The bug here is that the value of UtcNow
could change between setting .Created
and .Modified
, so the two property values would be different, implying that the resource has been modified after it was created.
The correct implementation would cache the initial value of UtcNow
so that the values of the two properties are guaranteed to be identical:
DateTime now = DateTime.UtcNow;
Resource ret = new Resource();
ret.Created = now;
ret.Modified = now;
Or alternatively:
Resource ret = new Resource();
ret.Modified = ret.Created = DateTime.UtcNow;
return ret;
What is the term to describe this "correctness"? I thought of "time-correct" or the slightly more pretentious "temporally-correct" or "chronologically-correct" but I wonder if those terms might imply something else.
var r = new Random(); var a = r.Next(); var b = r.Next();
and expectinga == b
to be true.DateTime.Now
directly is really really really cumbersome to test. it's like newing up a db connection or doing disk IO. hard dependencies that belong in a higher layer.