Entities: The Foundation of Clean Architecture
Learning Objectives: By the end of this lesson, you will be able to:
- Define what an Entity is in Clean Architecture
- Identify and design core business entities for a sample application
- Implement entities in Java as plain objects with business rules and no external dependencies
1. Welcome and Introduction (5 minutes)
Icebreaker Activity
Think of your favorite app or website. What are the most important “things” (objects) it manages? For example, in a to-do app, it’s the tasks; in a blog, it’s the posts and users. Why do you think these are central to the app?
Lesson Overview
- Duration: 90 minutes
- Prerequisites: Understanding of OOP and Clean Architecture basics
- Materials Needed: Java development environment, pen and paper for sketching entities
2. Learning Objectives and Session Outline (5 minutes)
What We’ll Cover Today:
- What are Entities and why are they important?
- Characteristics of good Entities
- Designing Entities for a sample application
- Implementing Entities in Java
- Hands-on practice and exercises
- Common pitfalls and how to avoid them
Success Criteria:
By the end of this session, you should be able to design and implement entities that are independent of frameworks and external concerns.
3. Foundation Knowledge (15-20 minutes)
Core Concepts
What is an Entity?
An Entity is a core business object that contains critical business data and rules. Entities are the most stable part of your application and should not depend on frameworks, databases, or UI.
Real-World Analogy: Think of a bank account. No matter how you access it (ATM, online, in-person), the rules for how money is deposited or withdrawn remain the same. The bank account is the Entity; the access methods are external.
Why This Matters: Entities encapsulate the most important business rules. By keeping them independent, you ensure your core logic is robust and adaptable to change.
Characteristics of Good Entities
- Contain business-critical data and rules
- No dependencies on frameworks, databases, or UI
- Implement methods that enforce business rules
- Are stable and change rarely
Key Terminology
- Entity: A business object with identity and business rules
- POJO (Plain Old Java Object): A simple Java object not bound by any special restriction
- Business Rule: Logic that enforces how the business operates
4. Detailed Explanation and Examples (25-30 minutes)
Understanding Entities in Clean Architecture
Entities are the innermost circle of Clean Architecture. They represent the heart of your business logic and should be designed to last for years, even as technology changes around them.
Practical Applications
- In a to-do app: Task, User
- In a blog: Post, Author, Comment
- In a banking app: Account, Transaction, Customer
Common Misconceptions
- Misconception: Entities should contain database annotations or framework code. Reality: Entities must be free of any external dependencies.
- Misconception: Entities are just data holders (anemic models). Reality: Entities should also contain business rules and methods.
5. Live Coding Demonstration (20-25 minutes)
Example 1: Basic Entity in Java
public class Task {
private String id;
private String description;
private boolean completed;
public Task(String id, String description) {
this.id = id;
this.description = description;
this.completed = false;
}
public void markComplete() {
this.completed = true;
}
public boolean isCompleted() {
return completed;
}
public String getDescription() {
return description;
}
}
Explanation:
Taskis a POJO with no framework or database dependencies.- The
markCompletemethod enforces a business rule: marking a task as complete.
Example 2: Entity with Business Rules
public class BankAccount {
private String accountNumber;
private double balance;
public BankAccount(String accountNumber, double initialBalance) {
this.accountNumber = accountNumber;
this.balance = initialBalance;
}
public void deposit(double amount) {
if (amount <= 0) throw new IllegalArgumentException("Deposit must be positive");
balance += amount;
}
public void withdraw(double amount) {
if (amount <= 0) throw new IllegalArgumentException("Withdrawal must be positive");
if (amount > balance) throw new IllegalArgumentException("Insufficient funds");
balance -= amount;
}
public double getBalance() {
return balance;
}
}
Key Points:
- Business rules (e.g., no negative deposits, no overdrafts) are enforced in the entity.
- No database or framework code is present.
Example 3: Avoiding Framework Dependencies
// Incorrect: Entity with JPA annotation (framework dependency)
// @Entity
public class User {
// ...
}
// Correct: No annotations or imports from frameworks
public class User {
// ...
}
Debugging Demonstration
Show a common error:
// Common mistake: Entity with database code
public class Product {
public void saveToDatabase() {
// Database code here (should not be in entity!)
}
}
// Corrected version: No database code in entity
public class Product {
// ...
}
6. Hands-On Practice (30-40 minutes)
Exercise 1: Basic Practice (10 minutes)
Objective: Design a POJO for a blog post entity.
Instructions:
- Define fields for id, title, content, and author.
- Add a method to update the content.
- Ensure no framework or database code is present.
Starter Code:
public class BlogPost {
// ...
}
Solution:
public class BlogPost {
private String id;
private String title;
private String content;
private String author;
public BlogPost(String id, String title, String content, String author) {
this.id = id;
this.title = title;
this.content = content;
this.author = author;
}
public void updateContent(String newContent) {
this.content = newContent;
}
}
Exercise 2: Intermediate Challenge (15 minutes)
Objective: Add business rules to an entity.
Requirements:
- Add a method to the
BlogPostentity that prevents updating the content if the title is empty. - Throw an exception if the rule is violated.
Hints:
- Use
if (title == null || title.isEmpty())to check the rule.
Exercise 3: Creative Application (15 minutes)
Objective: Design entities for a simple library system (Book, Member, Loan).
Challenge:
Define the fields and business rules for each entity. For example, a Loan should not be created if the book is already loaned out.
Extension Ideas:
- Add methods to check overdue loans
- Implement rules for maximum books per member
Entity? Model? DTO?
In software development, the terms Entity, Model, and DTO (Data Transfer Object) are often used, sometimes interchangeably, but they have distinct meanings and roles, especially in Clean Architecture.
Entity
- Represents a core business object with identity and business rules.
- Exists in the innermost layer of Clean Architecture.
- Should contain business logic and be independent of frameworks, databases, or UI.
- Example:
Task,BankAccount,Userclasses shown above.
Model
- A general term that can refer to any object representing data in your application.
- In MVC (Model-View-Controller), “Model” often means the data and business logic layer, but in Clean Architecture, it’s more precise to use “Entity” for core business objects.
- Sometimes used for objects that represent the state of the application or UI, not necessarily business rules.
DTO (Data Transfer Object)
- A simple object used to transfer data between layers or systems.
- Contains no business logic—just data fields and (optionally) basic validation.
- Used to decouple the internal representation (Entities) from how data is sent over the network, to the UI, or between layers.
- Example:
// DTO for transferring task data
public class TaskDTO {
public String id;
public String description;
public boolean completed;
}
Key Differences:
- Entities encapsulate business rules and identity.
- DTOs are for data transfer only, with no business logic.
- Models is a broad term; in Clean Architecture, prefer using “Entity” and “DTO” for clarity.
Why Separate Them?
- Keeps business logic isolated and testable.
- Prevents leaking internal details to external systems.
- Allows flexibility in how data is presented or transferred without changing core logic.
Common Mistake:
- Using Entities directly as DTOs, which can expose sensitive data or business logic and create tight coupling between layers.
Best Practice:
- Map between Entities and DTOs in the Interface Adapters layer (e.g., using a Mapper class or library).
7. Common Pitfalls and Troubleshooting (10 minutes)
Frequent Mistakes
-
Problem: Adding framework or database code to entities Cause: Mixing concerns Solution: Keep entities as POJOs with only business logic
-
Problem: Entities with no business rules (anemic models) Cause: Treating entities as data holders only Solution: Add methods that enforce business rules
Debugging Tips
- Check for imports from frameworks in entity classes
- Ensure all business rules are enforced in entity methods
- Write unit tests for entity methods
8. Best Practices and Professional Tips (5 minutes)
Industry Standards
- Keep entities free of external dependencies
- Place business rules in entity methods
- Use meaningful method names that reflect business actions
Next Steps in Your Learning Journey
- Identify entities in your own projects
- Refactor existing code to move business rules into entities
- Read about Domain-Driven Design (DDD) for deeper understanding
9. Summary and Review (5 minutes)
Key Takeaways
- Entities are the foundation of Clean Architecture
- Entities should contain business rules and be free of external dependencies
- Well-designed entities make your application robust and adaptable
Quick Review Questions
- What is an Entity in Clean Architecture?
- Why should entities not depend on frameworks or databases?
- How do you enforce business rules in an entity?
For Instructors
Teaching Tips
- Use real-world analogies to explain entities
- Encourage students to identify entities in familiar applications
- Review entity code for external dependencies
Assessment Ideas
- Ask students to design entities for a sample domain
- Review code for business rule enforcement
- Peer review of entity implementations
Adaptation Notes
- For beginners, provide more scaffolding and examples
- For advanced students, challenge them to design entities for complex domains
- Adjust timing based on class experience and engagement