3 ms·
Honest question: Why is it a bad pattern? And what are some better alternatives from other ecosystems?
by cezart 4y ago
Honest question: Why is it a bad pattern? And what are some better alternatives from other ecosystems?
- latchkey 4y agoThe singleton pattern generally tends to be hard to write tests for. Singletons are basically a global object with static methods. The dependency injection pattern fits better. DI is basically passing around objects which conform to an interface. This way you can mock out those objects more easily.
- RangerScience 4y agoOne issue that a lot of patterns run into in Ruby (and other highly flexible languages) is that a lot of patterns exist to help you deal with the restrictions the language puts on what you can do with it. Ruby has enough sharp knives that many patterns are pointless, or trivial enough that they're idioms instead, or that the downsides of the pattern are drastically limited. (example: command pattern vs lambdas; delegate vs blocks) Having singletons can make sense, if the abstraction has to be leaky... (examples of abstractions that must be leaky: AWS vs GCP) (examples of abstractions that can be tight: Segment vs Rudderstack) ...because then you're never really in a position where you need multiple objects, or to swap out the implementing object, during production runtime. So you don't benefit much from DI on prod. And in Ruby, when you're in the tests, there's a handful of nice and handy shenanigans you can pull to remove the downside / AKA make it trivial to mock the object. -- AKA Ruby is flexible enough that you need DI like a contortionist needs a backscratcher.
- fomine3 4y agoI agree in general, but Ruby is flexible enough to handle mock/stab everything so it's not tend to big issue.