Phase 12 of 20 · Topic 12.3

Encapsulation Boundaries in Layered Microservices

1Concept

In enterprise microservices (Hexagonal or Onion Architecture), strict access boundaries protect domain entities from external framework leaks. Keeping domain entities package-private within internal packages prevents controllers from directly modifying database entities without service validation.

2Architecture Diagram

[ Web Controller (public) ] ---> [ Application Service (public) ] ---> [ Domain Entity (package-private) ]

3Code Example

Core Java
public class ArchitectureBoundaryDemo {
    // Package-private internal entity (hidden from other packages)
    static class InternalDomainEntity {
        private String status = "PENDING";
        void approve() { this.status = "APPROVED"; }
        String getStatus() { return status; }
    }

    // Public boundary service
    public static class OrderWorkflowService {
        public String processWorkflow() {
            InternalDomainEntity entity = new InternalDomainEntity();
            entity.approve();
            return "Workflow successfully executed: Status is " + entity.getStatus();
        }
    }

    public static void main(String[] args) {
        OrderWorkflowService service = new OrderWorkflowService();
        System.out.println(service.processWorkflow());
    }
}

4Expected Output

Workflow successfully executed: Status is APPROVED

5Key Takeaways

  • Design public APIs minimally; keep implementation details package-private.
  • Prevents external code from tightly coupling to internal data structures.
  • Enables safe refactoring of internal classes without breaking external clients.