Domain driven design: Domain rules in services and aggregates - domain-driven-design

I have doubts about the way the domain should enforce business rules when there is more than one aggregate involved.
Suppose I have the account and external account aggregates:
public class Account {
public String getId() {...}
public void add (Double amount) {}
}
public class ExternalAccount {
public String getId() {...}
public void add (Double amount) {}
}
and this service:
public class TransferService implements TransferServiceInterface {
public void transfer (String AccountId, String ExternalAccountId, Double amount) {
Account fromAccount = accRepository.get(AccountId);
ExternalAccount toAccount = extAccRepository.get(ExternalAccountId);
transferIsValid(fromAccount, toAccount, amount);
fromAccount.add(-amount);
toAccount.add(amount);
}
}
transferIsValid will throw an exception if the transfer doesn't comply with the domain rules.
How can I prevent the the user of this model from not using the Service and execute something like this:
Account fromAccount = accRepository.get(AccountId);
ExternalAccount toAccount = extAccRepository.get(ExternalAccountId);
fromAccount.add(-amount);
toAccount.add(amount);
The user didn't use the service and didn't use transferIsValid(...) to check the integrity. I believe that there is an error in my design because the user shouldn't be able to do something invalid. How can I prevent it? Where is the error in my design?

First of all: Do not use Add() to withdraw. DDD is all about following the domain. And I don't think that you say So when I add a negative amount of money to account A, the equal amount will be added to account B when you talk to the product owner. Add a Widthdraw method.
Remember. No users are involved when coding. programmers are. And all programmers can screw up the code.
Regarding the service: there is nothing you can do to prevent that with code. Unless the only valid way to withdraw money is to transfer it to another account. In that case you can change the Widthdraw() method to take another account as the argument.
Other than that, simply add documentation to your Widthdraw method and say that the service should be used if two accounts are involved. imho any DDD developer should know that the service should be used since it's how we do things in DDD (you & I did, and so should also the next dev with DDD experience).

