Sat, 03 May 2003
class Mumble def do_something(...) ... ... Time.now ... # Time.now gives current time. ... end end
The conventional answer is that time should be a variable, not (in
effect) a global. Either pass it in to
def do_something(..., now = Time.now) ... ... now ... ... end
Or, if multiple methods depend on time, add a method that changes the object's current time:
class Mumble def set_time(time) @now = time end def now @now || Time.now # iff no time set, use the system time. end end
Or, if you're squeamish about giving clients the ability to change
I recently found myself doing something different. In Ruby, all
classes are "open". You can add methods to any of them at any time. Rather than adding a
time-setting method to
class << Time # change Time's methods alias_method :original_now, :now # save old method. def set(time) @now = time end def advance(seconds) @now += seconds end def now @now || original_now end def use_system_time @now = nil end end
My tests look like this:
def test_active_time_extends_over_day job 'oldie' Time.set(Time.local(2002, 'feb', 28, 14, 30)) start 'oldie' ... assert_equal("'oldie', with 24.00 hours from 02002/02/28 2:30 PM.", result) end
This is more convenient than running around telling a bunch of objects or methods what time they should be thinking it is. Instead, I tell everything what time it should be thinking it is. It's worked out rather well. I've not encountered a case where, say, I want two different objects in the same test to have different notions of "now".
That's not to say I don't use the more traditional ways for things like telling objects what servers they're talking to. But, in the case of time, there's already a global notion of "now" defined by your language. By introducing object- or method-specific notions of "now", you're violating Occam's Razor (in the "do not multiply entities unnecessarily" sense). What do I mean by that?
You can simply declare there is
no global variable that an object can query to find out which server
to use. If an object wants to know, it has to be passed the server or
an object it can query for the server. You cannot similarly declare
It simply seems less error-prone to have a single source of time information that all code must use. Then, for testing, we treat the assembled product or any piece of it as a brain in a vat, unable to tell whether it's interacting with the real world's time or a simulation.
More generally, we need to be able to control all the product's perceptions. For this, it seems we need language/substrate support of the type Ruby allows. I believe this was also once a property of Community.com/Combex's Java Vat (hence the name), but I'm not sure if that's true any more.