germanandino
germanandino

Reputation: 1

Simple CRUD in Application Services, DDD way

I'm new to DDD, and been reading a lot about it, but I can't figure this out. I'm making a tipical CRUD operation (Create), and I have to validate some field against, the rest of the entities persisted in my repository.

I know that Application Services, shouldn't have any business logic, a domain Entity, should not access to repositories directly, a Domain Service, may be the best choice, but I don't know how to do it well. I'm very confused.

How can I correct the next code:

class CustomerApplicationService {

    void AddNew ( CustomerDTO myNewCustomerDTO ) {

        CustomerRepository myCustomerRepo = new CustomerRepository();
        var allCustomers = myCustomerRepo.FindAll();
        for each (Customer c in allCustomers) {
            if (c.SomeField == myNewCustomerDTO.SomeField) {
                // do something, check duplicate data, etc
            }
        }
        var myNewCustomer = new Customer();
        // map myNewCustomer ... fields with myNewCustomerDTO
        myCustomerRepo.Save( myNewCustomer );
    }
}

Thanks!

Upvotes: 0

Views: 848

Answers (1)

Tyler Day
Tyler Day

Reputation: 1718

I guess it all depends on what you are doing on the line that says "// do something". Checking for duplicates is not really a domain layer concern, so that's fine to check in your application layer. Although I wouldn't load all your customers into memory to check for that. Your repository could just have a FindByUsername or FindByEmail method, and if it doesn't return any results then it's not a duplicate. Same goes for simple validation, like checking for nulls or string length. That type of validation goes in the application layer. Only put logic into your domain models when it makes sense to do so, such as when you have a true complex business problem and the logic is volatile. A constraint like username is unique is not really volatile so it doesn't belong in your domain model.

It's also important to remember that just because you are "doing DDD" doesn't mean that's the only tool your system can use. If all you have is a simple CRUD insert, then just do a CRUD insert with ADO.NET or whatever is easiest. Reserve DDD for when you have true complexity and invariants that need to be enforced.

Overall I think your general approach looks pretty good though.

Upvotes: 2

Related Questions