Business logic should be in domain object, so, instead of putting business logic in TransferService, the better way, I think, to avoid business logic leak to Service is to create new Entity calledAccountTransfer with contains AccountFrom and AccountTo, something like (sorry I use C# in here):
public class AccountTransfer
{
Account From { get; set; }
Account To { get; set; }
// More properties
private bool IsValid(ammount)
{}
public void DoTransfer(int amount)
{
is (IsValid(ammount))
{
From.Withdraw(amount);
To.Add(amount);
}
}
}
You might need more information in object AccountTransfer like:
When to transfer
What kind of transfer: transfer via visa, paypal....
To populate this class into database, you store transfer history to trace them later.
With this way, you also put IsValid method inside AccountTransfer as private method.

Related

DDD Aggregate needs info from another aggregate

i'm stuck with this problem while designing aggregates in a DDD project.
Please consider the following scenario:
public abstract class BaseAppType{
public abstract int GetUserOwnerId();
public List<AppTypeHost> Hosts {get;set;} = new List<AppTypeHost>()
}
public class PersonalAppType:BaseAppType //this is an aggregate root
{
public int override GetUserOwnerId(){ return Hosts.Select(h=>h.UserId).Single(); }
}
public class TeamAppType:BaseAppType //this is another aggregate root
{
publi int TeamOwnerId {get;set;}
public int override GetUserOwnerId(){ //this is much harder becase i don't have the info in the object }
}
public class Team {
public List<TeamMember> TeamMembers = new List<TeamMember>();
}
public class TeamMember {
public int TeamId {get;set;}
public int UserId {get;set;}
public TeamMemberRole Role {get;set;} //this might be either Owner or Member
}
So basically i've two types of appointments that share common info, functionality and shape via a root class.
Now i've to implement GetUserOwnerId in the two derived class, which are two distinct aggregates root.
In the PersonalAppType it is kind of easy because the information of the userOwner is within one of the entity of the aggregate so i simply query the object in memory and return it.
In the TeamAppType it is more diffuclt because the information is in another aggregate root ( basically for my business rules, the owner of the TeamAppType is the Owner of the Team AggregateRoot).
Since Team is another AggregateRoot i could not load it into the TeamAppType aggregate and i pretty stuck...
I've tried:
the route of injecting a service in the TeamAppType
so that i can call it within the GetUserOwnerId but i don't like it because it feel "wrong" to inject a service within a domain constructor and it is kind of hard because when i retrieve the aggregate root from ef core, it doesn't inject the service ( because it uses the default construcor with 0 params )
I've also tried the route of doing it in a domain service, something like this:
public class AppTypeOwnerResolverService{
public int GetUserOwnerId (BaseAppType appType)
{
switch (appType.GetType())
{
case "PersonalAppType":
//retrieve owener of PersonalAppType
break
case "TeamAppType":
//retrieve owener of TeamAppType
break
}
}
}
but it feels off because it looks like the GetUserOwnerId should stay within the inherited class and this reduces the benefits of polymorfism.
Do you have any suggestion on how to approach this problem?
Thanks to everyone for the help.
Another option would be to have a Team aggregate emitting domain events, (i.e. TeamOwnerAssigned) and having a domain event handler that modifies the TeamAppType aggregate based on this event.

Protecting invariants and children of aggregate roots when implementing DDD

In my attempt to start learning about DDD, I began with a simple domain model that I will gradually build up over time. My domain in this instance is the usual order > order item in order to keep things simple and be able to add on later with invoices, etc. Here's what I have so far:
public class Order
{
private readonly IList<OrderItem> _orderItems;
public Guid Id { get; private set; }
public bool Completed { get; private set; }
public DateTime Created { get; private set; }
public IEnumerable<OrderItem> OrderItems
{
get { return _orderItems; }
}
public Order()
{
Id = new Guid();
Created = DateTime.UtcNow;
_orderItems = new List<OrderItem>();
}
public void AddOrderItem(int quantity, int unitCost)
{
var orderItem = new OrderItem(quantity, unitCost);
_orderItems.Add(orderItem);
}
public void CompleteOrder()
{
Completed = true;
}
}
public class OrderItem
{
public int Quantity { get; private set; }
public int UnitCost { get; private set; }
public OrderItem(int quantity, int unitCost)
{
Quantity = quantity;
UnitCost = unitCost;
}
}
I will eventually turn Quantity and UnitCost into value objects, but that isn't the important part here. As DDD preaches, we always want to protect our invariants, but I'm having a little trouble with one piece of that. From an Order, you can add a new OrderItem by calling the AddOrderItem() method and passing your quantity and unit cost.
My question now becomes what is to stop another coder from creating a new OrderItem with var orderItem = new OrderItem(1, 2)? The OrderItem constructor should probably have an Order order parameter since an OrderItem cannot exist without an Order, but again now that other coder could just call new OrderItem(new Order(), 1, 2)?
Am I missing something? Or is it just accepted that the team working on the model needs to understand the fundamentals of DDD?
Update
Thanks #theDmi, #guillaume31, #Matt as you all have provided some good points. I think it is pretty clear at this point that the repository's interface should be enough to make it clear that you can't do anything with an OrderItem created by itself. Setting the ctor for OrderItem to internal also helps to enforce this restriction as well, but it may not be needed. I plan to see what happens with or without the internal ctor. Ultimately, the reason I accepted #guillaume31's answer is the comment about the bidirectional relationships. That makes a lot of sense and I have encountered this issue in the past with EF for example, so I like the idea of keeping it unilateral as well.
"An OrderItem cannot exist without an Order" is not really an invariant. Well at least it's not an invariant in the Order aggregate. By definition, invariants only look at things that are inside one aggregate (or span across multiple ones), not things that wander around outside an aggregate.
The OrderItem constructor should probably have an Order order
parameter since an OrderItem cannot exist without an Order
I wouldn't model it that way, because
Bidirectional relationships between entities are not recommended. It can lead to synchronization problems (A points to B but B points to something else), it's better to have unidirectional relations if you can.
By doing that, your ultimate goal is to put a constraint on what's happening outside an Aggregate, which is not really the point of DDD, and, as other answers have shown, dispensable. All changes in a DDD system go through an Aggregate and a Repository.
When working with DDD, all attempts to change the state of the system run through a repository, because you need to retrieve the aggregate you want to work on first. So even if someone creates objects that make no sense outside of a certain entity, they will not be able to do anything useful with it.
Regarding this problem, DDD has even advantages over CRUD-based systems: It leads to a high discoverability. First, the repository interface tells you what you can load. Then you get an aggregate, which in turn offers operations that modify the aggregate in a meaningful way.

Domain events are customer defined, not hard-coded

Requirements for our SaaS product are to build a domain layer where any attribute or combination of attributes that are changed could trigger a domain event - and subsequently kick off a custom process, or notification.
So, I am hesitant to add tons of code to the domain layer that kicks off tons of DomainEvent objects which may not make sense to many tenants.
Each tenant will have the ability to (through a UI screen):
1. define which attributes they care about (e.g. "amount") and why (e.g. amount is now greater than $100)
2. define what happens when they change (e.g. kick off an approval process)
This seems like a business rules engine integration to me along with a BPMS. Does anyone have thoughts on a more lighter-weight framework or solution to this?
You could publish a generic event that has its constraints/specification defined against a unique Name. Let's call the event SpecificationEvent. Perhaps you would have a SpecificationEventService that can check you domain objects that implement a ISpecificationValueProvider and return a populated event that you could publish:
public interface ISpecificationEventValueProvider
{
object GetValue(string name);
}
public class SpecificationEventService
{
IEnumerable<SpecificationEvent> FindEvents(ISpecificationEventValueProvider provider);
}
public class SpecificationEvent
{
private List<SpecificationEventValue> _values;
public string Name ( get; private set; }
public IEnumerable<ISpecificationEventValue> Values
{
get { return new ReadOnlyCollection<ISpecificationEventValue>(_values); }
}
}
public class SpecificationEventValue
{
public string Name { get; private set; }
public object Value { get; private set; }
public SpecificationEventValue(string name, object value)
{
Name = name;
Value = value;
}
}
So you would define the custom events in some store. Possibly from some front-end that is used to defined the constraints that constitute the event. The SpecificationEventService would use that definition to determine whether the candidate object conforms to the requirements and then returns the event with the populated values that you can then publish.
The custom code could be registered in an endpoint where you handle the generic SpecificationEvent. Each of the custom handlers can be handed the event for handling but only the handler that determines that the event is valid for it will perform any real processing.
Hope that makes sense. I just typed this up so it is not production-level code and you could investigate the use of generics for the object :)

DDD Invariants Business Rules and Validation

I am looking for advice on where to add validation rules for domain entities, and best practices for implementation. I did search and did not find what i was looking for, or i missed it.
I would like to know what the recommended way is for validating that properties are not null, in a certain range, or length, etc... I have seen several ways using an IsValid() and other discussions about enforcing in the constructor so the entity is never in an invalid state, or using preprocessing and postprocessing, and others using FluentValidation api, how invariants impact DRY and SRP.
Can someone give me a good example of where to put these sorts of checks, when using a App Service, Bounded Context, Domain Service, Aggregate Root, Entity layering. Where does this go, and what is the best approach?
Thanks.
When modeling your domain entity, it is best to consider real-world implications. Let's say you are dealing with a Employee entity.
Employees need a name
We know that in the real-world an employee must always have a name. It is impossible for an employee not to have a name. In other words, one cannot 'construct' an employee without specifying its name. So, use parameterised constructors! We also know that an employees name cannot change - so we prevent this from even happening by creating a private setter. Using the .NET type system to verify your employee is a very strong form of validation.
public string Name { get; private set; }
public Employee(string name)
{
Name = name;
}
Valid names have some rules
Now it starts to get interesting. A name has certain rules. Let's just take the simplistic route and assume that a valid name is one which is not null or empty. In the code example above, the following business rule is not validated against. At this point, we can still currently create invalid employees! Let's prevent this from EVER occurring by amending our setter:
public string Name
{
get
{
return name;
}
private set
{
if (String.IsNullOrWhiteSpace(value))
{
throw new ArgumentOutOfRangeException("value", "Employee name cannot be an empty value");
}
name = value;
}
}
Personally I prefer to have this logic in the private setter than in the constructor. The setter is not completely invisible. The entity itself can still change it, and we need to ensure validity. Also, always throw exceptions!
What about exposing some form of IsValid() method?
Take the above Employee entity. Where and how would an IsValid() method work?
Would you allow an invalid Employee to be created and then expect the developer to check it's validity with an IsValid() check? This is a weak design - before you know it, nameless Employees are going to be cruising around your system causing havoc.
But perhaps you would like to expose the name validation logic?
We don't want to catch exceptions for control flow. Exceptions are for catastrophic system failure. We also don't want to duplicate these validation rules in our codebase. So, perhaps exposing this validation logic isn't such a bad idea (but still not the greatest!).
What you could do is provide a static IsValidName(string) method:
public static bool IsValidName(string name)
{
return (String.IsNullOrWhiteSpace(value))
}
Our property would now change somewhat:
public string Name
{
get
{
return name;
}
private set
{
if (!Employee.IsValidName(value))
{
throw new ArgumentOutOfRangeException("value", "Employee name cannot be an empty value");
}
name = value;
}
}
But there is something fishy about this design...
We now are starting to spawn validation methods for individual properties of our entity. If a property has all kinds of rules and behavior attached to it, perhaps this is a sign that we can create an value object for it!
public PersonName : IEquatable<PersonName>
{
public string Name
{
get
{
return name;
}
private set
{
if (!PersonName.IsValid(value))
{
throw new ArgumentOutOfRangeException("value", "Person name cannot be an empty value");
}
name = value;
}
}
private PersonName(string name)
{
Name = name;
}
public static PersonName From(string name)
{
return new PersonName(name);
}
public static bool IsValid(string name)
{
return !String.IsNullOrWhiteSpace(value);
}
// Don't forget to override .Equals
}
Now our Employee entity can be simplified (I have excluded a null reference check):
public Employee
{
public PersonName Name { get; private set; }
public Employee(PersonName name)
{
Name = name;
}
}
Our client code can now look something like this:
if(PersonName.IsValid(name))
{
employee = new Employee(PersonName.From(name));
}
else
{
// Send a validation message to the user or something
}
So what have we done here?
We have ensured that our domain model is always consistent. Extremely important. An invalid entity cannot be created. In addition, we have used value objects to provide further 'richness'. PersonName has given the client code more control and more power and has also simplified Employee.
I built a library that can help you.
https://github.com/mersocarlin/ddd-validation

Proper way to secure domain objects?

If I have an entity Entity and a service EntityService and EntityServiceFacade with the following interfaces:
interface EntityService {
Entity getEntity(Long id);
}
interface EntityServiceFacade {
EntityDTO getEntity(Long id);
}
I can easily secure the read access to an entity by controlling access to the getEntity method at the service level. But once the facade has a reference to an entity, how can I control write access to it? If I have a saveEntity method and control access at the service (not facade) level like this (with Spring security annotations here):
class EntityServiceImpl implements EntityService {
...
#PreAuthorize("hasPermission(#entity, 'write')")
public void saveEntity(Entity entity) {
repository.store(entity);
}
}
class EntityServiceFacadeImpl implements EntityServiceFacade {
...
#Transactional
public void saveEntity(EntityDTO dto) {
Entity entity = service.getEntity(dto.id);
entity.setName(dto.name);
service.save(entity);
}
}
The problem here is that the access control check happens already after I have changed the name of the entity, so that does not suffice.
How do you guys do it? Do you secure the domain object methods instead?
Thanks
Edit:
If you secure your domain objects, for example with annotations like:
#PreAuthorize("hasPermission(this, 'write')")
public void setName(String name) { this.name = name; }
Am I then breaking the domain model (according to DDD?)
Edit2
I found a thesis on the subject. The conclusion of that thesis says that a good way IS to annotate the domain object methods to secure them. Any thoughts on this?
I wouldn't worry about securing individual entity methods or properties from being modified.
Preventing a user from changing an entity in memory is not always necessary if you can control persistence.
The big gotcha here is UX, you want to inform a user as early as possible that she will probably be unable to persist changes made to that entity. The decision you will need to make is whether it is acceptable to delay the security check until persistence time or if you need to inform a user before (e.g. by deactivating UI elements).
If Entity is an interface, can't you just membrane it?
So if Entity looks like this:
interface Entity {
int getFoo();
void setFoo(int newFoo);
}
create a membrane like
final class ReadOnlyEntity implements Entity {
private final Entity underlying;
ReadOnlyEntity(Entity underlying) { this.underlying = underlying; }
public int getFoo() { return underlying.getFoo(); } // Read methods work
// But deny mutators.
public void setFoo(int newFoo) { throw new UnsupportedOperationException(); }
}
If you annotate read methods, you can use Proxy classes to automatically create membranes that cross multiple classes (so that a get method on a readonly Entity that returns an EntityPart returns a readonly EntityPart).
See deep attenuation in http://en.wikipedia.org/wiki/Object-capability_model for more details on this approach.

Resources