Benefits of implementation driven & dependency injection vs cost of maintaining implementations - spring

I am starting an application that I would like to build quickly and will be later developed by 20+ developers.
Knowing what you know about DI in an environment with multiple developers, would you go with DI for a new application you'd like to build relatively fast?
The costs of using DI to me right now, would be lines of code written and generated vs not using an interface for every object. And down the line I am hoping DI doesn't become a performance problem because of reflection.

DI is basically not about frameworks. If you just add your dependencies, for example, as parameters to the constrictor, then you're doing DI. Actually you don't even need to create interfaces (though that would help testing. Introduce interface later is a simple refactoring in languages like Java). DI just removes the responsibility of creation from the user of the class.
The single greatest cost in my head would be change of mind. To learn to think DI.
benefits include easier testing. Separation of concern and more.

Simply said, doing Object-oriented development without dependency injection is bad. Very bad. Dependency injection is in my opinion the root of well-understood OO development: separation of concerns, loose coupling between independent components, coding in layers, all of that is done using DI. And also, it makes testing incredibly easier, and allows techniques like TDD, mocking (BDD), etc.
As Shakyamuni said in his answer, DI is not about the framework you use. Spring did not invent DI, it just proposes a solution to achieve it. So if your original question is "should we use Spring", then I'd say it's a question of personal taste. You can achieve exactly the same result if you do it yourself. I've worked in project with or without containers (Spring, pico, etc.) and they all have their benefits and drawbacks. My personal preference, though, is not to use any of it and manage your DI yourself.
This is DI:
// constructor
public MyClass(MyDependencyInterface injected) {
this.dependency = injected;
}
or that:
// setter injection
public void setDependency(MyDependencyInterface injected) {
this.dependency = injected;
}
And down the line I am hoping DI doesn't become a performance problem because of reflection.
No idea what you mean by that. DI does not require reflection.

I would definitely advocate DI, particularly when there are a lot of developers.
This allows each developer to write and test their own code without relying on injected components being developed outside of their control.
It can also facilitate interface definitions so everyone knows what functionality is available from which components.

The basic problem in Java is that when you in class A do a new B() this mean that class A is very tightly bound to class B at the byte code level.
This is typically a good thing as it means that the resulting application becomes very sturdy as all the "bricks" are very well "glued together".
You frequently, however, need to postpone some design issues to deploy time (and occasionally even runtime) and the way to handle this in Java has traditionally been to delegate to a Factory which perhaps even in turn delegates to another factory etc, until you reach the place where you make the decision. This is typically done with a property file containing either flags corresponding to if-statements in the code (which requires the programmer to foresee all situations when writing the code), or class names to resolve with Class.forName() (which is brittle as the compiler cannot help).
The advantage of Dependency Injection is that you sidestep the hard binding of the newoperator by delegating the responsibility to create an appropriate object outside of your own code (to a container but could as well be a deity). You create some very clear cut-lines where you can put things together and for those DI-frameworks providing code configuration (like Guice) the result can be as sturdy as well as modular.
Note that coding to interfaces makes it easier to identify the right places to make incisions for the cut-lines, because interface usages usually corresponds to injection points.

Related

Is Spring more suitable for business-logic-focused apps?

After reading the official doc of Spring, I got this impression:
"Spring, specifically its IoC container, suits better for apps that requires only one instance of most classes".
For example we have an online shopping app. Its business logic is divided into
Order process
Payment process
and encapsulating these two parts into classes is for better code organisation rather than for implementing any functionalities, and Spring makes it easier to inject the same instance to whichever object needs it, to avoid frequent and redundant new.
However, in a Mario-like game, we might have a class Coin that requires hundreds of individual instances, and hence Spring can't be applied in this case ('cause I think #qualifier makes more mess than the good part brought by IoC).
Is the above correct?
You're correct in thinking that you wouldn't inject an object that only applies in a narrow scope.
I could see objects with Request scope that are not Singleton. Spring has supported that from the beginning.
Method scope variables should not be under Spring's control. There's nothing wrong with calling new.
You should understand Spring better before you make judgements about its efficacy.

Multiple Controllers appropriate with one entity in spring framework

