Dependency Injection - what is the difference between these two codes? [closed] - oop

Closed. This question needs details or clarity. It is not currently accepting answers.
Want to improve this question? Add details and clarify the problem by editing this post.
Closed 6 years ago.
Improve this question
I have been trying to understand dependency injection and I have been making progress but
I will like to know the benefit/difference/importance of these code. They look the same but different approach
//dependency injection - (as was claimed)
Customer customer = new Customer(10);
IOrderDAO orderDAO = new OrderDAO();
customer.setOrderDAO(orderDAO);
customer.getOrdersByDate();
OR
//Unknown Pattern - Please what pattern is this?
Customer customer = new Customer(10);
IOrderDAO orderDAO = new OrderDAO();
orderDAO.getOrderByDate(customer.id);
What's wrong with the second approach?
Thanks.

Neither one looks like dependency injection to me; there shouldn't be calls to new.
Dependency injection is done by a bean factory that's wired with all the dependencies. It instantiates the beans and gives them their dependencies.
I see no bean factory here at all. It's a long way to dependency injection.
The Customer gets the OrderDAO in the first example using the setter. The first one says that the Customer has to expose persistence methods in its API. It's responsible for saving its Orders. I'd say it's a poor separation of concerns, because now Customers have to know about Orders.
The second one keeps Customer separate from OrderDAO. You pass a Customer ID to the OrderDAO and have it save Orders on that Customer's behalf. I think it's a better separation of concerns.
But neither one is a good example of dependency injection.
The first and best description of DI came from Martin Fowler. I'd recommend that you read this carefully:
http://martinfowler.com/articles/injection.html
It's eight years old, but still spot on.

