Data Flow and Crossing Boundaries in Clean Architecture

Learning Objectives: By the end of this lesson, you will be able to:

  • Trace the flow of data and control through all layers of Clean Architecture
  • Identify and design DTOs and interfaces at each boundary
  • Draw and interpret sequence diagrams for use cases

1. Welcome and Introduction (5 minutes)

Icebreaker Activity

Think about a feature in an app (like creating a new blog post). How does the data you enter in the UI end up in the database? What steps and transformations does it go through?

Lesson Overview

  • Duration: 90 minutes
  • Prerequisites: Understanding of all Clean Architecture layers and their responsibilities
  • Materials Needed: Java development environment, diagramming tool or pen and paper

2. Learning Objectives and Session Outline (5 minutes)

What We’ll Cover Today:

  1. Control flow vs. data flow in Clean Architecture
  2. How data is transformed as it crosses boundaries
  3. The role of DTOs and interfaces at each layer
  4. Drawing and interpreting sequence diagrams
  5. Hands-on practice and exercises
  6. Common pitfalls and how to avoid them

Success Criteria:

By the end of this session, you should be able to trace and explain the journey of data through a Clean Architecture application.

3. Foundation Knowledge (15-20 minutes)

Core Concepts

Control Flow vs. Data Flow

  • Control Flow: The direction in which commands and method calls move (usually from the UI inward)
  • Data Flow: The path data takes as it is transformed and passed between layers (can be more complex)

Real-World Analogy: Think of a package delivery: the sender (UI) initiates the process, but the package (data) is handled, repackaged, and routed by different people (layers) before reaching its destination (database or response).

Why This Matters: Understanding data and control flow helps you design clear boundaries, avoid leaks, and ensure maintainability.

DTOs and Interfaces at Boundaries

  • DTOs (Data Transfer Objects): Used to transfer data between layers, especially across boundaries
  • Interfaces: Define contracts for communication between layers (e.g., repositories, gateways)

Key Terminology

  • Boundary: The point where one layer communicates with another
  • DTO: Object for transferring data between layers
  • Sequence Diagram: Visual representation of the flow of control and data

4. Detailed Explanation and Examples (25-30 minutes)

Understanding Data Flow in Clean Architecture

Data typically flows from the UI (outermost layer) inward to the core, and then back outward as a response. At each boundary, data is transformed to fit the needs of the next layer.

Practical Applications

  • HTTP request (UI) → Controller DTO → Use Case Request Model → Entity → Use Case Response Model → Presenter ViewModel → HTTP response
  • Each transformation isolates concerns and prevents leaking details between layers

Common Misconceptions

  1. Misconception: You can use the same object across all layers. Reality: Each layer should have its own models/DTOs to prevent coupling.
  2. Misconception: Data always flows in one direction. Reality: Data can flow both ways, especially in response to user actions.

5. Live Coding Demonstration (20-25 minutes)

Example 1: Data Flow for Creating a Blog Post

// UI Layer: HTTP request mapped to DTO
public class CreateBlogPostRequestDTO {
    public String title;
    public String content;
}

// Controller Layer: Receives DTO, calls use case
public class BlogPostController {
    private final CreateBlogPostUseCase useCase;
    private final CreateBlogPostPresenter presenter;
    public BlogPostController(CreateBlogPostUseCase useCase, CreateBlogPostPresenter presenter) {
        this.useCase = useCase;
        this.presenter = presenter;
    }
    public String createPost(CreateBlogPostRequestDTO dto) {
        CreateBlogPostRequest request = new CreateBlogPostRequest(dto.title, dto.content);
        CreateBlogPostResponse response = useCase.execute(request);
        return presenter.present(response);
    }
}

// Use Case Layer: Request/Response models
public class CreateBlogPostRequest {
    public final String title;
    public final String content;
    public CreateBlogPostRequest(String title, String content) {
        this.title = title;
        this.content = content;
    }
}
public class CreateBlogPostResponse {
    public final boolean success;
    public final String message;
    public CreateBlogPostResponse(boolean success, String message) {
        this.success = success;
        this.message = message;
    }
}

// Entity Layer: BlogPost entity
public class BlogPost {
    private String id;
    private String title;
    private String content;
    // ...constructor, getters, business rules...
}