I'm starting to develop website that use the spring framework.I have three controller.There are newCustomerController,editCustomerController and deleteCustomerController.These controllers are mapped with view that use for create update and delete, but I create only customer.
So, I would like to know.Is it appropriate to declare the controllers like this.
Thank
The answer to this question is subjective and maybe more a topic for https://softwareengineering.stackexchange.com/. However, there is something very spring related about it that I would like to comment.
There are a few principles that attempt at guiding developers of how to strike a good balance when thinking about designing the classes. One of those is the Single responsibility principle.
In object-oriented programming, the single responsibility principle
states that every class should have a single responsibility, and that
responsibility should be entirely encapsulated by the class. All its
services should be narrowly aligned with that responsibility
A catchier explanation is
A class or module should have one, and only one, reason to change.
However, its still often hard to reason about it properly.
Nevertheless, Spring gives you means for it (think of this statement as a poetic freedom of interpretation). Embrace constructor based dependency injection. There are quite a few reasons why you should consider constructor based dependency injection, but the part relevent to your question is adressed in the quote from the blog
An often faced argument I get is: “Constructors just get too verbose
if I have 6 or 7 dependencies. With fields only, this is fine”.
Awesome, you’ve effectively worked around a clear indicator that the
code you write is doing way too much. An increase in the number of
dependencies a type has should hurt, as it makes you think about
whether you should split up the component into multiple ones.
In other words, if you stick to constructor based injection, and your constructor turns a bit ugly, the class is most likely doing too much and you should consider redesigning.
The same works the other way around, if your operations are a part of the logical whole (like CRUD operations), and they use the same dependencies (now "measurable" by the count and the type of the injected deps) with no clear ideas of what can cause the operations to evolve independently of each other, than no reason to split to separate classes/components.
It should be better if you define one controller for Customer class and in that class you should have all methods related to customer operations (edit,delete,create and read).

Laravel4: Will not using the repository pattern hurt my project in the long run?

I'm reading Taylor Otwell's book in which he suggests using the repository pattern. I get the theory behind it. That it's easy to switch implementations and decouples your code. I get the code too. And it is very nice to be able to switch by App::bind() with some other implementation. But I've been thinking for the last two hours how I should approach things for a new CRM I'm building. Almost no code yet but it might end up big.
I would prefer to simply use eloquent models and collection injected through the controller. That should make everything testable if I'm not mistaken.. . Allowing for mocks and such.
Does the repository pattern maybe offer any benefits towards scalability? In cases when more servers or resources are needed..
And why would anybody want to replace the Eloquent ORM once committed to its use? I mean most projects need a relational database. If I would build a UserRepositoryInterface and an implementation DbUserReponsitory, I cannot see when I would ever need or want to switch that with something else. This would count for most entities in my project (order, company, product, ...). Maybe to use another ORM to replace Eloquent? But I don't see myself doing this for this project.
Or am I missing something? My main concern is to have code that is readable and easy to test. Haven't really been testing that well up to now :)
It does not necessarily mean that ignoring the Repository pattern will give you headaches on the long run, but it certainly makes re-factoring code much easier thus you can easily write Test repositories and bind them with your controllers to easily test your business logic.
So even if it is not likely that you will replace Eloquent or any other part, encapsulating chunks of logic and operations in repositories will still be beneficial for you.
Dependency injection is nothing new in terms of design patterns, will it hurt your code, not necessarily. Will it hurt your ability to easily write / re-factor old code and swap it in easily... absolutely it will.
Design patterns exist as solutions to common problems. I would tell you straight away that ignoring the IoC container in Laravel and not dependency injecting will have a big impact on you later down the line if you're writing complex applications. Take for example that you may want different bindings based on request type, user role / group, or any other combination of factors, by swapping out the classes without impacting your calling code will be beyond invaluable to you.
My advice, do not ignore the IoC container at all.
As a sidenote, Service Providers are also your friend, I'd suggest you get well acquainted with them if you want to write great apps in Laravel 4.

Avoiding singletons and global variables - but what about caching, providers, controllers, ...?

