My FeedDiscussionsHeadless CMS
New
Sign in
Log inSign up
Learn more about Hashnode Headless CMSHashnode Headless CMS
Collaborate seamlessly with Hashnode Headless CMS for Enterprise.
Upgrade ✨Learn more
Dany Paredes

15 likes

·

15.0K reads

3 comments

Oleksandr
Oleksandr
Apr 19, 2023

Hello Dany Paredes!

Thank you for the article. It reminded me of when I passed an injector from a child class to a parent class, but after a short period of time, I rewrote everything back. Here is a small example:

` class Base { protected param: Param; protected param1: Param1;

constructor(injector: Injector) { this.param = injector.get(Param); this.param1 = injector.get(Param1); } }

class Child extends Base { constructor(injector: Injector, private childParam: ChildParam) { super(injector); } } `

When we use the injector(in your case is a "inject()") as a service locator, we violate the encapsulation, we also violate the segregation of interfaces. In general, the service locator is an anti-pattern. Based on that, don't you think it's the same thing? Because now it is not clear what dependencies are needed to make this class work.

·
·2 replies
Dany Paredes
Dany Paredes
Author
·Apr 19, 2023

Using the Service Locator pattern depends on your app's needs. However, critics warn it might violate important principles and complicate testing, with Dependency Injection patterns being generally favored.

but the Service Locator pattern in programming comes with its own advantages and disadvantages. Those who favor it say it makes app configuration more adaptable, as you can effortlessly swap or refresh dependencies while the app runs.

It also enhances app configuration flexibility, maintains separation of application layers, and can be more efficient than Dependency Injection for managing multiple dependencies. 😊😊

·
Oleksandr
Oleksandr
Apr 19, 2023

Dany Paredes

Thank you for elaborating on the advantages and disadvantages of the Service Locator pattern. I agree that the pattern can provide benefits such as flexibility and enhanced separation of application layers. However, I still have concerns about violating important design principles and complicating testing when using this approach.

In light of your response, I wonder if you could provide some more complex examples or scenarios(idea for the second part of article?🤔😄) where you think the Service Locator pattern, and specifically the inject() function in Angular, would be a better choice than Dependency Injection. It would be helpful to see some practical use cases that demonstrate the advantages of this approach. Thanks again for the post 😊

P.S. But I should note that at first, when I accidentally discovered this approach, I was very pleased🤩 After some time, when I wandered through the Angular source code, I saw this approach there(if I'm not mistaken 😅)

·