The Clean Architecture suggests to let a use case interactor call the actual implementation of the presenter (which is injected, following the DIP) to handle the response/display. However, I see people implementing this architecture, returning the output data from the interactor, and then let the controller (in the adapter layer) decide how to handle it. Is the second solution leaking application responsibilities out of the application layer, in addition to not clearly defining input and output ports to the interactor?

Input and output ports

Considering the Clean Architecture definition, and especially the little flow diagram describing relationships between a controller, a use case interactor, and a presenter, I'm not sure if I correctly understand what the "Use Case Output Port" should be.

Clean architecture, like hexagonal architecture, distinguishes between primary ports (methods) and secondary ports (interfaces to be implemented by adapters). Following the communication flow, I expect the "Use Case Input Port" to be a primary port (thus, just a method), and the "Use Case Output Port" an interface to be implemented, perhaps a constructor argument taking the actual adapter, so that the interactor can use it.

Code example

To make a code example, this could be the controller code:

Presenter presenter = new Presenter();
Repository repository = new Repository();
UseCase useCase = new UseCase(presenter, repository);
useCase->doSomething();

The presenter interface:

// Use Case Output Port
interface Presenter
{
    public void present(Data data);
}

Finally, the interactor itself:

class UseCase
{
    private Repository repository;
    private Presenter presenter;

    public UseCase(Repository repository, Presenter presenter)
    {
        this.repository = repository;
        this.presenter = presenter;
    }

    // Use Case Input Port
    public void doSomething()
    {
        Data data = this.repository.getData();
        this.presenter.present(data);
    }
}

On the interactor calling the presenter

