Skip to content
ddd-da-massa logo

DDD da Massa for Jakarta EE

ddd-da-massa

Practical DDD patterns for Jakarta EE web applications with cognitive load distribution. Use when designing controllers, entities, services, or evaluating cohesion and load balance.

SKILL.md

Full skill instructions

DDD da Massa for Jakarta EE

Practical Domain-Driven Design patterns for web applications, applying Cognitive Load Theory to create maintainable code. Based on Alberto Souza's "DDD da Massa".

Philosophy

Enable web application development that does what's necessary, has sufficiently flexible design, and where understanding most of the project requires low effort.

Key Principles

  1. Leverage frameworks — Don't ignore them, maximize their value
  2. Contextual load limits — Different components have different limits
  3. Logical responsibility division — Based on cognitive load, not feelings
  4. 100% cohesive components — Every attribute used by every method

Contextual Cognitive Load Limits

Different parts of a web application have different complexity budgets:

ComponentMax PointsRationale
Controller/​Resource7Handles information flow, must be clear
Domain Service7Business flow should be easily understood
Form/​Request DTO9Transient state with transformation logic
Entity9Persistent state with behavior
Repository3Framework does the heavy lifting
Infrastructure∞Rarely touched, OK to be complex
Configuration∞Template, rarely modified

Core Patterns

1. 100% Cohesive Controllers

Every method in a controller must use ALL injected dependencies.

@Path("/​orders/​{orderId}/​payments")
@RequestScoped
public class OrderPaymentResource {

    @Inject
    private OrderRepository orders;      // Used by all methods

    @Inject
    private PaymentGateway gateway;      // Used by all methods

    @Inject
    private Event<PaymentEvent> events;  // Used by all methods

    @POST
    @Transactional
    public Response processPayment(
            @PathParam("orderId") Long orderId,
            @Valid PaymentRequest request) {

        Order order = orders.findById(orderId)
            .orElseThrow(NotFoundException::new);

        Payment payment = request.toPayment(order);
        PaymentResult result = gateway.process(payment);

        events.fire(new PaymentEvent(order, result));

        return Response.ok(PaymentResponse.from(result)).build();
    }
}
// All 3 dependencies used ✓

2. Form Value Objects (Smart DTOs)

DTOs that know how to convert themselves to domain objects.

public record CreateOrderRequest(
    @NotBlank String customerId,
    @NotEmpty List<@Valid OrderItemRequest> items,
    String notes
) {
    // Conversion logic lives HERE, not in a separate Mapper
    public Order toEntity(Customer customer) {
        return new Order(
            customer,
            items.stream().map(OrderItemRequest::toEntity).toList(),
            notes
        );
    }
}

3. Rich Entities

Entities hold business logic, not just data.

@Entity
public class Bolao {

    private Instant expiresAt;

    @ElementCollection
    private Set<String> invitedEmails;

    // ✓ Logic on state lives in the entity
    public Participation accept(User participant) {
        if (expiresAt.isBefore(Instant.now())) {
            throw new InvitationExpiredException();
        }

        if (!invitedEmails.contains(participant.getEmail())) {
            throw new NotInvitedException(participant);
        }

        return new Participation(this, participant);
    }
}

4. Domain Service Controllers

When controller + service roles merge (for simple flows):

@Path("/​payments/​pagseguro/​{orderId}")
@RequestScoped
public class PagseguroPaymentCallbackResource {

    @Inject
    private OrderRepository orders;

    @Inject
    private PaymentRepository payments;

    @Inject
    private Event<NewPaymentEvent> paymentEvents;

    @POST
    @Transactional
    public void processCallback(
            @PathParam("orderId") Long orderId,
            @Valid PagseguroCallbackRequest request) {

        Order order = orders.findById(orderId)
            .orElseThrow(NotFoundException::new);

        Payment payment = request.toPayment(order);
        payments.save(payment);

        paymentEvents.fire(new NewPaymentEvent(payment));
    }
}
// Acts as both controller AND domain service

Load Distribution Check

If entity has LOW load but calling code has HIGH load → bad distribution:

// ❌ Entity too thin, controller too fat
@POST
public Response accept(@Valid AcceptRequest request) {
    Bolao bolao = bolaoRepo.findById(request.bolaoId()).get();

    // All this logic should be IN the entity
    if (bolao.getExpiresAt().isBefore(Instant.now())) {
        return Response.status(422).entity("Expired").build();
    }
    if (!bolao.getEmails().contains(request.email())) {
        return Response.status(422).entity("Not invited").build();
    }
    // ... more external logic
}

// ✓ Move logic to entity
@POST
public Response accept(@Valid AcceptRequest request) {
    Bolao bolao = bolaoRepo.findById(request.bolaoId()).get();
    User user = userRepo.findByEmail(request.email()).orElseThrow();

    Participation participation = bolao.accept(user);  // Entity has the logic
    participationRepo.save(participation);

    return Response.ok().build();
}

When to Create New Classes

Only create new files when:

  1. Cognitive load exceeded — Must distribute
  2. New domain concept — Entity, Value Object
  3. Language feature — Enum, sealed type

Do NOT create classes just because it "feels cleaner".

Cookbook Index

Controller Patterns

DTO Patterns

Domain Patterns

Service Patterns

More skills from majiayu000

xiaohongshu logo
majiayu000/claude-arsenal

xiaohongshu

xiaohongshu

286 148
View
agent-task-conductor logo
majiayu000/claude-skill-registry

agent-task-conductor

Conduct multi-agent task orchestration and workflow coordination.

663 1
View
conductor-setup logo
majiayu000/claude-skill-registry

conductor-setup

Initialize project with Conductor artifacts (product definition,

663 1
View
animation-designer logo
majiayu000/claude-skill-registry

animation-designer

Expert in web animations, transitions, and motion design using Framer Motion and CSS

663 1
View
diagramming logo
majiayu000/claude-skill-registry

diagramming

Creates Mermaid and ASCII diagrams for flowcharts, architecture, ERDs, state machines, mindmaps, and more. Use when user mentions diagram, flowchart, mermaid, ASCII diagram, text diagram, terminal diagram, visualize, C4, mindmap, architecture diagram, sequence diagram, ERD, or needs visual docume...

663 1
View
h3-pg logo
majiayu000/claude-skill-registry-data

h3-pg

PostgreSQL bindings for H3 hexagonal grid system. Use when working with H3 cells in Postgres, including spatial indexing, geometry/geography integration, and raster analysis.

23 1
View
conductor-development logo
majiayu000/claude-skill-registry

conductor-development

Context-Driven Development skill for projects using Conductor. Use this skill when you detect a `conductor/` directory in the project, when working on tasks defined in a `plan.md` file, or when the user asks about tracks, specs, or plans. Automatically applies TDD workflow, tracks task completion...

663 1
View
conductor-status logo
majiayu000/claude-skill-registry

conductor-status

Display project status, active tracks, and next actions

663 1
View
dockerization logo
majiayu000/claude-skill-registry

dockerization

Official Stakpak application containerization standard operating procedure, a step-by-step guidline to properly dockerize applications. This is a rule book curated by the Stakpak Team.

663 1
View

Popular AI tools

Kaiber logo
Video

Kaiber

Generate, edit, and beat-sync AI video with leading models in one workspace.

Paid
View
Vimcal logo
Productivity

Vimcal

The world's fastest calendar for remote work

Free
View

Transform Your Design with AI Designer by ImgCreator.ai

Freemium
View
Akool AI logo
Content & writing

Akool AI

Revolutionizing Video Production with AI-Powered Creativity

Paid
View

Extend an image past the frame and let AI fill the new aspect ratio.

Freemium
View
StarByFace logo
Security

StarByFace

Discover your celebrity doppelgänger with StarByFace!

Free
View
C

ChainClarity explains 700+ crypto whitepapers in plain English, with layered summaries, comparisons, research tools, alerts, and a $4.99 Pro plan.

Freemium
View
Opus Clip logo
Coding & apps

Opus Clip

Opus.ai: Revolutionize Your Web Experience

Free
View