Junior — Middle
Can you name approaches that are not recommended when implementing dependencies in code?
sobes.tech AI
Answer from AI
The following approaches are not recommended when implementing dependencies in Java:
- Hardcoding dependencies inside the class (using new inside methods or constructors). This makes testing and replacing dependencies difficult.
- Using singletons unnecessarily. They create global state and complicate dependency management.
- Passing dependencies through static methods or fields. This reduces flexibility and makes testing harder.
- Using a Service Locator instead of explicit dependency injection. This hides dependencies and worsens code readability.
It is better to use constructor or setter injection, as well as DI frameworks (e.g., Spring), to manage dependencies explicitly and conveniently.