Neither of them is proper dependency injection example. Those are rather examples of data access patterns.
The first one is an example of active record pattern. Setting orderDAO as a dependency for customer entity we could call property or setter injection.
The second example could be repository pattern. Dependency pattern here would be method injection, which translates to common invoking method with some parameters (parameters here are dependencies for method).
Good way to start learning DI pattern would be reading this book. There are also many online resources like those videos:
http://www.youtube.com/watch?v=RlfLCWKxHJ0
http://www.youtube.com/watch?v=-FRm3VPhseI&feature=relmfu
http://www.youtube.com/watch?feature=player_embedded&v=hBVJbzAagfs
I would also recommend looking for Dependency Inversion Principle in google (it's not the same as dependency injecion).

It's an odd example, but the first one demonstrates what a dependency injection container would do and the second one demonstrates one object passing an argument to another object. The first embeds its dependencies as instance variables of the calling class; the second is more procedural in nature. Neither is wrong, per se. It depends on how complex your dependencies are and how you want to manage code.
Looking just at the injector code you provided, it's not immediately obvious why you'd ever want to use dependency injection. But consider a more complex (and more typical) example for a moment.
CustomerService:
public class CustomerService implements ICustomerService {
private IOrderDAO orderDao;
public void setOrderDAO(IOrderDAO orderDao) {
this.orderDao = orderDao;
}
public Order getOrderByDate(Integer customerId, Date date) {
return this.orderDao.findOrderByDate(customerId, date);
}
}
OrderDAO (default implementation):
public OrderDAO implements IOrderDAO {
private javax.sql.DataSource dataSource;
public void setDataSource(javax.sql.DataSource dataSource) {
this.dataSource = dataSource;
}
public Order findOrderByDate(Integer customerId, Date date) {
...
}
}
StubOrderDAO (stub implementation):
public StubOrderDAO implements IOrderDAO {
public Order findOrderByDate(Integer customerId, Date date) {
return new HardCodedOrder(); // this class would extend or implement Order
}
}
At runtime, instances of CustomerService won't have any idea which implementation of IOrderDAO is being used. That means that you could very easily, for instance, bootstrap a unit test for CustomerService by initializing it with StubOrderDAO (which always returns a hard-coded customer). Likewise, your DataSource implementation may vary (either a mock data source or one which is different in different runtime environments).
So an injector intended for production use might look like:
// instantiate
CustomerService service = new CustomerService();
OrderDAO dao = new OrderDAO();
javax.sql.dataSource dataSource = jndiContext.lookup("java:comp/env/MyDataSource");
// initialize
dao.setDataSource(dataSource);
service.setOrderDAO(dao);
return service;
Whereas an injector for using a local (test) data source might look like:
// instantiate
CustomerService service = new CustomerService();
OrderDAO dao = new OrderDAO();
javax.sql.dataSource dataSource = new DriverManagerDataSource("jdbc:sqlserver:yadayada...", "myUsername", "myPassword");
// initialize
dao.setDataSource(dataSource);
service.setOrderDAO(dao);
return service;
And an injector for an integration test might look like:
// instantiate
CustomerService service = new CustomerService();
OrderDAO dao = new StubOrderDAO();
// initialize
service.setOrderDAO(dao);
return service;
So it's essentially a way to implement good layering and separation of concerns, i.e. the way you access the database is independent of how you access the data to create the domain model, and both are independent of any aggregation or business logic processing you'd do in CustomerService (not shown here for sake of brevity).
Does that make more sense?

Don't confuse inversion of control with dependency injection (as another answer did). I describe dependency injection and IoC here: http://www.codeproject.com/Articles/386164/Get-injected-into-the-world-of-inverted-dependenci
//dependency injection - (as was claimed)
Customer customer = new Customer(10);
IOrderDAO orderDAO = new OrderDAO();
customer.setOrderDAO(orderDAO);
customer.getOrdersByDate();
No. I would not call that DI. I would go as far as calling it badly written code. The customer should not be aware of the persistance layer which setOrderDAO(orderDAO) forces it to be. It breaks the single responsibility principle since the customer also have to take care of the orders.
//Unknown Pattern - Please what pattern is this?
Customer customer = new Customer(10);
IOrderDAO orderDAO = new OrderDAO();
orderDAO.getOrderByDate(customer.id);
It's not specific pattern, but better code since there is no coupling between the customer and the orderDao.

Related

Best Practice Open Close Principle

Please take a look at my class. In it WoW avatars are created. In the constructor method instances of different classes are created. If the program is extended by a new class (e.g. Tauren), the constructor method must be changed stupidly. One would have to add another object instantiation into the method. This contradicts the Open Close principle, according to which a software should be open for extensions but closed for changes. How can I solve this problem.
public class UpdateAvatarFactory{
public UpdateAvatarFactory(Client client){
ICreateMethod createHuman = new CreateHuman();
createHuman.name="Human";
ICreateMethod createElf = new CreateElf();
createElf.name="Elf";
ICreateMethod createGnome = new CreateGnome();
createGnome.name="Gnome";
ICreateMethod createOrc = new CreateOrc();
createOrc.name="Orc";
client.avatarFactory.addCreateMethod(createHuman);
client.avatarFactory.addCreateMethod(createElf);
client.avatarFactory.addCreateMethod(createGnome);
client.avatarFactory.addCreateMethod(createOrc);
}
}
In case you depicted, there is no point of having such class at all - it is the same as a static method.
Avatar factory could be a private member of Client and could simply have a method which takes array of CreateWhatever (according to Law of Demeter).
Now how to prevent hardcoding all these new Create*()? In real world scenarios it is usually done by DI (dependency injection) libraries. They often comes with your framework of choice (e.g. Spring), but you can find standalone solutions too (I don't work with java for many years now, so I don't know the latest trends, but you can find them easily).

Strategy Pattern and Open-Closed Principle Conflict

I was reading through strategy pattern and was trying to implement it but I have got stuck at deciding the strategy implementation which I feel violates the open-closed principle.
In strategy pattern we code to interface and based on client interaction we will pass in the strategy implementation.
Now if we have bunch of strategies so we need to decide using conditions which strategy the client chooses something like
IStrategy str;
if(stragety1) {
str = new Strategy1()
} else if (stragety2) {
str = new Strategy2()
} and so on..
str.run()
Now as per open-closed principle the above is open to extension but it is not closed to modification
If I need to add another strategy(extension) in future I do need to alter this code.
is there a way where this could be avoided or it is how we need to implement strategy pattern ?
1) You must separate selecting/creating a concrete strategy from its uses. I. e. use function selectStrategy, pass it as (constructor) parameter, etc.
2) There is no way to fully avoid conditional creation, but you can hide it (e. g. using some dictionary for mapping state=>strategy) and/or shift it into another level of the application. The last approach is very powerful and flexible, but depends on the task. In some cases you may put selecting/creating on the same level that uses it. In other cases you may even end up with delegation selecting/creating to the highest/lowest level.
2.1) You can use the Registry pattern and kinda avoid modification of "core" object when adding new strategy's.
This is indeed not closed to modification, but that is due to the way you initialize. You are using a value (enum?) to determine which Strategy subclass should be used. As #bpjoshi points out their comment, this is more of a Factory pattern.
Wikipedia discusses how a Strategy pattern can support the Open/Closed Principle, instead of hampering it.
In that example, they use a Car class with a Brake Strategy. Some cars brake with ABS, some don't. Different Car subclasses and instances can be given different Strategies for braking.
To get your code closed for modification, you need to select the Strategies differently. You want to select the Strategy in the place where new behavior or subclass is defined. You'd have to refactor your code so that the specific Strategy subclass is applied at the point where the code is extended.
I think, there is misunderstanding about Closed for Modifications.
In 1988, Mayer said:
Software that works should when possible not be changed when your application is extended with new functionality.
and Rober C. Matrin said:
This definition is obviously dated.
Think about that very carefully. If the behaviors of all the modules in your system could be extended, without modifying them, then you could add new features to that system without modifying any old code. The features would be added solely by writing new code.
https://8thlight.com/blog/uncle-bob/2014/05/12/TheOpenClosedPrinciple.html
Adding some new codes without modifying old codes do not conflict with Open-Closed Principle.
I think the decision you are referring to should be the responsibility of a factory class. The following is some example code:
public interface ISalary
{
decimal Calculate();
}
public class ManagerSalary : ISalary
{
public decimal Calculate()
{
return 0;
}
}
public class AdminSalary : ISalary
{
public decimal Calculate()
{
return 0;
}
}
public class Employee
{
private ISalary salary;
public Employee(ISalary salary)
{
this.salary = salary;
}
public string Name { get; set; }
public decimal CalculateSalary()
{
return this.salary.Calculate();
}
}
The Employee class uses the Strategy pattern and follows the Open/Closed principle, i.e. it is open to new strategy types (ISalary implementations) through injection via the constructor, but closed to modification.
The piece that is missing is the code that creates the Employee objects, something like:
public enum EmployeeType
{
Manager,
Admin
}
public class EmployeeFactory
{
public Employee CreateEmployee(EmployeeType type)
{
if (type == EmployeeType.Manager)
return new Employee(new ManagerSalary());
else if (type == EmployeeType.Admin)
return new Employee(new AdminSalary());
etc
}
}
This is a very simple factory pattern. There are better ways to do this but this is the simplest way to explain the concept.

