Why controller has to call interface on use cases in Clean Architecture - clean-architecture

In Robert Martin's clean architecture book, I appears the Controller has to call an interface to the UseCase. However, since all dependencies point inward, meaning the Adapter layer has a dependency on the Application layer, then why then need for an interface? I should be able to new up the Usecase directly

Depending of the size and the complexity of ur project it would be perfectly fine to simply create the use case interactor with new in the controller and use the implementation directly.
However there are a few advantages of using interfaces (input ports):
Testing: in case u want to unit test ur controller code an interface would allow u to mock away the use case interactor
Dependencies: in case ur use case interactor has dependencies to domain services or repositories then u want to "wire those up" in ur "main component" and just pass the use case interactor via interface (input port) to the controller
For a more in depth discussion on controllers and presenters pls have a look at my blog post: http://www.plainionist.net/Implementing-Clean-Architecture-Controller-Presenter/

Related

When to use models vs service in Laravel?

I have been using for a while but still I am confuse on what to include in my controllers specifically "When should I use Model and When to Use Service"?
I am confused if I am making the right thing.
I would suggest to never use models directly into the controllers.. Adopt the repository-pattern which enables the use of dependency injection of services into the controller.. Use Service Layer to contain the business logic.. In this way all the related codes would be onto similar layer.
Reference for repository pattern:
http://heera.it/laravel-repository-pattern#.VuJcVfl97cs
Please don't use model directly in your controller, unless if you are building a very simple application but for a large application, it would be good to use a repository. Kindly take a look at this tutorial https://bosnadev.com/2015/03/07/using-repository-pattern-in-laravel-5/

how to use spring 3.0 without service?

I am using spring 3.0 with annotation which i am creating dao interface , then dao implementation class,
then creating service interface and then creating service implementation class.
and using object of service implementation into controller. this process is too lengthy.
can i use only dao class and directly use it in controller?
#service
#controller
public class MyController { ... }
You can but you really really really shouldn't. If you have any plans of putting this code into production, then you need to keep your layers well defined. This is because each layer has a different responsibility.
Your DAO layer is responsible for all database access. It doesn't care what object you want, what you want to do with it, and when you want it done. It only cares about how it's done.
Your Service layer is responsible for what you want to do to your objects. It contains all of your business logic, convenience methods and may use multiple DAO's inside a single service. Your service layer is where you handle your database transactions as well.
Your controller layer is responsible for how you want to show your data to the user. It only contains services and minimal logic concerned with how to display the data returned by your service layer.
I think there are 2 distinct questions being asked here :
Is it really necessary to have all three layers : web layer, service layer, and DAO ?
and :
Do Spring beans necessarily need to implement and interface and to bve (auto)wired by interface rather thant concrete class ?
The answer to both is the same : it is not a necessity, but it is strongly recommended for anything other thant trivial projects.
For the first question, yes it is better so separate concerns in different layers. However I must admint that my controllers sometimes access the DAOs directly for simple read-only tasks in some projects. Sometimes the service layer seems like too much when all it does is to map the DAO methods. However I always use a service layer for transactional business logic that actually modifies the data.
For the second question : Spring can, without problem, instantiate and inject beans that don't implement any interface. However you will start to have problems if you use more advanced stuff linked to aspect-oriented programming, the most common being the #Transactional annotation. In this case Spring has to create proxies to your objects, and it is all simpler to create proxies of interfaces. Ohterwise it has to manipulate bytecode and it introduces limitations.
Perhaps more importantly, "programming to an interface" is a good practice regardless if you are using Spring or not, or even Java or anothrer language. A simple google search will bring up many good articles on this, or SO questions such as this one.
So again, while you can live well without both things in the short term, both will make your life much better in the long term.

Example use-cases for using Dependency Injection with the Play Framework

