Hacker News new | past | comments | ask | show | jobs | submit login

Always avoid singletons? Here's my situation: in various parts of my code I need to get the current time. Normally I would call System.currentTimeMillis() but in my test cases I need to ensure the time is a particular value. So I have a Clock singleton class which allows me to get the current time but also to 'stop the clock'.

Is it really better for me to pass the Clock instance all over the place, rather than have a singleton instance that can be referenced anywhere?




If you really want to modify global state while running a test, then you might as well use a dependency injection container and get similar behaviour, entirely generalized.

You can then have two much simpler clock classes, one for real time and one for fake time.

Personally, I prefer just passing around the clock, though - it makes dependencies between classes crystal clear.


You get the added benefit of not relying on global state. Which you have to do anyway if you want to parallelize your test suite execution.




Join us for AI Startup School this June 16-17 in San Francisco!

Guidelines | FAQ | Lists | API | Security | Legal | Apply to YC | Contact

Search: