All interview topics
System Design & Architecture

Clean Architecture Interview Questions and Answers

Practice Clean Architecture interview questions and answers organized by difficulty, with revealable explanations and related topics.

18 questionsEntry → Expert

Junior questions

4 questions
  1. Question 1
    Junior

    What is an Entity in Clean Architecture?

    • Clean Architecture
    Reveal answer

    An Entity is an object within our software that represents the union of critical business rules operating on critical business data (i.e. data bound to behaviour if you may). For example,the Loan entity could look like: Loan -principle -rate

    -period
    +makePayment()
    +applyInterest()
    +chargeLateFee()
    

    The entity should either hold the critical business data OR have very easy access to it. The entity does not know anything about databases, user interfaces or third-party frameworks. In an object-oriented language the entity may be a class, but in other paradigms it can be whatever construct allows to bind data and behaviour together (all programing paradigms have this concept).

  2. Question 2
    Junior

    What do you understand by Clean Architecture approach?

    • Clean Architecture Software Architecture
    Reveal answer

    The majority of architectural approaches (like Onion or Hexagonal Architecture) have this common set of characteristics: The architectural approach shall be: Independent of any tech frameworks Testable: business rules are testable without the UI, the DB, the web server, and any other external element. Independent of the UI: The UI can change easily with no impact on the business rules. The UI can easily be replaced. Independent of the database Independent of external agents: The business rules don't know anything about interfaces to the outside world. The Clean Architecture is an attempt at integrating all these architectures into a single actionable idea:

  3. Question 3
    Junior

    How you pass data between modules where they have different models in Clean Architecture?

    • Clean Architecture
    Reveal answer

    You simply use mappers. Mappers transform DTOs into domain models and vice versa. The reason to make each module has its own models or entities is to easily test each module separately.

  4. Question 4
    Junior

    Explain the Data Flow in Clean Architecture

    • Clean Architecture
    Reveal answer
    1. UI calls a method from Presenter/ViewModel.
    2. Presenter/ViewModel executes the Use case.
    3. Use case combines data from User and Post Repositories.
    4. Each Repository returns data from a Data Source (Cached or Remote).
    5. Information flows back to the UI where we display the list of posts.

Mid questions