I am a big fan of Dependency Injection and the Play Framework, but am having trouble seeing how the two could be exploited together.
There are modules for Spring and Guice, but the way that Play works makes it hard for me to see how DI could be beneficial beyond some quite simple cases.
A good example of this is that Play expects JPA work to be done by static methods associated with the entity in question:
#Entity
Person extends Model {
public static void delete(long id) {
em().find(id).remove();
}
//etc
}
So there is no need for a PersonManager to be injected into controllers in the way it might for a Spring J2EE application. Instead a controller just calls Person.delete(x).
Obviously, DI is beneficial when there are interfaces with external systems, as the concrete implementation can be mocked for testing etc., but I don't see much benefit for a self-contained Play application.
Does anyone have any good examples? Does anyone use it to inject a Manager-style class into Controllers so that a number of operations can be done within the same transaction, for example?
I believe from this sentence you wrote:
"Does anyone have any good examples? Does anyone use it to inject a Manager-style class into Controllers so that a number of operations can be done within the same transaction, for example?"
that before answering the DI question I should note something: transactions are managed automatically by Play. If you check the model documentation you will see that a transaction is automatically created at the beginning of a request, and committed at the end. You can roll it back via JPA or it will be rolled back if an exception is raised.
I mention this because from the wording of your sentence I'm not sure if you are aware of this.
Now, on DI itself, in my (not-so-extensive) experience with DI, I've seen it used mainly to:
Load the ORM (Hibernate) factory/manager
Load Service classes/DAOs into another class to work with them
Sure, there are more scenarios, but these probably cover most of the real usage. Now:
The first one is irrelevant to Play as you get access to your JPA object and transaction automatically
The second one is quite irrelevant too as you mainly work with static methods in controllers. You may have some helper classes that need to be instantiated, and some may even belong to a hierarchy (common interface) so DI would be beneficial. But you could just as well create your won factory class and get rid of the jars of DI.
There is another matter to consider here: I'm not so sure about Guice, but Spring is not only DI, it also provides a lot of extra functionalities which depend on the DI module. So maybe you don't want to use DI in Play, but you want to take advantage of the Spring tools and they will use DI, albeit indirectly (via xml configuration).
The problem in my humble opinion on the static initialization approach of Play! is that it makes testing harder. Once you approach the HTTP vs Object Orientation problem with static members and objects that carries the HTTP message data (request and response) you make a trade of having to create new instances for each request by the ability of make your objects loosely coupled with the rest of your project classes.
One good example of a different design are servlets, it also extends a base class but it approaches the problem with a single instance creation (by default, because there are configurations that enable more instances).
I believe that maybe a mix of the two approaches would be better, having a singleton of each controller would give the same characteristics of a full static class and would allow dependency injection of some kinds of object. But not the objects with request or session scope, once the controller would need to be created every new request. Moreover it would improve testability by inverting the control of dependency injection, thus allowing arbitrary injection points.
Dependencies would be injected by the container or by a test, probably using mocks for the heavy stuff that much likely would already have been tested before.
In my point of view, this static model pushes the developer away from testing controllers because extending FunctionalTest starts the application server, thus paying the price of heavy objects like repositories, services, crawlers, http clients, etc. I don't want to wait a lot of objects to be bootstrapped just to check if some code was executed on the controller, tests should be quick and clear to make developers love them as their programming assistant/guide.
DI is not the ultimate solution to use everywhere... Don't use DI just because you have it in your hands... In play, you don't need DI to develop controllers/models etc... but sometimes it could be a nice design: IMO, you could use it if you have a service with a well know interface but you would like to develop this service outside Play and test it outside play and even test your play project with just a dummy service in order NOT to depend on the full service implementation. Therefore DI can be interesting: you plug the service loosely in play. In fact, this is the original use case for DI afaik...
I just wrote a blog post about setting up a Play Framework application with Google Guice. http://geeks.aretotally.in/dependency-injection-with-play-framework-and-google-guice
I see some benefits, especially when a component of your application requires a different behavior based on a certain context or something like that. But I def believe people should be selective about what goes into a DI context.
It shows again that you should only use dependencies injection if you really have a benefit. If you have complex services it's useful, but in many cases it's not. Read the chapter about models in the play-documentation.
So to give you an example where you can use DI with play. Perhaps you must make a complex calculation, or you create a pdf with a report-engine. There I think DI can be useful, specially for testing. There I think the guice-module and spring-module are useful and can help you.
Niels
As of a year and some change later, Play 2.1 now has support for dependency injection in controllers. Here's their demo project using Spring 3, which lays it out pretty clearly.
Edit: here's another example using Guice and Scala, if that's your poison.

Test Driven Development For Complex Methods involving external dependency

I am implementing a Service Contract for WCF Service.
As per TDD I wrote a test case to just pass it using hardcoded values.
After that I started to put real logic into my Service implementation. The actual logic relies on 3-4 external service and database.
What should I do to my original test case that I wrote ?
If i Keep it same in order to make test pass it will have to call several other external services.
So I have question in general what should I do if I write a test case for a Business Facade first using TDD and later when I add real logic, if it involves external dependency.
Utilize a mocking framework (with dependency inversion or just a factory) so you can inject fake dependencies into the object. These can then then just return canned responses and/or be checked that the class utilizes the dependencies how you intended.
As an example, if your code calls a repository to save, we don't really care in the business method test that the repository did actually save to a persistance store, only that it got called and returned some data if required. What you're really testing is how your code reacts to what the dependency returned, or if it was utilzed correctly - but not the dependency's actual functionality
Ideally the first test should have been representative of how the class/method will work and return data, so the test would still be valid once you're finished.

Implementing a service layer in an MVC architecture

How would one typically implement a service layer in an MVC architecture? Is it one object that serves all requests to underlying business objects? Or is more like an object that serves different service objects that in their turn interact with business objects?
So:
Controller -> Service -> getUserById(), or:
Controller -> ServiceManager -> getUserService() -> getUserById()
Also, if the latter is more appropriate, would you configure this ServiceManager object in a bootstrap? In other words, register the different services that you will be needing for your app to the service manager in a bootstrap?
If none of the above is appropriate, what would help me get a better understanding of how a service layer should be implemented?
Thank you in advance.
The way I read this question, there's really two things that should be answered:
A) I would prefer splitting "Service" into "CustomerService" and "OrderService", in other words grouped by domain concepts.
B) Secondly I'd use dependency injection to get the proper service directly where I need it, so I'm basically using alt 1. The added abstraction in alternative 2 provides no additional value for me, since the IoC container does the important part.
Using a "facade" is one way to go:
"A facade is an object that provides a simplified interface to a larger body of code"
I personally prefer #2, and yes, it would generally be configured in a bootstrap, or the dependencies would be resolved using some sort of IoC container to give you the actual concrete instances.
I would also like to comment, and yes I understand this is probably more of a personal preference. Try to avoid using the name "Service" layer for these objects. refer to them as repositories or something else. if you use service, that term becomes overloaded ... because then devs are like, "do you mean like, a rest or wcf service?". trust me, we did that with a recent project, and we confuse ourselves all the time when we're talking about where to make code changes :-P

Resources