Don’t Use The Date Object
And you shouldn’t use it.
By that I mean, you shouldn’t use it directly.
Because the date and time is an interaction with an exterior system. Because of how languages incorporate them into basic functionality, we have a hard time seeing that, but you should view it the same way you view the HTTP call that charges a credit card. Would you access the XMLHTTPRequest object directly from your code and hardcode in the URL to charge a credit card? No. You abstract that into its own functionality.
There are two reasons we do this. The first is that the code is complex and we want to extract it to a simpler interface. That really doesn’t apply with getting a date & time. But the second reason does apply. And that reason is that extracting the functionality to somewhere else allows us to test and build our system rapidly by creating fake situations.
Let’s examine a simple application that sends you an email on Wednesday evening at 8 pm to remind you to take the garbage out. How can you test this functionality to assert that it’s working? Wait a whole week until Wednesday evening at 8 pm? Definitely not. Would you modify the system date/time on your development machine? Please for the love of all that is good and holy and bug-free don’t do that. Maybe you can make the trigger date/time configurable, and when testing, keep setting it to 1 minute from now. Even that isn’t the best idea. To test you’ll have to keep changing settings in your development data store.
Instead, imagine you coded your system something like this (I’ll use a bit of pseudocode):
There are other ways to make this work. You can treat the IsTimeToSendEmail as the abstraction that you fake. You don’t need to wrap all the functionality of your built-in Date object. But whatever you do, use an abstraction.
This is the proper way to use the current Date/Time functionality in a system.
Most developers don’t automatically see the current date/time as an external system, but it is. So abstract accessing it away in its own function/class/service/whatever makes your code easier to write, read, and maintain.
Signup for my newsletter here.
Visit Us: thinkster.io | Facebook: @gothinkster | Twitter: @GoThinkster