Loading from database - inside or outside class? [closed]

Closed. This question is opinion-based. It is not currently accepting answers.
Want to improve this question? Update the question so it can be answered with facts and citations by editing this post.
Closed 8 years ago.
Improve this question
I've seen different ways of loading an object to and fro a database, with two common ones as shown below. Which one is better, and why?
Method 1: This includes defining two member methods for a class, load(id) and save(). These methods are called on instances of the class. For example,
class Wheel{
double diameter;
string tag;
public void Load(int id){
var result = ... // database query
this.diameter = result['diameter'];
this.tag = result['tag'];
}
public void Save(){
... // database query to update row
}
}
Wheel johnWheel = new Wheel();
johnWheel.Load(5); // In this case John's wheel has a row id of 5 in the database
Method 2: A utility method which loads/saves an object directly:
class DBUtils{
public static Wheel LoadWheel(int id){
var result = ... // database query
Wheel w = new Wheel();
w.setDiameter(result['diameter']);
w.setTag(result['tag']);
}
public static void SaveWheel(Wheel wheel){
...// Update DB
}
}
I ask because the notion of a 'wheel' itself does not include functions which loads and saves it from a database, so perhaps method 1 would be considered bad OOP design.
Both seem a bit off...
Method 1
For one thing, Load() should be a static factory in this case. This usage is a bit obtuse:
Wheel johnWheel = new Wheel();
johnWheel.Load(5);
Between those two lines of code, what is johnWheel? Is it in anything approaching a valid state? If not, then it seems like its construction is a little broken. OO principles would suggest encapsulating that into a single operation rather than expecting consuming code to perform multiple sequential operations every time. If it's a static factory, the usage is simpler:
Wheel johnWheel = Wheel.Load(5);
Method 2
This one is more of a naming concern than a structure concern. DBUtils? That's going to turn into a dumping ground for unrelated functionality quickly. You want to avoid that. How about something like this?:
class WheelRepository
{
public static Wheel Get(int id)
{
// ...
}
public static void Save(Wheel wheel)
{
// ....
}
}
As an object (this is still OOP after all), a WheelRepository represents (and therefore encapsulates) very specific functionality whereas a DBUtils doesn't.
Conclusion
I generally prefer method 2 in a structural sense, because the business object (Wheel) shouldn't know anything about the database (WheelRepository). The former is a core portable business concern, the latter is a periphery infrastructure concern. My only caveat is that I'd recommend standard patterns for improving method 2, such as a combination of the Repository Pattern and the Unit Of Work pattern, for example.
You should create a separate class that handles database connections and the creation/destruction of these connections. That way, the wheel is a separate entity from the database it is using.
Go with method 2.
I would go with Method 2 (like laiello proposed). I would however not name the class DbUtils but more something like WheelDao or WheelRepository (if for instance your Wheel class is an Root entity in your domain model).
If however you go with Method 1 the load(id) method should be static. Since it is not called on a particular instance of an object but it rather produces a new instance of an object. This is unlike the save() method for which it is correct to be called on a specific instance of Wheel.

