DDD: Quering child objects of aggregate root - spring

If I have understood right, in domain driven design there are repositories for only aggregate root objects. So what is the right way to implement, for example, paging (or access control filtering) for those objects which are child objects of roots.
Example:
#Entity
public class Person extends AbstractPersistable<Long> {
#OneToMany
private List<Competence> competences = new ArrayList<>();
public void addCompetence( Competence competence ) {
this.competences.add( competence );
}
public List<Competences> competences() {
return this.competences;
}
}
So if I first get person object from repository and then I'd like to send subset (page) of competences to my front end? It not make sense to create CompetenceRepository to find competences by person because it brokes the whole idea of aggregate roots... For now I have used Spring Data JPA.

A popular approach is to avoid using the domain model (which is a transactional model optimized for processing commands) for queries. You can read about that a little more by searching for CQRS.

This sounds like there are few processes that needs to be defined.
What application / part of application that requires a paging of competences?
Paging part of a domain model to me does not belong to be part of a domain / business rules. It is an application concern.
The application service layer from DDD would probably be the place to put this.
You could create a service that helps your particular application to display the competences paging.

Related

Domain driven design - access modifiers for entities and enforcing validation

I am very new to DDD and reading various discussions on validation (where to put it) on the stackoverflow as well as on the web. I do like the idea of keeping the validations outside the entities and validate them depending upon the context. In our project, we have an entity called MedicalRecord and there are various rules for when one can be created or can be saved. I want to create a service layer, let's say RecordService, that would do some check to make sure if a user can create a medical record before creating one. I also want to create MedicalRecordRepository that would save the medical record. What confuses me is the access modifies on my entity and repository classes. Since both will be public, how can I enforce the client of my application to use the service instead of just creating new medical record (with public constructor) and use the repository to save it? I am using c#. I know DDD is language independent but wondering if someone could provide some thoughts on this.
Thanks.
You must control record creation by making the c'tor non-public and allowing creation only through a factory:
public class MedicalRecord
{
internal MedicalRecord()
{
}
}
public static class MedicalRecordFactory
{
public static MedicalRecord Create(User onBehalfOf)
{
// do logic here
return new MedicalRecord();
}
}
For the internal keyword to be applicable, either both classes must be in the same assembly or the class assembly must allow the factory assembly access with the InternalsVisibleTo attribute.
Edit
If you need to be able to perform validation at any time, you additionally have to encapsulate validation logic in another class (here partially done via an extension method):
public static class MedicalRecordValidator
{
public static bool IsValid(this MedicalRecord medicalRecord, <context>)
{
return IsValid(<context>);
}
public static bool IsValidForCreation(User onBehalfOf)
{
return IsValid(null, onBehalfOf);
}
private static bool IsValid(<context> context, User user = null)
{
// do validation logic here
}
}
then, the factory could do this:
public static MedicalRecord Create(User onBehalfOf)
{
return IsValidForCreation(onBehalfOf) ? new MedicalRecord() : null;
}
and you could also always do this:
if (myMedicalRecord.IsValid(<context>))
{
// ....
Only use your repository to retrieve your entities; not to save them. Saving (persisting) your entities is the responsibility of your unit of work.
You let your service change one or more entities (for instance a MedicalRecord) and track the changes in a unit of work. Before committing the changes in your unit of work, you can validate all entities for validation needs across entities. Then you commit your unit of work (in a single transaction), which will persist all your changes, or none at all.
For clarity, your MedicalRecord should protect its own invariants; such that a client retrieving a MedicalRecord using a repository, calling some methods to modify it and then persisting it using a unit of work, should result in a "valid" system state. If there are situations where this is not the case, then it can be argued that it should not be possible to retrieve a MedicalRecord on its own - it is part of some larger concept.
For creation purposes, using a factory like #Thomas suggests below is a good approach, although I think I'd call it a service (because of the collaboration between entities) instead of a factory. What I like about Thomas' approach is that it does not allow a client to create a MedicalRecord without a User (or other contextual information), without tying the MedicalRecord tightly to the user.

Where to put my queries - model vs. controller

I just switched from ActiveRecord/NHibernate to Dapper. Previously, I had all of my queries in my controllers. However, some properties which were convenient to implement on my models (such as summaries/sums/totals/averages), I could calculate by iterating over instance variables (collections) in my model.
To be specific, my Project has a notion of AppSessions, and I can calculate the total number of sessions, plus the average session length, by iterating over someProject.AppSessions.
Now that I'm in Dapper, this seems confused: my controller methods now make queries to the database via Dapper (which seems okay), but my model class also makes queries to the database via Dapper (which seems strange).
TLDR: Should the DB access go in my model, or controller, or both? It seems that both is not correct, and I would like to limit it to one "layer" so that changing DB access style later doesn't impact too much.
You should consider using a repository pattern:
With repositories, all of the database queries are encapsulated within a repository which is exposed through public interface, for example:
public interface IGenericRepository<T> where T : class
{
T Get(object id);
IQueryable<T> GetAll();
void Insert(T entity);
void Delete(T entity);
void Save(T entity);
}
Then you can inject a repository into a controller:
public class MyController
{
private readonly IGenericRepository<Foo> _fooRepository;
public MyController(IGenericRepository<Foo> fooRepository)
{
_fooRepository = fooRepository;
}
}
This keeps UI free of any DB dependencies and makes testing easier; from unit tests you can inject any mock that implements IRepository. This also allows the repository to implement and switch between technologies like Dapper or Entity Framework without any client changes and at any time.
The above example used a generic repository, but you don't have to; you can create a separate interface for each repository, e.g. IFooRepository.
There are many examples and many variations of how repository pattern can be implemented, so google some more to understand it. Here is one of my favorite articles re. layered architectures.
Another note: For small projects, it should be OK to put queries directly into controllers...
I can't speak for dapper personally, but I've always restricted my db access to models only except in very rare circumstances. That seems to make the most sense in my opinion.
A little more info: http://en.wikipedia.org/wiki/Model%E2%80%93view%E2%80%93controller
A model notifies its associated views and controllers when there has been a change in its state. This notification allows the views to produce updated output, and the controllers to change the available set of commands. A passive implementation of MVC omits these notifications, because the application does not require them or the software platform does not support them.
Basically, data access in models seems to be the standard.
I agree with #void-ray regarding the repository model. However, if you don't want to get into interfaces and dependency injection you could still separate out your data access layer and use static methods to return data from Dapper.
When I am using Dapper I typically have a Repository library that returns very small objects or lists that can then be mapped into a ViewModel and passed to the View (the mapping is done by StructureMap, but could be handled in the controller or another helper).

Which layer should I implement caching of lookup data from database in a DDD application?

I am designing a WCF service using DDD.
I have a domain service layer that calls repository to create domain objects. The repository is implemented using ADO.Net and not an ORM. The data comes from DB using Stored Procs. While creating an object say an Address the SP returns an id for state. The SP will not join address table with the state table. The state is represented by a value object class State that has id, abbr and name properties. The list of state objects can be cached (using system.runtime.caching.memorycache) when the application starts up as it is non-volatile data. In general I have a LookupDataRepository that can retrieve all such lookup data from tables. Now the AddressRepository has to populate the State property of address from the state id.
pseudo code:
class AddressRepository : IAddressRepository
{
Address GetAddressById(int id)
{
// call sp and map from data reader
Address addr = new Address(id);
addr.Line = rdr.GetString(1);
addr.State = // what to do ?, ideally LookupCache.GetState(rdr.GetInt32(2))
}
}
class State
{
public int Id;
public string Abbr;
public string Name;
enum StateId {VIC, NSW, WA, SA};
public static State Victoria = // what to do, ideally LookupCache.GetState(StateId.VIC)
}
// then somewhere in address domain model
if(currentState = State.Victroia)
{
// specific logic for Victoria
}
My question is which layer to put this cache ?. Service, Repository, a separate assembly available across all layers.
Where to put Cache? It depends.
If you're scenario will be that you inject your IAddressRepository into several application services (I believe you call em Domain services) the outcome will be:
Caching at repository level will result in that all services will benefit (Pros).
Caching at repository level will result in that all services must use cache (cons).
Caching at service level will only cache for those clients/service that use that specific service and methods (Pros/Cons?)
If you have your transaction management at service layer, you'll need to be careful when applying caching at repository level. Sometime a read operation may hit cache instead and the transaction cannot verify that the read data you're suppose to conduct write operation on isn't modified.
I would go for caching at Service layer. If feels more natural and gives you more control of where and when you want to cache. Repository level is usually to low grained. Service layer and its methods is more closer to use cases and it's then you know when and what to cache.
I really recommend writing a cache wrapper like
public class CacheManager : ICacheManager
{
public Address Address
{
get { }
set { }
}
}
That holds a static reference to System.Runtime.Caching.MemoryCache.Default.
It makes your Caching type safety and casting is only done inside wrapper. You can also unit test your services with a Mocked ICacheManager injected.
A more advanced approach is to do this with Aspect Oriented Programming and decorators/interceptors. You have tons of good info here at StackOverFlow https://stackoverflow.com/search?q=AOP+caching
In my opinion and from my experience, would caching as a repository result in duplicate code, more complexity to the domain, and all events need to be cached? Since an IRepository interface would be implemented ...
So I opted for an infrastructure service, let's cache only what is needed in our app. It is also available to all other services that wish to consume it.

Spring MVC 3 - Binding an 'immutable' object to a form

I have several thoroughly unit-tested and finely crafted rich DDD model classes, with final immutable invariants and integrity checks. Object's instantiation happens through adequate constructors, static factory methods and even via Builders.
Now, I have to provide a Spring MVC form to create new instances of some classes.
It seems to me (I'm not an expert) that I have to provide empty constructor and attribute's setters for all form's backing classes I want to bind.
So, what should I do ?
Create anemic objects dedicated to form backing and transfer the informations to my domain model (so much for the DRY principle...) calling the appropriate methods / builder ?
Or is there a mecanisms that I missed that can save my day ? :)
Thank you in advance for your wisdom !
The objects that are used for binding with the presentation layers are normally called view models and they are DTOs purposed toward displaying data mapped from domain objects and then mapping user input back to domain objects. View models typically look very similar to the domain objects they represent however there are some important differences:
Data from the domain objects may be flattened or otherwise transformed to fit the requirements of a given view. Having the mapping be in plain objects is easier to manage than mappings in the presentation framework, such as MVC. It is easier to debug and detect errors.
A given view may require data from multiple domain objects - there may not be a single domain object that fits requirements of a view. A view model can be populated by multiple domain objects.
A view model is normally designed with a specific presentation framework in mind and as such may utilize framework specific attributes for binding and client side validation. As you stated, a typical requirement is for a parameterless constructor, which is fine for a view model. Again, it is much easier to test and manage a view model than some sort of complex mapping mechanism.
View models appear to violate the DRY principle, however after a closer look the responsibility of the view model is different, so with the single responsibility principle in mind it is appropriate to have two classes. Also, take a look at this article discussing the fallacy of reuse often lead by the DRY principle.
Furthermore, view models are indeed anemic, though they may have a constructor accepting a domain object as a parameter and a method for creating and updating a domain object using the values in the view model as input. From experience I find that it is a good practice to create a view model class for every domain entity that is going to be rendered by the presentation layer. It is easier to manage the double class hierarchy of domain objects and view models than it is to manage complex mapping mechanisms.
Note also, there are libraries that attempt to simplify the mapping between view models and domain objects, for example AutoMapper for the .NET Framework.
Yes you will need to create Objects for the form to take all the input, and the update the your model with this objects in one operation.
But I wont call this objects anemic (especially if you do DDD). This objects represent one unit of work. So this are Domain Concepts too!
I solved this by creating a DTO Interface:
public interface DTO<T> {
T getDomainObject();
void loadFromDomainObject(T domainObject);
}
public class PersonDTO implements DTO<Person> {
private String firstName;
private String lastName;
public PersonDTO() {
super();
}
// setters, getters ...
#Override
public Person getDomainObject() {
return new Person(firstName, lastName);
}
#Override
public void loadFromDomainObject(Person person) {
this.firstName = person.getFirstName();
this.lastName = person.getLastName();
}
// validation methods, view formatting methods, etc
}
This also stops view validation and formatting stuff from leaking into the domain model. I really dislike having Spring specific (or other framework specific) annotations (#Value, etc) and javax.validation annotations in my domain objects.

What is the difference between an MVC Model object, a domain object and a DTO

What is the difference between a MVC Model object, a domain object and a DTO?
My understanding is:
MVC Model object:
Models the data to be displayed by a corresponding view. It may not map directly to a domain object, i.e. may include data from one or more domain objects.
Client side
May contain business logic. Eg. validations, calculated properties, etc
No persistence related methods
Domain object:
An object that models real-world object in the problem domain like Reservation, Customer, Order, etc. Used to persist data.
Server side
No business logic
DTO (Data Transfer Object):
An object used to transfer data between layers when the layers are in separate processes, e.g. from a DB to a client app. Allows a single transaction across the wire rather than multiple calls when fetching data corresponding to multiple domain objects. A DTO contains just data and accessor methods and there is no logic present. The data is for a particular DB transaction, so it may or may not directly map to a domain object as it may include data from one or more domain objects.
Used on both server and client sides as it is passed between layers
No business logic
No persistence related methods
So, the questions:
Is above understanding correct? Am I missing some key points?
Are there any reasons not to use Domain objects as the MVC Model assuming that the Model objects do not require extra business logic?
Are there any reasons not to use DTOs as the MVC Model assuming that the Model objects do not require extra business logic?
Domain and model objects are essentially the same, and may contain business logic. Depending on implementation, domain and DTO objects may be equivalent if you remove business logic from the model into a service class.
Often a key variant of the DTO is the View Model, which is used purely to transfer data between the domain model and the view, although often a View Model may contain logic, although this should be purely UI logic.
The Domain and DTO can also be your "model" objects - you can have a view to render the details of the "Customer" domain object.
A domain object can have business logic to enforce the properties of the domain entity. validation is one such case. The domain object by itself does not contain persistence related methods, but it can have meta-data (like annotations) to support persistence
the POJO programming model makes it possible to use the same object as your domain, DTO and model objects - essentially, you will not be implemented any extraneous interfaces that will only apply to one layer but does not apply to others.
A DTO = is an object that carries data between processes.
But the most interesting part is that, it does not have any behavior except for storage and retrieval of its own data!!!
Sticking with the MVC methodology...
Domain = subject of your entire application.
Model = contains the (programming languages objects : EX: C# objects) to make up the universe of your application.
They can obvioussly have behaviour and properties(see difference with DTO).
Often an application (a light one) can have one model - case in which your model is exactly your domain.
Another model can be, a totaly different object type, that is processing another one. Both of them, in this case are part of your domain, and are named "domain models - objects".
Hopefully this answer is exhaustive and makes it all clear for you !
My understing (in a big short) is as follows:
(MVC) Model object:
represent some things in a some usage context eg. PersonEditModel, PersonViewModel or just PersonModel
has no business logic
can be subject of some valdation logic etc.
used to provide data from one application layer to another eg. MVC Controller <-> MVC View
Domain object:
represents some business object (real world object in the problem domain)
has business logic
do not allow invalid object state, has methods to properly change object's state
used to encapsulate business logic related to it
have not to be used to persist data (or even should not)
DTO (Data Transfer Object):
similar to Model object but should have flat structure
only simple type properties/fields (strings, numbers, datetimes, booleans)
used to transfer data cross application boundaries eg. between web server and web browser
Any definition for most of the objects is various based on place of using of objects:
Model: is a general definition for using object in client or server.
Model View : is a object using in client most of the time.
Domain Object : is a object using in server and transfering data to the database.
Data Transfer Object(DTO) : is a object that transfer data from one object to another object, specially in getting data in API Call(for example: in api GET Method call for getting data you must not to give database models to client, for this purpose you use dto).
Notice: the definitions are true most of the time but in some situations arent't practical.
MVC and DDD can be used together. What we call "Models" both in DDD and MVC are virtually the same: abstractions. Using pseudo-code we can illustrate a few examples.
Model View Controller (MVC)
The Model View Controller ARCHITECTURE separates the software into three parts:
The Model Layer
The Model layer from the MVC Architecture is where the logic resides. In this layer we have our models and business logic.
class Car {
String color;
String year;
Cat(color, year) {
this.color = color;
this.year = year;
}
//getters & setters
}
A simple Car abstraction.
class CarService {
save(car) {
if(car.getColor() != null && car.getYear() != null) {
methodToSave(car);
} else {
throwsException();
}
}
find(car) {
return methodToFind(car);
}
update(car) {
assertThatExists(car);
methodToSave(car);
}
delete(car) {
assertThatExists(car);
methodToDelete(car);
}
}
A simple CRUD for Car using a Service
The View Layer
The View layer is where the user interface resides. Here's where the user can interact with the system, which will then trigger the Controllers on actions performed, which will then inform the Model layer and request data. The View Layer can reside either in the client-side of the application or the server-side of the application (ie: JSF (Java Server Faces) as Server-Side, ReactJS as Client-Side). By any means, even if the View layer resides on the client side, the client will need to request the server-side for sending requests. This may be done by HTTP requests for a Web-Based Application.
<theCarPage>
<theCar>
getTheCarOnLoad();
</theCar>
</theCarPage>
A pseudo-page for the Car.
The Controller Layer
The Controller layer basically receives input from the View and then convert and send the data to the Model Layer and vice-versa.
class CarController {
#OnLoadingTheCarPage
getTheCarOnLoad() {
return theCar();
}
}
The method to load the Car.
Domain Driven Design (DDD)
Domain Driven Design is a concept:
DDD lays it's foundations in the concept that classes, class variables and class methods must match it's core business domain.
Domain Driven Design Resides into the "M"
In this case, when MVC is applied, the Domain Driven Design resides into the Model Layer of the MVC Architecture. As explained before, the Model Layer is where the Business Logic of the application resides.
Either if you have entities or not, they still are Models. A Model is just an abstraction of something in the real world. A cat can be a Model if abstracted:
class Cat {
String color;
String age;
Cat(color, age) {
this.color = color;
this.age = age;
}
//getters & setters
}
Simple Cat abstraction. It is a Model of Cat.
DDD Entities
In Domain Driven Design we have Entities, that are also classified as Models. The difference between them is that Entities are identifiable. If you have a class that is identifiable and can be persisted, then it's an Entity. An Entity still, is a Model.
#AnEntity
#ThisCanBePersisted
class Cat {
#ThisIsAnId
#ThisValueIncrementsAutomatically
#PersistentProperty
Long id;
#PersistentProperty
String color;
#PersistentProperty
String age;
Cat(color, age) {
this.color = color;
this.age = age;
}
//getters & setters
}
A simple Entity. An Entity is a Model.
Data Transfer Objects (DTO)
Data Transfer Objects have no logic inside them and the only use to them is to be containers for transferring data from one endpoint to another. Usually Enterprise Entities are not Serializable by nature, so we need a way to send only the data that we need to be sent to a client.
Since a Model could have sensible data or simply data we don't want to share in a request for a fetch, for instance, then considering our Cat Model, we could create a DTO that does not share the Cat's ID:
class CatDTO {
String color;
String age;
//getters & setters
}
A Data Transfer Object for Cat. We only need it's properties and something to get and set the properties. We don't want to share it's ID.
So if we, for instance, had to request a list of all cats from our client using REST, then we would request the endpoint that responds with our CatDTO instead of our Cat Entity:
[
Cat {
"color": "yellow",
"age": "1"
},
Cat {
"color": "black",
"age": "4"
}
]
And that would be all the data that our client could see.
1) No, It is a definition of ViewModel. MVC Model Object and Domain Object both are same.
2) Domain Models (Objects) are always present, business logic is optional
3) If there is no business logic in Domain Object then automatically it becomes DTO.

Resources