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.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With