|
|
|
|
|
by pfitzsimmons
4209 days ago
|
|
"For any significant piece of logic, it ends up living in a class on its own, with its dependencies injected either via constructor parameters or method parameters." And I was worried I was the only one who thought this was crazy! In most python frameworks, like django, when you want to call some service, you import some static class or singleton. It is simple and straightforward. If the framework wants to allow you to swap in different implementation classes, then it will define a singleton or static class with a clear API that then dispatches to the specific implementation class based on your global settings. Or, if you want to override the default implementation on the spot, you can just invoke the implementation class you want directly. So in django, I just do: from django.core.cache import cache
cache.get('my_key')
Voila! That's all the code I need, and it works great. I can easily swap in memcached or a file cache or a local memory cache or whatever. It is straightforward and easy to debug. If I am wondering why the wrong implementation service is being used, I can usually step through with a debugger right at the point it is being called and figure out what is going on. If you I am writing tests, I either use different settings or monkey patch the static class in my setup and tear down functions.In most java frameworks, your classes are supposed to either accept the service via a constructor, or have it injected into your class via Guice or Spring. This adds a whole new level of complication and verbosity, and means things break far away from when you are using them. I know people swear by dependency injection, but I really don't get it, I have never found it to be a better pattern than the django pattern. |
|
Java doesn't have that loading system, so there is a small cottage industry of frameworks that provide its valuable features. None of them can rely on a language-specified import system and global namespace to which things can be added, which is why they get parameterized one way or another.
Breakage from faraway places can happen in either system, as far as I can tell. It's kind of inherent in the abstraction.