4 ms·
Singletons solve several problems with static methods, namely that you can't change their behavior (e.g. do error logging to both the global error log and a per
by candiodari 6y ago
Singletons solve several problems with static methods, namely that you can't change their behavior (e.g. do error logging to both the global error log and a per-request log, then at other times do it to a log buffer for testing, and NOT to anywhere else).
At least with a singleton you can create a bunch of "standard configurations" by calling them with a different constructor at startup time. So you can have a test DB during tests, different log targets, read from different filesystem (not the real one, but the one in the testdata/ directory) ...
Better yet is to have a "context" abstraction that you pass down the chain. Issue with that is, every method needs to have a first parameter that is the context ... so it requires some discipline.
Some frameworks (java @#$@#%@# servlet spec for example) make this parameter implicit and then use something akin to exception resolution to get this parameter (so when you do GetContext(), it unwinds the stack to give you the correct context). That makes things very complicated, and is an invisible LOT of state that gets passed down the stack. Still better than singletons or static methods, but good luck figuring out why a context is set to X.
In all cases you need to be very careful to USE the context. DO NOT use database except the one in the context, no caches except the one in the context, no filesystem reading, logging, ... except by redirecting through the context.
- deleted 6y ago[deleted]