-
Couldn't load subscription status.
- Fork 0
Service Locator Considerations
It's important to mention that the Service Locator pattern can become an antipattern, depending on the design we adopt
in our application. This pattern can violate the Dependency Inversion principle if our classes depend on concrete
implementations instead of abstractions (interfaces). This can lead to a decrease in the flexibility, modularity of the
code and complicate the achievement of tests or unit tests. (simulation of mocks or stubs).
It is recommended to use dependencies injection to solve this problem. It is a better alternative because it makes dependencies explicit, which facilitates the comprehension of the code, improves maintainability and simplifies tests. This approach reinforces the transparency in the design, which results in more robust and decoupled systems.
class Request {
public Fetch() {
const fetchService = container.get('fetchService');
return fetchService.get('/todos/1');
}
}Issues
-
Hidden dependency: The dependency (
fetchService) is not visible in theRequestclass signature, making the code less transparent. - Testing challenges: For unit testing, you'd need to set up the service container in every test, adding complexity and reducing flexibility.
-
Increased coupling: The
Requestclass is coupled to the dependency container, which can make the code harder to maintain and evolve over time.
class Request {
constructor(private fetchService: FetchService) {
}
public Fetch() {
return this.fetchService.get('/todos/1');
}
}Advantages
-
Explicit dependency: The
Requestclass clearly states its dependency onFetchService, making the code easier to read and understand. -
Easier testing: For unit testing, you can simply inject a mock or stub of
FetchServiceinto the constructor without setting up a container. -
Reduced coupling: The
Requestclass now directly depends on an abstraction (FetchService), reducing its coupling with the dependency container and making the code more modular.
We welcome contributions from the community! Whether it's reporting a bug, suggesting a feature, or contributing code, your involvement is key to making Packet.js better. Please check out this section for more details.
If you encounter any issues or bugs while using packetjs, or if you have any feature requests, please feel free to
open an issue in our GitHub repository. You can report issues, track progress, and engage in discussions with the
community via the following link:
If you have any questions or need further assistance, feel free to reach out via the discussion board.