Is this a ddd anti-pattern?

Is it a violation of the Persistance igorance to inject a repository interface into a Entity object Like this. By not using a interface I clearly see a problem but when using a interface is there really a problem? Is the code below a good or bad pattern and why?
public class Contact
{
private readonly IAddressRepository _addressRepository;
public Contact(IAddressRepository addressRepository)
{
_addressRepository = addressRepository;
}
private IEnumerable<Address> _addressBook;
public IEnumerable<Address> AddressBook
{
get
{
if(_addressBook == null)
{
_addressBook = _addressRepository.GetAddresses(this.Id);
}
return _addressBook;
}
}
}
It's not exactly a good idea, but it may be ok for some limited scenarios. I'm a little confused by your model, as I have a hard time believing that Address is your aggregate root, and therefore it wouldn't be ordinary to have a full-blown address repository. Based on your example, you probably are actually using a table data gateway or dao rather than a respository.
I prefer to use a data mapper to solve this problem (an ORM or similar solution). Basically, I would take advantage of my ORM to treat address-book as a lazy loaded property of the aggregate root, "Contact". This has the advantage that your changes can be saved as long as the entity is bound to a session.
If I weren't using an ORM, I'd still prefer that the concrete Contact repository implementation set the property of the AddressBook backing store (list, or whatever). I might have the repository set that enumeration to a proxy object that does know about the other data store, and loads it on demand.
You can inject the load function from outside. The new Lazy<T> type in .NET 4.0 comes in handy for that:
public Contact(Lazy<IEnumerable<Address>> addressBook)
{
_addressBook = addressBook;
}
private Lazy<IEnumerable<Address>> _addressBook;
public IEnumerable<Address> AddressBook
{
get { return this._addressBook.Value; }
}
Also note that IEnumerable<T>s might be intrinsically lazy anyhow when you get them from a query provider. But for any other type you can use the Lazy<T>.
Normally when you follow DDD you always operate with the whole aggregate. The repository always returns you a fully loaded aggregate root.
It doesn't make much sense (in DDD at least) to write code as in your example. A Contact aggregate will always contain all the addresses (if it needs them for its behavior, which I doubt to be honest).
So typically ContactRepository supposes to construct you the whole Contact aggregate where Address is an entity or, most likely, a value object inside this aggregate.
Because Address is an entity/value object that belongs to (and therefore managed by) Contact aggregate it will not have its own repository as you are not suppose to manage entities that belong to an aggregate outside this aggregate.
Resume: always load the whole Contact and call its behavior method to do something with its state.
Since its been 2 years since I asked the question and the question somewhat misunderstood I will try to answer it myself.
Rephrased question:
"Should Business entity classes be fully persistance ignorant?"
I think entity classes should be fully persistance ignorant, because you will instanciate them many places in your code base so it will quickly become messy to always have to inject the Repository class into the entity constructor, neither does it look very clean. This becomes even more evident if you are in need of injecting several repositories. Therefore I always use a separate handler/service class to do the persistance jobs for the entities. These classes are instanciated far less frequently and you usually have more control over where and when this happens. Entity classes are kept as lightweight as possible.
I now always have 1 Repository pr aggregate root and if I have need for some extra business logic when entities are fetched from repositories I usually create 1 ServiceClass for the aggregate root.
By taking a tweaked example of the code in the question as it was a bad example I would do it like this now:
Instead of:
public class Contact
{
private readonly IContactRepository _contactRepository;
public Contact(IContactRepository contactRepository)
{
_contactRepository = contactRepository;
}
public void Save()
{
_contactRepository.Save(this);
}
}
I do it like this:
public class Contact
{
}
public class ContactService
{
private readonly IContactRepository _contactRepository;
public ContactService(IContactRepository contactRepository)
{
_contactRepository = contactRepository;
}
public void Save(Contact contact)
{
_contactRepository.Save(contact);
}
}

