IoC DI, How to I resolve deep within the core? - inversion-of-control

Everyone says that an IOC should not be static or global in any way and should be created at root. But how do I get at it deep within my code?
Lets say I have an entry point ClassA. In here I can create an instance of an IOC and register all my interfaces to concrete types etc. But what then? Do I now start passing the IoC around ? Surely this would violate DIP ? None of the articles I have read discuss getting access to the Ioc and I would have thought it fundamental. I'm sure I must be missing something very simple here :)
Lets say ClassA creates a ClassB which creates A ClassC. Class C needs access to my resolved IDatabase. How does it get it ? Do I have to pass the IoC all the way in ?

You should be passing in the dependencies that a class needs. If Class C needs access to IDatabase then you must allow your IoC Container to pass an implementation of IDatabase into Class C, for example by having an IDatabase parameter on the Constructor for Class C.
If the IoC framework has the responsibility for creating Class C, then it also has the responsibility for giving Class C the dependencies it needs. As long as IDatabase has been registered in the IoC Container against a class which implements IDatabase, then an IDatabase parameter on Class C's constructor should be passed an implementation of IDatabase automatically.
To look at your example of ClassA creating ClassB which creates ClassC. Class A should not be 'newing' up an instance of ClassB using the 'new' keyword (I'm using C# or Java syntax here).
Rather, ClassA, ClassB and ClassC should all be registered with your IoC Container. If ClassA needs an instance of ClassB, then give ClassA a constructor which takes a parameter of ClassB. Your IoC Container should automatically resolve an instance of ClassB and pass it into ClassA. The same applies all the way down the chain as far as you need to go.
Using constructors (aka 'Constructor Injection') is not the only option here. You can often also use Property Injection, whereby public property setters are automatically set by your IoC Container (and there is also the much rarer 'Interface Injection'). But Constructor Injection is often the best way to go because it is then very clear exactly what dependencies a class needs before it can be instantiated; Property Injection can be unclear because a property may or may not be set by the IoC Container, depending on whether or not the property type has been registered or not.

Related

Why JPA requires Entity classes to be non-final & fields non-final

Was reading about JPA here. Two of the requirements of an Entity class are that
The class must not be declared final. No methods or persistent instance variables must be declared final.
The class must have a public or protected, no-argument constructor.
Persistent instance variables must be declared private, protected, or package-private.
Was curious to know why are these conditions required ?
The class must not be declared final. No methods or persistent instance variables must be declared final.
JPA implementations use proxies in front of your entities to manage for example: Lazy loading. As a final class cannot be extended, a proxy cannot be built.
Some implementations as Hibernate can persist final classes but it can affect performance more info.
The class must have a public or protected, no-argument constructor.
These kind of frameworks and others in order to create new objects use ```Class.newInstance()`` that is the reason why a no arg constructor is needed.
Persistent instance variables must be declared private, protected, or package-private.
Being only accesible through accessor or business methods allow interception in proxies.
The reasons are (at least some of them):
JPA provider needs to create instances of the entity dynamically. If class would contain the only constructor which takes arbitrary arguments, JPA provider cannot figure out values for those arguments. That's why it must has a no-arg constructor.
JPA implementations deal with persisting instances of your entities classes. that's why the class, methods and variables cannot be final.
Because you don't want access to the variables from outside directly, in order to keep encapsulation - this is an OOP reason. another reason is that many frameworks of persistence are having a getter/setter method to identify POJO "properties".

Play framework controller test - No implementation for <classname> was bound

I would like to write test for a controller class. The controller class takes a service object as constructor parameter. Added the #Inject annotation to the constructor of the service class.
class AssociateService #Inject()(configuration: Configuation){...}
The constructor parameter of the service class is a custom configuration object also created for the application. I added the #Inject to the constructor of the config class as well. Now I'm getting these types of error messages:
No implementation for "className" was bound.
Could not find a suitable constructor in java.lang.Integer. Classes must have either one (and only one) constructor annotated with #Inject or a zero-argument constructor that is not private.
The configuration class has several constructor parameters, those are "basic" types (Int, Boolean) and one parameter is a custom class type (className).
How should I do this binding or is it just enough to annotate something else?
And why it says that constructor error message?
As far as I know, there are two ways with tests and guice, with trade offs:
Don't using field injections, using only constructor injections and fields assignment in constructor for injected parameters. This approach enables very simple solution for testing, just don't use dependency injection in tests. But all your classes must have ability to be created with new operator in test cases...
Ps. You can define optional constructor and use field injections, of course, but it is not very clear solution.
Creating correct module with injectable interfaces binding to its implementations for every test or group of similar tests. Sometimes this approach takes a lot of unnecessary working hours.
You must design your software to maintain testability. Sometimes not every line of code in project need to be tested, sometimes not every code is testable, you must separate it from important parts of your software, that requires testing. If you design your software with single responsibility principe so writing tests is much easer...

Constructor and Unit Testing

I have a class XmlRecord. This class will deal with reading/writing to an xml file. At the moment, I have the following for that class:
class XmlRecord {
private val _file = new File("file.xml")
}
I want this class to somehow create the file if it doesn't exist. I know how to achieve this but I'm unsure how to design it in an Object Orientated way. I think I have two options:
Do I add a code to the constructor (or a call to a private method) that will create this file automatically if it doesn't exist. My problem with this method is that how do I unit test this as this code is effectively private code? Would I have to inject the File dependency so it could be mocked during testing?
Do I get the constructor to return an exception or implement a public method for the class so that the caller can use it to check if a file needs to be created? If so, the caller would then call another public method that would create the file. Again I think I would need to inject the dependency.
I hope that makes sense. I'm just trying to get a better grasp on designing my classes.
The presence of abstractions to accomplish DIP have other design
implications in an Object Oriented program:
All member variables in a class must be interfaces or abstracts.
All concrete class packages must connect only through interface/abstract classes packages.
No class should derive from a concrete class.
No method should override an implemented method.[5]
All variable instantiation requires the implementation of a Creational pattern as the Factory Method or the Factory pattern, or the more complex use of a Dependency Injection framework.
Dependency inversion principle

Abstract Class and Interface, Object Oriented Programming question

I have a clue about Object Oriented Programming:
I need to have a parent class HandlerException which needs to define the sign of three methods (MethodA, MethodB, MethodC).
Then, I have a child class BusinessHandler which inherits from HandlerException and defines ONLY the MethodA of its parent class.
Then, I have a child class DataHandler which inherits from HandlerException and defines ONLY MethodC of its parent class.
Then, I have a class named CustomerDAO which inherits from DataHandler and consumes the MethodC written on its parent class. (consumes it like: DataHandler.MethodC).
As you can see, its a typical object oriented programming problem; I need to have some static methods (MethodC) to access it directly without any instance of the class. The parent class HandlerException could be abstract? and its 3 methods (A, B and C) could be ???? (that's my question, how is the RIGHT way to write this parent class: abstract with abstract members, or virtual, or maybe an interface?)
I hope you got the idea of my question and that I made myself clear. Thanks in advance.
I forgot: I'm using C#, and to mention: MethodB would be implemented on the next release of the app.
Depends on the language you are using, but it sounds like the HandlerException class would be abstract and all three methods would be virtual.
If the HandlerException class has absolutely no implementation whatsoever (only defines those three methods) then it would probably make sense to make it an interface rather than an abstract class.
Also, where is MethodB implemented? If it isn't implemented by any of those classes, then all the classes would need to be abstract.

Advantage of Static class over use of Singleton

Duplicate
What’s wrong with singleton?
Singletons: good design or a crutch?
Singleton: How should it be used
What is so bad about Singletons
You can find numerous reasons for using a Singleton over a Static class. But there must surely be some situations where it is better to use a static class before a Singleton. What are they?
You can use static class when:
1) all its methods are utilities (nice example - class Math)
2) you don't want to deal with preserving your instance from garbage collector (in applets), but I would better use singleton there
3) you are absolutely sure that it wouldn't become stateful in the future and you are sure that you will always need only one instance of that class
If you are using singleton and in one moment you realize that you need several instances then your singleton easily can be transformed to multitone, but you'll have a problem with static class
Having fought with the testability of consumers of static classes over the years I can honestly say that they are the work of evil minds. Seriously though, I'd use static classes for extention methods in C# but not really anywhere else.
If your class doesn't store any state, then use a Static class.
If it stores state and you require a single instance, then (maybe) use a Singleton.
Otherwise use a regular class.
Static class is better for when you don't need to change the implementation. With a Singleton, you can have an interface with various implementations. A Static class, can only be an implementation.
A singleton is a class of which only one instance can be instantiated, whereas there is no instance associated with a static method.
If you can implement the function you want with a single static method, then that is probably your best approach, because it is easier to implement. Consider extension methods - they are just static methods with syntactic sugar. If you can logically view the static method as a helper to an existing class, then it makes sense to use a static method.
On the other hand, if there is some sort of state involved in the functionality you are trying to achieve, then it is probably best to use a Singleton instead. The Singleton object can contain/manage its state and manage concurrent access/threading, whereas this becomes much more complicated with static classes and static methods. If you are using Singleton's in C#, I highly recommend reading Jon Skeet's article on proper Singleton implementation, which is available at http://www.yoda.arachsys.com/csharp/singleton.html .
Singleton's are more comparable to static classes than static methods. A big advantage that singletons have in this comparison is that they can implement interfaces and derive from base classes. This allows you to decouple their implementations from their interfaces. For example, if I have an interface IAccountService in my core assembly with a Singleton implementation, SingletonAspNetAccountService in my service layer, then I can inject the IAccountService into my UI layer with an IoC container, without requiring a dependency on my service layer in the UI layer. On the other hand, if I had a static Accounts class, then I would have to either create an adapter to the static class's methods or have a dependency on the service layer in my UI in order to access the static account functionality.
It's always where you don't actually need to pass the singleton instance anywhere.
For example, singleton will be useful if it implements some interface, you can't do it with a static class.
Remember, every Class instance is a singleton, managed by JVM.
So static class is a singleton.