I have been looking for a while on the Internet about this but could not find an exact answer. Okay, they say inject an abstraction (interface or something) to a class rather than having it to create the instances it needs, or rather than passing an implementing type.
class Foo
{
private IBar _bar;
public Foo(Ibar bar)
{
_bar = bar;
}
}
Although I don't fully understand how above is reasonably loosely coupled, but my question at this point is about something else. That is, what if a method has to return an instance of something. How, for example, following can be made loosely coupled:
class Foo
{
public IBar GetMeSomething()
{
return new Bar(); // dependency here
}
}
I was just wondering how I resolve the above dependency on Bar? Any experienced programmers please help me understanding this. Or someone may be able to suggest some article comprehensively discussing all such scenarios that eliminate/reduce type inter-dependencies.
When a class need to know "Something" about your program, you can resolve that by passing a instance of another class in your constructor.
If you accept in constructors only interfaces instead of concrete classes you are later able to change implementation easily.
If you have to create Objects at run time you need factories, you class Foo is in your case a IBarFactory (because it instantiate IBars).
Dependencies in constructors via interfaces are easily resolved by any IoC framework (Factories are passed in constructors too), while the implementation of a factory itself is allowed to instantiate objects directly or through a IoC framework because that's the responsability of the class.
Using IoC containers and dependency injection does not make looscoupling happens for magic, you still have to model classes with SOLID principles in mind, but when using SOLID principles IoC containers and DI are of great help.
Related
Closed. This question needs to be more focused. It is not currently accepting answers.
Want to improve this question? Update the question so it focuses on one problem only by editing this post.
Closed 5 months ago.
Improve this question
I viewed a couple of answers online regarding Abstractions, Abstract Classes, Interface's, DI, and Loose coupling. But none of these answers are answering my question. I grouped these topics because they are related to achieving abstractions. Got a good understanding of the mentioned topics, but yet not fully understand them in detail and how they related to each other.
Generally speaking, interfaces are used to make classes loosely coupled. Thus define a set of functions and fields to be implemented. The idea of making Loosely Coupled classes is that will need to remove dependency over several classes.
For instance, if we make a change to one of these classes then we do not need to change other places making code maintainable. The only good example I can think of to use loosely coupling is through DI. So when we say interfaces make classes loosely coupled do we mean by passing an interface as a dependency?
"Please continue reading will further clarify".
A question here is if we are going to use DI and pass interfaces as dependencies then why not pass a class as a dependency instead? maybe I will need further clarification about Interfaces before answering the previous question. I will further explain.
The main idea of interfaces is to establish contact with classes that going to implement the interface meaning we are going to need to define functions and fields to enforce to implement them. but still, the idea of interfaces as a contract is not yet clear because if we enforce a developer to implement an interface called a server that has methods to turn on and off the server but the developer forgot to turn off the server programmatically then what is the point of this contract?
Further, my understanding is that this all falls under the concept of abstraction which means we do not need to worry about details but an abstraction. Does that not mean when building an application we first need to create classes/structures without code such as using UML?
Further, why would we use an abstract class over interfaces where an abstract class has similarities to an interface such as defining a function but without a body?
Coming back to Interfaces and DI we can inject interfaces as a dependency but why? Can we not inject a class it self? is it not easier to use classes as a dependency? where we can access all functions or this is not the idea of interface Can sombody help with this. I only understand one use case on why we should use DI. Example:
//Class1
//Class1 Con
Public Class1 Con(){
Class2 class2 = new Class2(1,1,1)
}
The above example is not maintainable because if we add a new parameter to Class2 then we need to modify it elsewhere. but if we use DI Injection then we won't are there any other reasons.
Also, DI can be useful to create one instance and use that instance across the whole application. Does that save some memory by not creating multiple instances? or saving time connecting to DI?
The question should we use abstractions at the very early coding stage where we create classes without code?
Further, do we use interfaces to make the developer aware that they need to implement a certain set of functions? But why?
Do I predict that we need to use an interface by creating UML diagrams to see if there would be different classes to use an interface with similar functionalities
"Can we not just create a superclass and override methods"
Can somebody explain when to use superclass and override methods over interfaces and provide an implementation?
Also, when to pass an interface as a dependency? And when to pass a class as a dependency? One advantage I can think of when using interfaces is polymorphism where we can make an interface of any implemented types and then access the interface type function; polymorphism. Example:
Class1 class = new Interface1();
Can this be possible?
Bottom line is we would like always to make our class's loosely coupled. Meaning that decouple class's to achieve maintainable. Thus, loosely coupled classes provider's late binding, extensibility, maintainability and easy testing. May refer to reference 1. We use interface's to make class's loosely coupled as well. but before answering how. we need to understand interface's why we use them and how they are different to abstract class's. Interface's are mainly used as contract meaning that when we create multiple class's sharing same behaviour but with different implementation then we use interface's. Thus, its a set of infrastructure to tell developer's what method's to implement. interface's only includes functions, fields signature with no implementation.
How we use DI to achieve loosely coupled class's is by injecting dependencies. suppose the following class's implements interface called Database:
public interface Database
{
void Save();
}
class SqlServer : Database
{
public void Save()
{
Console.WriteLine("Saving...");
}
}
class Oracle : Database
{
public void Save()
{
Console.WriteLine("Saving...");
}
}
Then we can easily inject dependencies as follows:
class Library
{
//private Database _SqlServer;
private Database _Oracle;
public Student(IDAL _SqlServer)
{
this._SqlServer = _SqlServer;
}
public void SaveBoo()
{
_SqlServer.Save();
}
}
Using the above approach we are injecting dependencies meaning that class's are now not fully tightly coupled. if any change made to _SqlServer we do not have to worry. To achieve full decoupled class's then use DI container Refer to reference 1.
The difference between abstract class's and interface's is that we use interface to define a contract where we use abstract if we want partial implementation. In Abstract class's you can define some method's implementation while leaving other as abstract.
You may create UML class diagrams to represent class's relationship without the need to worry about the coding side yet
As I am replying to my own question I would think it’s good to create classes and relationship I will call it classes structure then do all code later in case UML Class diagram is not going to be used. I guess this will fall under the technique/concept that is called abstraction where we do not yet worry about the details yet. So we can have an image about how is the application is structured without using UML’s.
Hope make sense
References:
(https://findnerd.com/account/#url=/list/view/Dependency-Injection-in--Net/24098/)
I'm having troubles getting the advantage of a IoC (DI) container like Ninject, Unity or whatever. I understand the concepts as follows:
DI: Injecting a dependency into the class that requires it (preferably via constructor injection). I totally see why the less tight coupling is a good thing.
public MyClass{
ISomeService svc;
public MyClass(ISomeService svc){
svc = svc;
}
public doSomething(){
svc.doSomething();
}
}
Service Locator: When a "container" is used directly inside the class that requires a dependancy, to resolve the dependancy. I do get the point that this generates another dependancy and I also see that basically nothing is getting injected.
public MyClass{
public MyClass(){}
public doSomething(){
ServiceLocator.resolve<ISomeService>().doSomething();
}
}
Now, what confuses me is the concept of a "DI container". To me, it looks exactly like a service locator which - as far as I read - should only be used in the entry point / startup method of an application to register and resolve the dependancies and inject them into the constructors of other classes - and not within a concrete class that needs the dependancy (probably for the same reason why Service locators are considered "bad")
What is the purpose of using the container when I could just create the dependancy and pass it to the constructor?
public void main(){
DIContainer.register<ISomeService>(new SomeService());
// ...
var myclass = new MyClass(DIContainer.resolve<ISomeService>());
myclass.doSomething();
}
Does it really make sense to pass all the dependancies to all classes in the application initialization method? There might be 100 dependancies which will be eventually needed (or not) and just because it's considered a good practice you set create them in the init method?
What is the purpose of using the container when I could just create the dependancy and pass it to the constructor?
DI containers are supposed to help you create an object graph quickly. You just tell it which concrete implementations you want to use for which abstractions (the registration phase), and then it can create any objects you want want (resolve phase).
If you create the dependencies and pass them to the constructor (in the application initialization code), then you are actually doing Pure DI.
I would argue that Pure DI is a better approach in many cases. See my article here
Does it really make sense to pass all the dependancies to all classes in the application initialization method? There might be 100 dependancies which will be eventually needed (or not) and just because it's considered a good practice you set create them in the init method?
I would say yes. You should create the object graph when your application starts up. This is called the composition root.
If you need to create objects after your application has started then you should use factories (mainly abstract factories). And such factories will be created with the other objects in the composition roots.
Your classes shouldn't do much in the constructor, this will make the cost of creating all the dependencies at the composition root low.
However, I would say that it is OK to create some types of objects using the new keyword in special cases. Like when the object is a simple Data Transfer Object (DTO)
I've recently been challenged on my view that singletons are only good for logging and configuration. And with Dependency Injection I am now not seeing a reason why you can't use your services or repositories as singletons.
There is no coupling because DI injects a singleton instance through an interface. The only reasonable argument is that your services might have shared state, but if you think about it, services should be stand alone units without any shared state. Yes they do get injected with the repositories but you only have one way that a repository instance is created and passed to the service. Since repositories should never have a shared state I don't see any reasons why it also cannot be a singleton.
So for example a simple service class would look like this:
public class GraphicService : IGraphicService
{
private IGraphicRepository _rep;
public GraphicService(IGraphicRepository rep)
{
_rep = rep;
}
public void CreateGraphic()
{
...
_rep.SaveGraphic(graphic):
}
}
No state is shared in service except repository which also doesn't change or have it's own state.
So the question is, if your services and repositories don't have any state and only passed in, through interface, configuration or anything else that's instantiated the same way they then why wouldn't you have them as singleton?
If you're using the Singleton pattern i.e a static property of a class, then you have the tightly coupling problem.
If you need just a single instance of a class and you're using a DI Container to control its lifetime, then it's not a problem as there are none of the drawbacks. The app doesn't know there is a singleton in place, only the DI Container knows about it.
Bottom line, a single instance of a class is a valid coding requirement, the only issue is how you implement it. The Di Container is the best approach. the Singleton pattern is for quick'n dirty apps where you don't care enough about maintainability and testing.
Some projects use singleton for dependence lookup before dependency injection gets populated. for example iBATIS jpetstore if I'm not mistaken. It's convenient that you can access your dependence gloablly like
public class GraphicService : IGraphicService
{
private IGraphicRepository _rep = GraphicRepository.getInstance();
public void CreateGraphic()
{
...
_rep.SaveGraphic(graphic):
}
}
But this harms testability (for not easy to replace dependence with test doubles) and introduces implicit strong dependence (IGraphicService depends on both the abstraction and the implementation).
Dependeny injection sovles these. I don't see why can't use singleton in your case, but it doesn't add much value when using DI.
I'm simply looking for advice on the best way I should handle this situation.
Right now I've got several files in a folder called Service. The files contact several functions which do random things of course. Each of these files needs access to the SM Adapter.
My question is, should I implement the ServiceManagerAwareInterface in each of these files OR should I just make a new class which implements the ServiceManagerAwareInterface and just extend my classes on the new class which implements this service?
Both ways work as they should, just not sure which way would be more proper.
If you think that your system will always rely on ZF2, both approaches are equivalent.
Now from an OO design perspective, personally I have a preference for the approach in which you extend your service then implement the ServiceManagerAwareInterface. I would even use an interface for the dependency over the ServiceLocator to protect even more my classes. Why?
Extending your classes does not cost you a lot, same for making your class depending on interfaces.
Let's take this example, Imagine you did not use this approach during a ZF1 project, during which you had probably resolved your dependencies with the Zend_Registry.
Now, let's assume you moved to a ZF2 implementation, how much time you think you'll spend refactoring your code from something like Zend_Registry::get($serviceX) to $this->getServiceManager()->get($serviceX) on your Service layer?
Now Assume you had made the choice of protecting your classes, first by creating your own Service locator interface, as simple as:
public interface MyOwnServiceLocatorInterface{
public function get($service);
}
Under ZF1 you had created an adapter class using the Zend_Registry:
public class MyZF1ServiceLocator implements MyOwnServiceLocatorInterface{
public function get($service){
Zend_Registry::get($service);
}
}
Your Service classes are not coupled to the Zend_Registry, which make the refactoring much more easier.
Now, You decide to move to ZF2 so you'll logically use the ServiceManger. You create then this new Adapter class:
public class MyZF2ServiceLocator implements
ServiceManagerAwareInterface,MyOwnServiceLocatorInterface
{
private $_sm;
public function get($service){
$this->_sm->get($service);
}
public function setServiceManager($serviceManager){
$this->_sm = $serviceManager;
}
}
Again, your Service classes are not coupled to the ZF2 ServiceManger.
Now, how would look like the configuration/registration of you Service layer on the ServiceManager. Well, you'll use your Module::getServiceConfig class for that:
//Module.php
public function getServiceConfig()
{
return array(
'factories'=>array(
'My\ServiceA'=>function($sm){
return new My\ServiceA($sm->get('My\Service\Name\Space\MyZF2ServiceLocator'));
}
//Some other config
)
}
As you can see, no refactoring is needed within your Service classes as we protected them by relying on interface and using adapters. As we used a closure factory, we don't even need to extend our Service classes and implement the ServiceLocatorAwareInterface.
Now, before concluding in my previous example i have to note that I did not treat the case in which my classes are constructed via factories, however, you can check one of my previous answers that address the factory topic but also the importance of loose coupling among an application layers.
you can add initializers to do that. It can reduce repetitive injection in getting the service that pass db adapter. OR, you can set abstract_factories, it will reduce repetitive SM registration. I just posted SM Cheatsheet here, Hope helpful :)
https://samsonasik.wordpress.com/2013/01/02/zend-framework-2-cheat-sheet-service-manager/
I have a question regarding dependency injection pattern.
My question is...
If I go for constructor injection, injecting the dependencies for my class, what I get is a "big" constructor with many params.
What if ie. I dont use some of the params in some methods?
Ie. I have a service that exposes many methods. And a constructor with 10 parameters (all dependencies). But not all the methods uses all the dependencies. Some method will use only one dependency, another will use 3 dependencies. But DI container will resolve them all even if non are used.
To me this is a performance penalty of using DI container. Is this true?
It seems your class is doing to much, that it does not comply to the S in SOLID (Single responsibility principle) , maybe you could split the class in multiple smaller classes with less dependencies. The fact that not all dependencies are used by all methods suggests this.
Normally the performance penalty of injecting many dependencies is low, but it depends on the framework you pick. Some will compile methods for this on the fly. You will have to test this. Many dependencies does indicate that your class is doing too much (like Ruben said), so you might want to take a look at that. If creation of an instance of a depedency that you often don't use causes performance problems, you might want to introduce a factory as dependency. I found that the use of factories can solve many problems regarding the use of dependency injection frameworks.
// Constructor
public Consumer(IContextFactory contextFactory)
{
this.contextFactory = contextFactory;
}
public void DoSomething()
{
var context = this.contextFactory.CreateNew();
try
{
// use context here
context.Commit();
}
finally
{
context.Dispose();
}
}
You can also hide some not-yet-needed dependencies behind lazy providers. For instance:
public DataSourceProvider implements Provider<DataSource> {
public DataSource get() {
return lazyGetDataSource();
}
}
The Provider interface is part of javax.inject package.
Actually you can't know which methods are used at runtime when you build your DI container. You would have to deal with that performance penalty or if you know that there are many cases where just a few dependencies are used, you could split your container into several small containers that have less dependencies that are injected.
As rube Says probabily you should review te design of your class to stick to SOLID principles.
Anyway if it is not really necessary I'm used to go for property setter dependency insteadof the constructor. It means that you can create a property for each dependecy you need. That helps also to test the class because you can inject only the dependency you need into the context of the test you are doing instead of stub out all the dependency even if you don't need it