Unit of Work and L2S DataContext

Quick Q for you pattern experts out there.
I want a Repository pattern that is de-coupled from the actual data access tech, as I've not decided on that yet and I want it to be flexible. So, this could be L2S, L2E, NHibernate, Lightspeed or anything.
But I'm getting confused about this UnitOfWork thing.
In the L2S world, this seems to be your DataContext.
But what about a non-L2S world, imagine I was using hand-written SQL for example.
My question is who does what? In my Repo.Save() method, should this call the UnitOfWork.Commit which then generates the required INSERT/UPDATE SQL ?
Not expecting a definite answer, but some discussion would be good, just to make sure I'm on the right track!
Thanks
Repositories certainly can call commit/save/submit on the unit of work object, or they could leave this up to the consumer. I prefer the latter scenario, because it enables the consumer to control the lifetime of the unit of work instance, which allows the consumer to engage multiple repositories:
// outside the repository layer
// int productId defined elsewhere
// int quantity defined elsewhere
IUnitOfWork unitOfWork = ... instantiate/get a new instance of your DataContext ...
ProductRepository productRepository = new ProductRepository(unitOfWork);
Product product = productRepository.GetById(productId);
Order order = new Order();
order.AddOrderLine(product, quantity);
OrderRepository orderRepository = new OrderRepository(unitOfWork);
orderRepository.Add(order);
unitOfWork.Save(); // This calls SubmitChanges() on the DataContext