I'm currently "updating" my development knowledge especially on TDD principles by reading books, articles on the web and watching videos. Something that pops up everywhere is the warning, not to use global state variables as they make the system fragile and less easy to test and since singletons are not much better or rather the same, not to use those either.
Now I'm wondering: Can I actually be consistent about this?
What about a cache, that the application uses so it doesn't have to look up frequently used database objects again and again? I NEED a single instance of that cache to be passed around, otherwise what would be the point?
Another example are DAOs or as we call them providers. They do nothing but provide JPA database access for us but otherwise have no state. So why not make them singleton?
And controllers in the web frontend? All they do is react to requests - again with no internal state.
Wouldn't it waste a lot of performance instantiating the latter two again and again? I'm sure there are a few more examples where this applies.
Maybe it's okay to use singletons, as long as they don't have any member variables except for finals?
And even if they have member variables but all of them are injected into them, it should be save to use them, as any object, singleton or not, can modify injected objects so it really doesn't make any difference.
I'm a bit confused about this whole "avoid singletons" business, I'm not even sure I fully understand the risks involved. But most of all I'd like to hear thoughts on the above examples, as those are the most common places in our application where we use singletons.
Thanks!
btw: we're using springs dependency injection, so how to do it is not my question, rather why avoid it and where it is okay.
The issue with Singletons is not so much the Singleton design pattern per se as their being overused under the covers as stateful global God objects all over applications.
That way of using them has 2 major drawbacks :
Dependencies on singletons are hidden dependencies, and objects are tightly coupled to them, which hampers discoverability, maintainability and testability of the code.
Objects depend on singletons they don't have any idea which state they're in. The order in which a singleton's behaviors are used here and there starts to become important, and you start seeing "MySingleton.Initialize()"s all over the place, which is dangerous and defeats the whole purpose of having a single instance.
Only singletons that trump these pitfalls are IMO worth considering - that means stateless, immutable objects that somehow get injected into their consumers and can be replaced with other instances with the same contract.
Other than that, Singleton-ification is most often premature optimization applied on the wrong objects.
This blog post pretty much sums it up : http://blogs.msdn.com/b/scottdensmore/archive/2004/05/25/140827.aspx
You are absolutely correct -- there are cases when single instance is needed. However "avoid singletons" business does not tell that they are not needed. In my understanding it states that singleton behavior should be added by Dependency Container, not by static instance.
That would allow you to mock it in your unittests while having only one instance in production. you may find this link useful: Object Scopes in Ninject
The problem with singletons and global variables is that we need them but that most programming languages offer only one "global" context.
Imagine that you could do this:
Global g1 = new Global();
g1.run( ... some code ... );
Global g2 = new Global();
g2.run( ... some code ... );
When the code is run by g2, none of the singletons and globals from the run of g1 are visible. This is actually what we want: A efficient way to say "okay, I'm done with the globals and stuff, get rid of them".
The solution is a factory which can build all your singletons and globals for you and put them into the code in the right place. Then you can create new instances of this factory (along with new singletons and globals) in your tests as you need it.
This is what "dependency injection" is all about. Here is a short introduction.

Test driven development: Inversion of Control (IOC)

I googled and read some good answers/posts on IOC and do understand the overall concept. I have an existing framework (not very well designed) and TDD is an after thought to write some NUNIT test fixtures. Can I use IOC on an existing code base with out changing the existing code base? Or IOC is used when we are designing application from scratch?
I use this technique for converting legacy code to dependency injected beauty:
If I create just one object for a class, make it a field and create it in the constructor.
If I create more than one object, make a factory for that object and create the factory in the constructor.
Put interfaces on the objects (I like the "IDoThisForYou" style as it allows me to understand the roles of classes easily, but whatever works for you).
Cascade the constructors - make one constructor new up the objects and pass them into the other by the interface.
Now you can mock and DI the interfaces in your tests. The actual cascade is simple enough that you can get by with inspection. Eventually you'll get to the point where you can use a container and then you'll delete the first constructor; this is an easy first step towards that.
(Don't mock out domain objects with heavy data - it's not worth it.)
Good luck!
It doesn't have to be from scratch, but obviously you would structure things to allow IOC to be pretty painless if you did,
But it can be patched in.... depending on how decoupled your system is, that may or may not be a big job. Essentially its an object creation pattern, so it only effect the points of creation.... if thats done willy nilly all over the place, then it will take a bit of clean up.
I'd start with getting unit tests in place first. Worry about IOC as a second concern, its not actually needed to do TDD

Resources