The previous interpretation seems to be confirmed by the aforementioned diagram itself, where the relation between the controller and the input port is represented by a solid arrow with a "sharp" head (UML for "association", meaning "has a", where the controller "has a" use case), while the relation between the presenter and the output port is represented by a solid arrow with a "white" head (UML for "inheritance", which is not the one for "implementation", but probably that's the meaning anyway).

Furthermore, in this answer to another question, Robert Martin describes exactly a use case where the interactor calls the presenter upon a read request:

Clicking on the map causes either the placePinController to be invoked. It gathers the location of the click, and any other contextual data, constructs a placePinRequest data structure and passes it to the PlacePinInteractor which checks the location of the pin, validates it if necessary, create a Place entity to record the pin, constructs a EditPlaceReponse object and passes it to the EditPlacePresenter which brings up the place editor screen.

To make this play well with MVC, I could think that the application logic that traditionally would go into the controller, here is moved to the interactor, because we don't want any application logic to leak outside the application layer. The controller in the adapters layer would just call the interactor, and maybe do some minor data format conversion in the process:

The software in this layer is a set of adapters that convert data from the format most convenient for the use cases and entities, to the format most convenient for some external agency such as the Database or the Web.

from the original article, talking about Interface Adapters.

On the interactor returning data

However, my problem with this approach is that the use case must take care of the presentation itself. Now, I see that the purpose of the Presenter interface is to be abstract enough to represent several different types of presenters (GUI, Web, CLI, etc.), and that it really just means "output", which is something a use case might very well have, but still I'm not totally confident with it.

Now, looking around the Web for applications of the clean architecture, I seem to only find people interpreting the output port as a method returning some DTO. This would be something like:

Repository repository = new Repository();
UseCase useCase = new UseCase(repository);
Data data = useCase.getData();
Presenter presenter = new Presenter();
presenter.present(data);

// I'm omitting the changes to the classes, which are fairly obvious

This is attractive because we're moving the responsibility of "calling" the presentation out of the use case, so the use case doesn't concern itself with knowing what to do with the data anymore, rather just with providing the data. Also, in this case we're still not breaking the dependency rule, because the use case still doesn't know anything about the outer layer.

However, the use case doesn't control the moment when the actual presentation is performed anymore (which may be useful, for example to do additional stuff at that point, like logging, or to abort it altogether if necessary). Also, notice that we lost the Use Case Input Port, because now the controller is only using the getData() method (which is our new output port). Furthermore, it looks to me that we're breaking the "tell, don't ask" principle here, because we're asking the interactor for some data to do something with it, rather than telling it to do the actual thing in the first place.

To the point

So, is any of these two alternatives the "correct" interpretation of the Use Case Output Port according to the Clean Architecture? Are they both viable?

  • 3
    Cross-posting is strongly discouraged. If this is where you want your question to live, then you should delete it from Stack Overflow. – Robert Harvey Sep 8 '17 at 15:16
up vote 33 down vote accepted

The Clean Architecture suggests to let a use case interactor call the actual implementation of the presenter (which is injected, following the DIP) to handle the response/display. However, I see people implementing this architecture, returning the output data from the interactor, and then let the controller (in the adapter layer) decide how to handle it.

That's certainly not Clean, Onion, or Hexagonal Architecture. That is this:

enter image description here

Not that MVC has to be done that way

enter image description here

You can use many different ways to communicate between modules and call it MVC. Telling me something uses MVC doesn't really tell me how the components communicate. That isn't standardized. All it tells me is that there are at least three components focused on their three responsibilities.

Some of those ways have been given different names: enter image description here

And every one of those can justifiably be called MVC.

Anyway, none of those really capture what the buzzword architectures (Clean, Onion, and Hex) are all asking you to do.

enter image description here

Add the data structures being flung around (and flip it upside down for some reason) and you get:

enter image description here

One thing that should be clear here is that the response model does not go marching through the controller.

If you are eagle eye'd, you might have noticed that only the buzzword architectures completely avoid circular dependencies. Importantly, it means the impact of a code change won't spread by cycling through components. The change will stop when it hits code that doesn't care about it.

Wonder if they turned it upside down so that the flow of control would go through clockwise. More on that, and these "white" arrow heads, later.

Is the second solution leaking application responsibilities out of the application layer, in addition to not clearly defining input and output ports to the interactor?

Since communication from Controller to Presenter is meant to go through the application "layer" then yes making the Controller do part of the Presenters job is likely a leak. This is my chief criticism of VIPER architecture.

Why separating these is so important could probably be best understood by studying Command Query Responsibility Segregation.

Input and output ports

Considering the Clean Architecture definition, and especially the little flow diagram describing relationships between a controller, a use case interactor, and a presenter, I'm not sure if I correctly understand what the "Use Case Output Port" should be.

It's the API that you send output through, for this particular use case. It's no more than that. The interactor for this use case doesn't need to know, nor want to know, if output is going to a GUI, a CLI, a log, or an audio speaker. All the interactor needs to know is the very simplest API possible that will let it report the results of it's work.

Clean architecture, like hexagonal architecture, distinguishes between primary ports (methods) and secondary ports (interfaces to be implemented by adapters). Following the communication flow, I expect the "Use Case Input Port" to be a primary port (thus, just a method), and the "Use Case Output Port" an interface to be implemented, perhaps a constructor argument taking the actual adapter, so that the interactor can use it.

The reason the output port is different from the input port is that it must not be OWNED by the layer that it abstracts. That is, the layer that it abstracts must not be allowed to dictate changes to it. Only the application layer and it's author should decide that the output port can change.

This is in contrast to the input port which is owned by the layer it abstracts. Only the application layer author should decide if it's input port should change.

Following these rules preserves the idea that the application layer, or any inner layer, does not know anything at all about the outer layers.


On the interactor calling the presenter

The previous interpretation seems to be confirmed by the aforementioned diagram itself, where the relation between the controller and the input port is represented by a solid arrow with a "sharp" head (UML for "association", meaning "has a", where the controller "has a" use case), while the relation between the presenter and the output port is represented by a solid arrow with a "white" head (UML for "inheritance", which is not the one for "implementation", but probably that's the meaning anyway).

The important thing about that "white" arrow is that it lets you do this:

enter image description here

You can let the flow of control go in the opposite direction of dependency! That means the inner layer doesn't have to know about the outer layer and yet you can dive into the inner layer and come back out!

Doing that has nothing to do with using the "interface" keyword. You could do this with an abstract class. Heck you could do it with a (ick) concrete class so long as it can be extended. It's simply nice to do it with something that focuses only on defining the API that Presenter must implement. The open arrow is only asking for polymorphism. What kind is up to you.

Why reversing the direction of that dependency is so important can be learned by studying the Dependency Inversion Principle. I mapped that principle onto these diagrams here.

On the interactor returning data

However, my problem with this approach is that the use case must take care of the presentation itself. Now, I see that the purpose of the Presenter interface is to be abstract enough to represent several different types of presenters (GUI, Web, CLI, etc.), and that it really just means "output", which is something a use case might very well have, but still I'm not totally confident with it.

No that's really it. The point of making sure the inner layers don't know about the outer layers is that we can remove, replace, or refactor the outer layers confident that doing so wont break anything in the inner layers. What they don't know about won't hurt them. If we can do that we can change the outer ones to whatever we want.

Now, looking around the Web for applications of the clean architecture, I seem to only find people interpreting the output port as a method returning some DTO. This would be something like:

Repository repository = new Repository();
UseCase useCase = new UseCase(repository);
Data data = useCase.getData();
Presenter presenter = new Presenter();
presenter.present(data);
// I'm omitting the changes to the classes, which are fairly obvious

This is attractive because we're moving the responsibility of "calling" the presentation out of the use case, so the use case doesn't concern itself with knowing what to do with the data anymore, rather just with providing the data. Also, in this case we're still not breaking the dependency rule, because the use case still doesn't know anything about the outer layer.

The problem here is now whatever knows how to ask for the data has to also be the thing that accepts the data. Before the Controller could call the Usecase Interactor blissfully unaware of what the Response Model would look like, where it should go, and, heh, how to present it.

Again, please study Command Query Responsibility Segregation to see why that's important.

However, the use case doesn't control the moment when the actual presentation is performed anymore (which may be useful, for example to do additional stuff at that point, like logging, or to abort it altogether if necessary). Also, notice that we lost the Use Case Input Port, because now the controller is only using the getData() method (which is our new output port). Furthermore, it looks to me that we're breaking the "tell, don't ask" principle here, because we're asking the interactor for some data to do something with it, rather than telling it to do the actual thing in the first place.

Yes! Telling, not asking, will help keep this object oriented rather than procedural.

To the point

So, is any of these two alternatives the "correct" interpretation of the Use Case Output Port according to the Clean Architecture? Are they both viable?

Anything that works is viable. But I wouldn't say that the second option you presented faithfully follows Clean Architecture. It might be something that works. But it's not what Clean Architecture asks for.

  • 2
    Thanks for taking the time to write such an in-depth explanation. – swahnee Sep 9 '17 at 7:14
  • 1
    I've been trying to wrap my head around the Clean Architecture, and this answer has been a fantastic resource. Very well done! – Nathan Apr 6 at 2:10
  • Great and in detail answer.. Thanks for that.. Can you give me some tips (or point to explanation) about updating GUI during UseCase run, i.e. progress bar update while uploading big file? – Ewoks May 9 at 23:58
  • 1
    @Ewoks, as a quick answer to your question, you should look into the Observable pattern. Your use case could return a Subject and Notify the Subject of progress updates. The presenter would Subscribe to the Subject and respond to the Notifications. – Nathan Jun 25 at 21:26

Regarding the interactors having knowledge of the presenters, below is the answer of Uncle Bob in one of the discussions I found...

Given this code sample:



    namespace Some\Controller;

    class UserController extends Controller {
        public function registerAction() {
            // Build the Request object
            $request = new RegisterRequest();
            $request->name = $this->getRequest()->get('username');
            $request->pass = $this->getRequest()->get('password');

            // Build the Interactor
            $usecase = new RegisterUser();

            // Execute the Interactors method and retrieve the response
            $response = $usecase->register($request);

            // Pass the result to the view
            $this->render(
                '/user/registration/template.html.twig', 
                array('id' =>  $response->getId()
            );
        }
    }


Uncle Bob said this:

"The purpose of the presenter is to decouple the use cases from the format of the UI. In your example, the $response variable is created by the interactor, but is used by the view. This couples the interactor to the view. For example, let's say that one of the fields in the $response object is a date. That field would be a binary date object that could be rendered in many different date formats. The wants a very specific date format, perhaps DD/MM/YYYY. Whose responsibility is it to create the format? If the interactor creates that format, then it knows too much about the View. But if the view takes the binary date object then it knows too much about the interactor.

"The presenter's job is to take the data from the response object and format it for the View. Neither the view nor the interactor know about each other's formats."

--- Uncle Bob

  • Thanks for the contribution. Reading the conversation, however, there's one thing I don't understand: he says that the presenter should render the data coming from the response, and at the same time that the response shouldn't be created by the interactor. But then who is creating the response? I'd say the interactor should provide the data to the presenter, in the application specific format, that is know by the presenter, since the adapters layer can depend on the application layer (but not the other way around). – swahnee Sep 14 '17 at 9:26
  • I'm sorry. Maybe it gets confusing because I did not include the code example from the discussion. I will update it to include the code example. – Jboy Flaga Sep 15 '17 at 5:24
  • Uncle Bob did not say that the response should not be created by the interactor. The response will be created by the interactor. What Uncle Bob is saying is that the response created by the interactor will be used by the presenter. The presenter will then "format it", put the formatted response to a viewmodel, then pass that viewmodel to the view.<br/>That's how I understand it. – Jboy Flaga Sep 15 '17 at 5:34
  • 1
    That makes more sense. I was under the impression that "view" was synonym for "presenter", since Clean Architecture doesn't mention either "view" nor "viewmodel", which I believe are solely MVC concepts, which may or may not be used when implementing an adapter. – swahnee Sep 15 '17 at 8:02

Even though I generally agree with the answer from @CandiedOrange, I would also see benefit in the approach where the interactor just retruns data which is then passed by the controller to the presenter.

This for example is a simple way to use the ideas of the Clean Architecture (Dependency Rule) in the context of Asp.Net MVC.

I have written a blog post to dive deeper into this discussion: https://plainionist.github.io/Implementing-Clean-Architecture-Controller-Presenter/

Use case containing the presenter or returning data?

So, is any of these two alternatives the "correct" interpretation of the Use Case Output Port according to the Clean Architecture? Are they both viable?


In short

Yes, they are both viable as long as both approaches take into consideration Inversion Of Control between the business layer and the delivery mechanism. With the second approach, we are still able to introduce IOC by making use of observer, mediator few others design patterns...

With his Clean Architecture, Uncle Bob's attempt is to synthesizes a bunch of known architectures to reveal important concepts and components for us to comply widely with OOP principles.

It would be counter productive to consider his UML class diagram (the diagram below) as THE unique Clean Architecture design. This diagram could have been drawn for the sake of concrete examples… However, since it is far less abstract than usual architecture representations he had to make concrete choices among which the interactor output port design which is only an implementation detail

Uncle Bob's UML class diagram of Clean Architecture


My two cents

The main reason why I prefer returning the UseCaseResponse is that this approach keeps my use cases flexible, allowing both composition between them and genericity (generalization and specific generation). A basic example:

// A generic "entity type agnostic" use case encapsulating the interaction logic itself.
class UpdateUseCase implements UpdateUseCaseInterface
{
    function __construct(EntityGatewayInterface $entityGateway, GetUseCaseInterface $getUseCase)
    {
        $this->entityGateway = $entityGateway;
        $this->getUseCase = $getUseCase;
    }

    public function execute(UpdateUseCaseRequestInterface $request) : UpdateUseCaseResponseInterface
    {
        $getUseCaseResponse = $this->getUseCase->execute($request);

        // Update the entity and build the response...

        return $response;
    }
}

// "entity type aware" use cases encapsulating the interaction logic WITH the specific entity type.
final class UpdatePostUseCase extends UpdateUseCase;
final class UpdateProductUseCase extends UpdateUseCase;

Note that it is analogously closer of UML use cases including/extending each other and defined as reusable on different subjects (the entities).


On the interactor returning data

However, the use case doesn't control the moment when the actual presentation is performed anymore (which may be useful, for example to do additional stuff at that point, like logging, or to abort it altogether if necessary).

Not sure to understand what you mean with this, why would you need to "control" the presentation performation? Don't you control it as long as you don't return the use case response?

The use case can return in its response a status code to let know to the client layer what happened exactly during its operation. HTTP response status codes are particularly well suited to describe the operation status of a use case…

Your Answer

By clicking "Post Your Answer", you acknowledge that you have read our updated terms of service, privacy policy and cookie policy, and that your continued use of the website is subject to these policies.

Not the answer you're looking for? Browse other questions tagged or ask your own question.