Is it an good idea to make a wrapper specifically for a DateTime that respresents Now?

Posted by Dirk Boer on Stack Overflow See other posts from Stack Overflow or by Dirk Boer
Published on 2014-06-01T15:11:53Z Indexed on 2014/06/01 15:25 UTC
Read the original article Hit count: 119

Filed under:
|

I have been noticing lately that is really nice to use a DateTime representing 'now' as an input parameter for your methods, for mocking and testing purposes. Instead of every method calling DateTime.UtcNow themselves, I do it once in the upper methods and forward it on the lower ones.

So a lot of methods that need a 'now', have an input parameter DateTime now.

(I'm using MVC, and try to detect a parameter called now and modelbind DateTime.UtcNow to it)

So instead of:

public bool IsStarted
{
    get { return StartTime >= DateTime.UtcNow; }
}

I usually have:

public bool IsStarted(DateTime now)
{
    return StartTime >= now;
}

So my convention is at the moment, if a method has a DateTime parameter called now, you have to feed it with the current time. Of course this comes down to convention, and someone else can easily just throw some other DateTime in there as a parameter.

To make it more solid and static-typed I am thinking about wrapping DateTime in a new object, i.e. DateTimeNow. So in one of the most upper layers I will convert the DateTime to a DateTimeNow and we will get compile errors when, someone tries to fiddle in a normal DateTime.

Of course you can still workaround this, but at least if feels more that you are doing something wrong at point. Did anyone else ever went into this path? Are there any good or bad results on the long term that I am not thinking about?

© Stack Overflow or respective owner

Related posts about c#

Related posts about dependencies