11 questions
  1. Question 1
    Mid

    How shall we integrate DB Layer access in Clean Architecture?

    • Clean Architecture Layering & Middleware
    Reveal answer

    Problem

    In Clean Architecture the Database is at the outer Layer but how would that work in reality?

    Solution

    Nothing in an inner circle can know anything at all about something in an outer circle. In particular, the name of something declared in an outer circle must not be mentioned by the code in an inner circle. That includes functions and classes. variables, or any other named software entity. For DB Layer you create a technology-independent interface in the use case layer and implement it in the gateway layer:

    public interface OrderRepository {
      public List<Order> findByCustomer(Customer customer);
    }
    

    implementation is in the gateway layer

    public class HibernateOrderRepository implements OrderRepository {
      ...
    }
    

    At runtime, you pass the gateway's implementation instance to the use case's constructor. That would not violate the dependency rule, because the use cases define the interface they need. It might be even better to extract these use cases' interfaces into their own module. This prevents the db module to depend on the dependencies of the use case module.

  2. Question 2
    Mid

    Where should I implement the external API calls logic in Clean Architecture?

    • Clean Architecture
    Reveal answer

    Problem

    Whenever a request is made to get a "full product", the client will ping the endpoint for the full product, it will grab that, and use its id to ping my Images and Reviews services to get all images and reviews for that product. Where should I implement the external API calls logic in Clean Architecture?

    Solution

    Obtaining the images and reviews from the perspective of your product use case is just like database access. The only difference is that you don't query a database, you query another service instead. When you take a look at the clean architecture you will realize that the controllers and gateways are on the same architectural layer - the interface adapters. This layer is named "interface adapters" because it adapts interfaces of the lower layer. As you can see gateways can be a DB or an external interface (a service). Thus you should structure your application in this way:

    +------------------+ | product use case | +------------------+ | +------------------+---------------------+ | | | V V V +-----------------+ +------------------+ +-------------------+ | ImageRepository | | ReviewRepository | | ProductRepository | +-----------------+ +------------------+ +-------------------+ ^ ^ ^ | | |

    ===========+=====================+====================+================
    | | |
    +--------------------+ +--------------------+ +--------------------+
    | ImageRestClient | | ReviewRestClient | | JDBCConnector |
    +--------------------+ +--------------------+ +--------------------+
    

    Easy to test and if you decide one day that the images should be managed in the product microservice instead of a separate service you can replace the ImageRestClient with a JDBCConnector .

  3. Question 5
    Mid

    Explain what is Interface Segregation Principle (ISP) in Clean Architecture and what are some of its benefits?

    • Clean Architecture Software Architecture
    Reveal answer

    The general wisdom is: Depending on something that carries baggage that you don’t need can cause you troubles that you didn't expect. The Interface Segregation Principle (ISP) is a design principle in object-oriented programming that emphasizes the importance of keeping interfaces segregated or divided into smaller, cohesive units. It suggests that clients (users or classes) should not be forced to depend on interfaces they do not use. As an example consider the Repository interface. To apply the Interface Segregation principle you shall provide your own repository interface that is dedicated to one use case will help to decouple use cases from each other. If all use cases use the same Repository

    interface, then this interface accumulates all the methods of all use cases. You can easily break one use case by changing the method of this interface. So I usually apply the interface segregation principle and create repository interfaces named after the use case. E.g.

    public interface PlaceOrderRepository {
      public void storeOrder(Order order);
    }
    

    and another use case's interface might look like this:

    public interface CancelOrderRepository {
      public void removeOrder(Order order);
    }
    
  4. Question 6
    Mid

    What do you mean by Clean Architecture is Screaming?

    • Clean Architecture
    Reveal answer

    One aspect Uncle Bob is emphasizing is that the clean architecture is screaming. According to Uncle Bob an architecture “screams” when it clearly expresses its core business purpose. The top-level folder structure, the project/DLL names, and the namespaces should express business aspects rather than frameworks or other details. That also means that the top-level structure and names should express your business domain and not the technical details and frameworks you use. Consider non-screaming folder structure:

    Consider screaming folder structure:

  5. Question 7
    Mid

    What are Use Cases in Clean Architecture?

    • Clean Architecture
    Reveal answer

    Use Cases are business rules that make or save money by defining the way the automated system operates. They wouldn't exist if the business operated in a manual environment. Each use case is a description of the way the system is used. They specify the input provided by the user, the processing steps and the output returned. It uses other data elements to represent input data and output data. See Requests and Response Models. They specify how and when the Entities' Critical Business Rules are invoked. Entities have no knowledge of the use cases that control them. Entities are at a higher-level than use cases and therefore do not depend on them.

    It does NOT describe the user interface. It only specifies the data to be passed in. Use cases don't know if they are part of a web-system, a desktop client, etc. A use case is an object that has one or more functions that implement the application-specific business rules.

  6. Question 8
    Mid

    Explain what is Dependency Rule in Clean Architecture

    • Clean Architecture Layering & Middleware
    Reveal answer

    The Dependency Rule states that source code dependencies should always point inward toward higher-level policies or abstractions and should never point outward toward lower-level details or implementations. In other words, the dependencies between different components or modules of a system should follow a specific direction, with higher-level modules depending on lower-level ones, but not the other way around. Presentation Layer depends on Domain Layer. Data Layer depends on Domain Layer. Domain Layer does NOT depend on Data/Presentation Layer.

  7. Question 9
    Mid

    Explain the purpose of Clean Architecture Inner and Outer layers

    • Clean Architecture Software Architecture Layering & Middleware
    Reveal answer

    The Entities layer contains the domain objects that are used by the Use Cases layer to perform its business logic. These objects are typically plain old data objects (PODOs) that hold the data for the system, and may also include methods for manipulating that data. The Use Cases (interactors) layer is the first layer of the Clean Architecture system. It is responsible for handling the business logic of the application. The Use Cases layer should be focused on a specific business requirement or action, and should not contain any infrastructure or presentation logic.

    The Interface Adapters layer is responsible for adapting the objects in the Entities layer to the outside world. It contains the code that maps between the internal data structures of the system and the external data structures that are used by the user interface or other external systems. Gateway (often Repository) in the 3rd layer is responsible for interaction with DB and external libraries. Presenter is responsible for interaction with the UI (View). The presenter has a Reactive Property that publishes Entity updates so that the UI View can be updated without any dependency by subscribing to the property. The Framework & Drivers layer is responsible for providing the infrastructure and services that the other layers depend on. This layer contains the code for interacting with databases, web services, and other external systems. View is responsible for manipulating the UI, i.e. inputting actions through the UI and outputting the update of Entity. The view can’t have any dependency on the components in the other layers.

  8. Question 10
    Mid

    What is the difference between the Clean and the N-Tier Architectures?

    • Clean Architecture Software Architecture
    Reveal answer

    Both architectural styles apply layers to separate concerns, however, they do that in a different way: The N-tier Architecture is about communicating with the database through layers of business logic and representation. It is tightly coupled to the externals (3rd party frameworks/drivers) you want to use, for example to an HTTP Server, an ORM, or an SQL driver. The Clean Architecture is about implementing use cases and building layers of adapters and externals (3rd party frameworks/drivers) around them. It is loosely coupled to the externals you want to use because of the layer of the adapters and DI. So essentially, When you opt for DI and use interfaces to decouple dependencies in your N-tier architecture, you are transforming your architecture to Onion Architecture. As long as you are observing the direction (and in my case the depth) of your dependencies you moving it to Clean Architecture.

  9. Question 13
    Mid

    Explain the control flow of a user interacting with Clean Architecture components?

    • Clean Architecture
    Reveal answer

    Following the purple arrow we can see the control flow of a user interacting with a system:

    1. The user interacts with the view.
    2. The view creates a request (object) which is passed to the controller.
    3. The controller converts the request into a request model and passes it to the use case interactor through its input port.
    4. The use case interactor processes the request model and creates a response model which is passed through the output port to the presenter.
    5. The presenter converts the response model to the view model which is then passed to the view.
    6. The user sees the result of his interaction in the view. The left (blue) section where the frameworks live (e.g. an HTML/JavaScript view) The middle (green) section where the adapters live (controllers and presenters) The right (red) section where the business logic (use case interactors) live The controller and the presenter are located in the middle of this picture and they appear as a bridge between the user’s world (the view) and the business logic’s world (interactors).
  10. Question 14
    Mid

    What is the role of the Controller in Clean Architecture?

    • Clean Architecture
    Reveal answer

    The controller takes user input, converts it into the request model defined by the use case interactor, and passes this to the same. The request object accepted by the controller is defined by the controller. We do NOT want the controller to depend on the view or types defined in the framework circle. Such request objects are usually simple data transfer objects (DTO).

  11. Question 15
    Mid

    What is the role of the Presenter in Clean Architecture?

    • Clean Architecture
    Reveal answer

    The job of the Presenter is to repackage the

    OutputData (
    Response Model) into viewable form as theViewModel, which is yet another plain old Java object (POJO). The
    

    ViewModel contains mostly Strings and flags that the View uses to display the data. Whereas the OutputData may contain Date objects, the Presenter will load the ViewModel with corresponding Strings already formatted properly for the user.

