immutables icon indicating copy to clipboard operation
immutables copied to clipboard

Externally Immutable interface

Open xenoterracide opened this issue 9 months ago • 0 comments

What I'm ultimately trying to do is build a Domain Driven Design Aggregate. In DDD an aggregate shouldn't expose arbitrary mutability. It should be able to mutate its own state though. The hardest case here is collections, since those expose things like "add"

In the case I'm currently working on most fields aren't going to be mutable at all, as those go through other "micro services".

one option that might allow what I think the ideal is... which would be that the builder can do things without the same level of checks...

@Value.Immutable
public abstract class Account {

   protected List<AccountUser> users;

   @Value.BackedBy(field = "users")
   public abstract Collection<Account> users();

   // shouldn't affect builder
   public void addUser(AccountUserCommand command) {
     // other logic
     users.add(command.user());
   }
}

in this scenario the generated method would be something like

public class ImmutableAccount {

   protected List<AccountUser> users;

   public Collection<Account> users() {
     return List.copyOf(users);
   }

   // shouldn't affect builder
   public void addUser(AccountUserCommand command) {
     // other logic
     users.add(command.user());
   }
}

but methods like Builder.addUsers(List<AccountUser> users). would still get generated; users could get added by the builder without having "other logic" happen.

xenoterracide avatar Jun 20 '25 18:06 xenoterracide