Explanation:

  • Data is transformed at each boundary to fit the needs of the next layer
  • Each layer has its own models/DTOs

Example 2: Sequence Diagram (Textual)

UI → Controller → Use Case → Entity
 |      |           |        |
 |      |           |        |
 |      |           |        |
 v      v           v        v
CreateBlogPostRequestDTO
   → CreateBlogPostRequest
      → BlogPost (entity)
         → CreateBlogPostResponse
            → Presenter/ViewModel
               → HTTP Response

Example 3: Marking Interfaces and DTOs

// Interface for repository
public interface BlogPostRepository {
    void save(BlogPost post);
    BlogPost findById(String id);
}

// DTO for response
public class BlogPostViewModel {
    public String id;
    public String title;
    public String content;
}

Debugging Demonstration

Show a common error:

// Common mistake: Using entity directly in the controller
public class BlogPostController {
    public void createPost(BlogPost post) { // tightly coupled!
        // ...
    }
}

// Corrected version: Use DTOs at boundaries
public class BlogPostController {
    public void createPost(CreateBlogPostRequestDTO dto) {
        // ...
    }
}

6. Hands-On Practice (30-40 minutes)

Exercise 1: Basic Practice (10 minutes)

Objective: Draw a sequence diagram for marking a task as complete.

Instructions:

  1. Identify the layers and boundaries involved.
  2. Draw the flow of data and control from the UI to the database and back.

Starter Code: N/A (diagramming exercise)

Solution: A correctly labeled diagram showing DTOs, interfaces, and transformations at each boundary.

Exercise 2: Intermediate Challenge (15 minutes)

Objective: Define DTOs and interfaces for a library system use case (e.g., borrowing a book).

Requirements:

  • Create request/response DTOs for the use case
  • Define repository interfaces for data access
  • Show how data is transformed at each boundary

Hints:

  • Use clear, descriptive names for DTOs and interfaces

Exercise 3: Creative Application (15 minutes)

Objective: Trace and document the data flow for a feature in your own project.

Challenge: Pick a feature (e.g., user registration, posting a comment) and document the data flow and transformations through all layers. Draw a sequence diagram and list all DTOs and interfaces used.

Extension Ideas:

  • Identify places where boundaries are unclear or models are reused inappropriately
  • Suggest improvements for better separation

7. Common Pitfalls and Troubleshooting (10 minutes)

Frequent Mistakes

  1. Problem: Using the same object across all layers Cause: Not defining clear boundaries Solution: Create separate DTOs and models for each layer

  2. Problem: Leaking framework or database details into core logic Cause: Poor separation of concerns Solution: Use interfaces and DTOs to isolate details

Debugging Tips

  • Check for direct use of entities in controllers or presenters
  • Ensure each boundary has its own DTOs and interfaces
  • Write tests for data transformations at boundaries

8. Best Practices and Professional Tips (5 minutes)

Industry Standards

  • Use DTOs and interfaces at every boundary
  • Draw sequence diagrams for complex features
  • Review data flow regularly to prevent leaks

Next Steps in Your Learning Journey

  • Practice documenting data flow for new features
  • Explore tools for drawing sequence diagrams (e.g., PlantUML)
  • Read about the Single Responsibility Principle (SRP)

9. Summary and Review (5 minutes)

Key Takeaways

  1. Data and control flow through multiple layers in Clean Architecture
  2. DTOs and interfaces are essential for clear boundaries
  3. Sequence diagrams help visualize and document data flow

Quick Review Questions

  1. What is the difference between control flow and data flow?
  2. Why should each layer have its own DTOs and interfaces?
  3. How do sequence diagrams help in Clean Architecture?

For Instructors

Teaching Tips

  • Use real-world features to illustrate data flow
  • Encourage students to draw and review sequence diagrams
  • Review DTO and interface design for clarity and separation

Assessment Ideas

  • Ask students to document data flow for a sample feature
  • Review sequence diagrams for completeness
  • Peer review of DTO and interface definitions

Adaptation Notes

  • For beginners, provide more scaffolding and diagram examples
  • For advanced students, challenge them to refactor unclear boundaries
  • Adjust timing based on class experience and engagement