Senior questions

2 questions
  1. Question 16
    Senior

    Compare Onion vs Clean vs Hexagonal Architectures

    • Clean Architecture Software Architecture
    Reveal answer

    Hexagonal, Onion, and Clean Architecture all center around the idea of externalizing the database and other dependencies instead of building around them but use different terminology: Hexagonal or “ports and adapters” architecture:

    Your core application logic is written with only a concept of whatever external dependencies it has. In object-oriented terms, this means it declares and references an interface, but leaves the implementation of that interface out of the core logic. This can be thought of as a “port” such as a display port or USB port. The outer layer of the application then creates an “adapter” which plugs into the port There are no layers. Onion Architecture. It expanded on the idea to define a “Core”: The core “Domain Model” represents enterprise-wide business rules. In the next layer up are “Domain Services” such as abstract repositories (still leaving the implementation details such as a database connection to the outer layers). Further up is “Application Services” which defined the business processes of the application. In the outer- most layer are the user interface, connections to external infrastructure, and automated tests. There are layers, with the dependencies always pointing inwards, i.e., a layer can use any of the layers inside it. Clean Architecture: Instead of “Domain Model”, it refers to the core as “Entities” The concept of “Screaming Architecture”. It should be glaringly obvious at a glance what an application does. Re-phrases “Application Services” as “Use Cases”

  2. Question 17
    Senior

    What is the difference between Request/Response Models and Entities in Clean Architecture?

    • Clean Architecture
    Reveal answer

    Request and Response data structures are introduced for the use cases to get input data and return output without coupling them to any particular type of I/O device (like the web or the DB). These structures should not depend on anything: They should not know about the web or the DB. They should not know about the framework. They should not contain references to Entity objects. Despite probably sharing data with Entity objects, the purpose of these two objects is very different and they will change for very different reasons. Therefore this is accidental duplication and it is better to keep them separate.

Expert questions

1 questions
  1. Question 18
    Expert

    How and where do you use transactions in the Clean Architecture?

    • Clean Architecture
    Reveal answer

    Put the transaction on the controllers. The controller knows about the larger framework since it probably has at least metadata like annotations of the framework. You can have each use case start a transaction and do transaction management. Internally the unit of work either starts the actual transaction or increases a counter of invoked starts. Each use case would then call

    commit or reject. When the commit count equals 0, invoke the actual commit. Reject skips all of that, rolls back, then errors out (exception or return code).

    public MyUseCase() {
      public boolean execute(...) {
        dataManagerRepository.openTransaction()
        try {
          int id = repository.insert(a)
          if(id > 0) {
            b.aId= id;
            repository.insert(b);
            ...
          }
        catch (MyException exc) {
          dataManagerRepository.rollbackTransaction()
        }
      dataManagerRepository.commitTransaction()
    }
    }