DDD, Aggregate Root and entities in library application scenario - oop

I'm building a library application. Let's assume that we have a requirement to let registered people in the library to borrow a book for some default period of time (4 weeks).
I started to model my domain with an AggregateRoot called Loan with code below:
public class Loan : AggregateRoot<long>
{
public static int DefaultLoanPeriodInDays = 30;
private readonly long _bookId;
private readonly long _userId;
private readonly DateTime _endDate;
private bool _active;
private Book _book;
private RegisteredLibraryUser _user;
public Book Book => _book;
public RegisteredLibraryUser User => _user;
public DateTime EndDate => _endDate;
public bool Active => _active;
private Loan(long bookId, long userId, DateTime endDate)
{
_bookId = bookId;
_userId = userId;
_endDate = endDate;
_active = true;
}
public static Loan Create(long bookId, long userId)
{
var endDate = DateTime.UtcNow.AddDays(DefaultLoanPeriodInDays);
var loan = new Loan(bookId, userId, endDate);
loan.Book.Borrow();
loan.AddDomainEvent(new LoanCreatedEvent(bookId, userId, endDate));
return loan;
}
public void EndLoan()
{
if (!Active)
throw new LoanNotActiveException(Id);
_active = false;
_book.Return();
AddDomainEvent(new LoanFinishedEvent(Id));
}
}
And my Book entity looks like this:
public class Book : Entity<long>
{
private BookInformation _bookInformation;
private bool _inStock;
public BookInformation BookInformation => _bookInformation;
public bool InStock => _inStock;
private Book(BookInformation bookInformation)
{
_bookInformation = bookInformation;
_inStock = true;
}
public static Book Create(string title, string author, string subject, string isbn)
{
var bookInformation = new BookInformation(title, author, subject, isbn);
var book = new Book(bookInformation);
book.AddDomainEvent(new BookCreatedEvent(bookInformation));
return book;
}
public void Borrow()
{
if (!InStock)
throw new BookAlreadyBorrowedException();
_inStock = false;
AddDomainEvent(new BookBorrowedEvent(Id));
}
public void Return()
{
if (InStock)
throw new BookNotBorrowedException(Id);
_inStock = true;
AddDomainEvent(new BookReturnedBackEvent(Id, DateTime.UtcNow));
}
}
As you can see I'm using a static factory method for creating my Loan aggregate root where I'm passing an identity of the borrowing book and the user identity who is going to borrow it. Should I pass here the references to these objects (book and user) instead of ids? Which approach is better? As you can see my Book entity has also a property which indicates the availability of a book (InStock property). Should I update this property in the next use-case, for example in the handler of LoadCreatedEvent? Or should it be updated here within my AggregateRoot? If it should be updated here inside my aggregate I should pass the entire book reference instead of just an ID to be able to call it's method _book.Borrow().
I'm stuck at this point because I would like to do it pretty correct with the DDD approach. Or am I starting to do it from the wrong side and I'm missing something or thinking in a wrong way of it?

DomainEvents are in-memory events that are handled within the same domain.
You commit or rollback the entire "Transaction" together. Consider Domain Event as a DTO, which needs to hold all the information related to what just happened in the domain. So, as long as you have that information I do not think it matters if you pass Id, or the entire object.
I would go for passing the id in the domain event though as that information is sufficient to pass on the information to the DomainEventHandler.
Also, refer to this example of a similar scenario in Microsoft Docs, where they only pass UserId and CardTypeId along with all the other relevant information in the Domain event.
public class OrderStartedDomainEvent : INotification {
public string UserId { get; }
public int CardTypeId { get; }
public string CardNumber { get; }
public string CardSecurityNumber { get; }
public string CardHolderName { get; }
public DateTime CardExpiration { get; }
public Order Order { get; }
public OrderStartedDomainEvent(Order order,
int cardTypeId, string cardNumber,
string cardSecurityNumber, string cardHolderName,
DateTime cardExpiration)
{
Order = order;
CardTypeId = cardTypeId;
CardNumber = cardNumber;
CardSecurityNumber = cardSecurityNumber;
CardHolderName = cardHolderName;
CardExpiration = cardExpiration;
} }

There are a couple of things that look suspicious in your sample code:
The first one, Loan does the following:
loan.Book.Borrow();
but it doesn't have a reference to Book and, at first sight, it doesn't seem it should either.
The second one, your Book entity seems to have many responsibilities: hold book information like Author, title, subject, hold stock information, and manage the Borrowing state. This is far too many responsibilities for an aggregate, let alone for an entity within an aggregate. Which also begs the question, does a Book really belong to a Loan? it seems strange.
I would recommend, rethinking your aggregates and try to give them a single purpose. What follows is purely as an example on the type of thinking that you could do, not a proposed design:
First, it makes sense to have a Book somewhere, which holds the book information. You can manage book information and Author information completely independent from the rest of the system. In fact, this part would look pretty much the same for a book store, a library, a publishing company, and an e-commerce site.
As you are modeling a Library, it probably makes sense to have something like LibraryItem (domain experts will know the right word for this). This item might have a type (book, DVD, magazine, etc) and the id of the actual item, but it doesn't care about the Title, Description, etc. with the Id is enough. Potentially, it also stores the location/sorting of the item with the library. Also, this Item might have some sort of Status, let's say Active/Retired. If it's Active, the item exists in the Library. If it's Retired, it doesn't exist anymore. If you have multiple items of the same book, you'll simply create more Items with the same BookId and if it's possible to identify the concrete physical book, with a bar code, for example, each Item will have that unique code, so you can find it by scanning the bar code.
Now a Loan, to me, it's basically an ItemId plus a CustomerId (not sure if they are called customers in this domain). Every time a Customer wants to borrow an Item, the user will find the Item (maybe scanning the bar code), and find the Customer. At this point you have to create the Loan with the CustomerId, ItemId, date and not a lot more I would say. This could be an aggregate on itself or simply be managed by the Item. Depending on what you chose the implementation will vary obviously. Note that you don't reuse Loans. You'll have somewhere a list of Loans that you can query and this list won't be inside the Item aggregate. This aggregate only needs to make sure that 2 loans of the same item are not allowed at the same time.
Well, that was a rather long preliminary explanation to answer your question: you need to manage the InStock in the same aggregate that allows you to Borrow a book. It has to be transactional, because you want to ensure that a book is not borrowed multiple times at once. But instead of passing one aggregate to the other, design your aggregates so that they have the right data and responsibilities together.

Related

OOP creating and copying an object that depends on one value

I am sorry but I didn't know what to call this post (if you have a better title please tell me in a comment).
Say for instance you have the following Object whose purpose is to create chart series of the data specified in the Constructor:
/**
* Helper to generate chart series
*/
public class ChartHelper
{
public System.Windows.Forms.DataVisualization.Charting.Chart ChartType { get; set; }
public String TimeType { get; set; }
private readonly List<IObject> _datalist;
private readonly TimeType _timeType;
private readonly DateTime _stopDate;
private readonly DateTime _startDate;
public ChartHelper(List<IObject> dataList, TimeType timeType, DateTime startDate, DateTime stopDate)
{
_startDate = startDate;
_stopDate = stopDate;
_datalist = dataList;
_timeType = timeType;
}
public System.Windows.Forms.DataVisualization.Charting.Chart GetChart()
{
CreateSeries(_startDate);
return ChartType;
}
private void CreateSeries(DateTime seriesTime)
{
//Do something
}
//More internal private methods
}
Now say for instance you have a program that creates 10 different Charts but only the value of the List<IObject> dataList changes.
Then you could do one of two things:
Create 10 different ChartHelper Objects
Use the same Object and change the dataList value
This is of course an example of how the problem could be presented when developing (ive met this problem several times)
My question is, is there a design pattern that helps you solve this issue ? Or is there a best practice method that would be useful for these situations? It is important for me to learn these methods as I wish to improve my own skills.
If only the data is different then I would recommend using the same class and creating 10 different objects from it.
If however the implementation of the CreateSeries would be different depending on the type of data, than this would be a candidate for the Strategy pattern. In that case you would extract the creation of the series behind an interface and provide implementations for the different kinds of series. You could then also have a factory that picks the correct strategy depending on the data and composes a chart (helper).

Populating association properties in entities from service call

Say I have a common pattern with a Customer object and a SalesOrder object. I have corresponding SalesOrderContract and CustomerContract objects that are similar, flatter objects used to serialize through a web service
public class Customer
{
public int CustomerId { get; set; }
public string Name { get; set; }
public Address ShippingAddress { get; set; }
//more fields...
}
public class Order
{
public int OrderId { get; set; }
public Customer Customer { get; set;
// etc
}
And my sales order contract looks like this
public class OrderContract
{
public int OrderId { get; set; }
public int CustomerId { get; set; }
}
public class OrderTranslator
{
public static Order ToOrder(OrderContract contract)
{
return new Order { OrderId = contract.OrderId };
// just translate customer id or populate entire Customer object
}
}
I have a layer inbetween the service layer and business object layer that translates between the two. My question is this...do I populate the Order.Customer object on the other end since the Order table just needs the customer id. I don't carry the entire customer object in the OrderContract because it's not necessary and too heavy. But, as part of saving it, I have to validate that it's indeed a valid customer. I can do a few things
Populate the Order.Customer object completely based on the CustomerId when I translate between contract and entity.. This would require calling the CustomerRepository in a helper class that translates between entities and contracts. Doesn't feel right to me. Translator should really just be data mapping.
Create a domain service for each group of operations that performs the validation needed without populating the Order.Customer. This service would pull the Customer object based on Order.CustomerId and check to see if it's valid. Not sure on this because a sales order should be able to validate itself, but it's also not explicitly dealing with Orders as it also deals with Customers so maybe a domain service?
Create a seperate property Order.CustomerId and lazy load the customer object based on this.
Populate Order.Customer in from a factory class. Right now my factory classes are just for loading from database. I'm not really loading from datacontracts, but maybe it makes sense?
So the question is two part...if you have association properties in your enties that will be required to tell if something is completely valid before saving, do you just populate them? If you do, where you do actually do that because the contract/entity translator feels wrong?
The bottom line is that I need to be able to do something like
if (order.Customer == null || !order.Customer.IsActive)
{
//do something
}
The question is where does it make sense to do this? In reality my Order object has a lot of child entities required for validation and I don't want things to become bloated. This is why I'm considering making domain services to encapsulate validation since it's such a huge operation in my particular case (several hundred weird rules). But I also don't want to remove all logic making my objects just properties. Finding the balance is tough.
Hope that makes sense. If more background is required, let me know.
You have a couple of things going on here. I think part of the issue is mainly how you appear to have arranged your Translator class. Remember, for an entity, the whole concept is based on instance identity. So a Translator for an entity should not return a new object, it should return the correct instance of the object. That typically means you have to supply it with that instance in the first place.
It is perhaps useful to think in terms of updates vs creating a new object.
For an update the way I would structure this operation is as follows: I would have the web service that the application calls to get and return the contract objects. This web service calls both repositories and Translators to do it's work. The validation stays on the domain object.
In code an update would look something like the following.
Web Service:
[WebService]
public class OrderService
{
[WebMethod]
public void UpdateOrder(OrderContract orderContract)
{
OrderRepository orderRepository = new OrderRepository(_session);
// The key point here is we get the actual order itself
// and so Customer and all other objects are already either populated
// or available for lazy loading.
Order order = orderRepository.GetOrderByOrderContract(orderContract);
// The translator uses the OrderContract to update attribute fields on
// the actual Order instance we need.
OrderTranslator.OrderContractToOrder(ref order, orderContract);
// We now have the specific order instance with any properties updated
// so we can validate and then persist.
if (order.Validate())
{
orderRepository.Update(order);
}
else
{
// Whatever
}
}
}
Translator:
public static class OrderTranslator
{
public static void OrderContractToOrder(ref Order order, OrderContract orderContract)
{
// Here we update properties on the actual order instance passed in
// instead of creating a new Order instance.
order.SetSomeProperty(orderContract.SomeProperty);
// ... etc.
}
}
The key concept here is because we have an entity, we are getting the actual Order, the instance of the entity, and then using the translator to update attributes instead of creating a new Order instance. Because we are getting the original Order, not creating a new instance, presumably we can have all the associations either populated or populated by lazy load. We do not have to recreate any associations from an OrderContract so the issue goes away.
I think the other part of the issue may be your understanding of how a factory is designed. It is true that for entities a Factory may not set all the possible attributes - the method could become hopelessly complex if it did.
But what a factory is supposed to do is create all the associations for a new object so that the new object returned is in a valid state in terms of being a full and valid aggregate. Then the caller can set all the other various and sundry "simple" attributes.
Anytime you have a Factory you have to make decisions about what parameters to pass in. Maybe in this case the web service gets the actual Customer and passes it to the factory as a parameter. Or Maybe the web service passes in an Id and the factory is responsible for getting the actual Customer instance. It will vary by specific situation but in any case, however it gets the other objects required, a factory should return at minimum a fully populated object in terms of it's graph, i.e all relationships should be present and traversible.
In code a possible example of new Order creation might be:
[WebService]
public class OrderService
{
[WebMethod]
public void SaveNewOrder(OrderContract orderContract)
{
// Lets assume in this case our Factory has a list of all Customers
// so given an Id it can create the association.
Order order = OrderFactory.CreateNewOrder(orderContract.CustomerId);
// Once again we get the actual order itself, albeit it is new,
// and so Customer and all other objects are already either populated
// by the factory create method and/or are available for lazy loading.
// We can now use the same translator to update all simple attribute fields on
// the new Order instance.
OrderTranslator.OrderContractToOrder(ref order, orderContract);
// We now have the new order instance with all properties populated
// so we can validate and then persist.
if (order.Validate())
{
//Maybe you use a Repository - I use a unit of work but the concept is the same.
orderRepository.Save(order);
}
else
{
//Whatever
}
}
}
So, hope that helps?

Is there something analogous on NHibernate regarding Entity Framework's navigation property?

Is there something analogous on NHibernate regarding Entity Framework's navigation property? For example, instead of:
s.Save(new Product { Category = s.Get<Category>("FD"), Name = "Pizza" });
I wish I could write:
s.Save(new Product { CategoryId = "FD", Name = "Pizza" });
Can I inform NHibernate not to use the Product's Category property as a mechanism to save the Product's category? I want to use CategoryId instead(Read: I don't want to use DTO). Entity Framework seems able to facilitate avoiding DTO patterns altogether, while at the same time offering the full benefit of ORM(can avoid joins using navigation properties). I want the EF's offering the best of both worlds(lean mechanism for saving objects, i.e. no need to retrieve the property's object) and navigation mechanism for querying stuff
Sample from EF: http://blogs.msdn.com/b/adonet/archive/2011/03/15/ef-4-1-code-first-walkthrough.aspx
public class Category
{
public virtual string CategoryId { get; set; }
public virtual string Name { get; set; }
public virtual IList<Product> Products { get; set; }
}
public class Product
{
public virtual int ProductId { get; set; }
public virtual string Name { get; set; }
public virtual string CategoryId { get; set; }
public virtual Category Category { get; set; }
}
[UPDATE]
Regarding James answer, I tried seeing the NHibernate's actions in SQL Server Profiler.
// this act didn't hit the Category table from the database
var c = s.Load<Category>("FD");
// neither this hit the Category table from the database
var px = new Product { Category = c, Name = "Pizza" };
// this too, neither hit the Category table from the database
s.Save(px);
Only when you actually access the Category object that NHibernate will hit the database
Console.WriteLine("{0} {1}", c.CategoryId, c.Name);
If I understand your question, you want to save a Product with a Category without hitting the database to load the Category object. NHibernate absolutely supports this and you almost have the right code. Here is how you do it in NHibernate:
s.Save(new Product { Category = s.Load<Category>("FD"), Name = "Pizza" });
This will not hit the database to fetch the actual Category, but it will simply save a Product with the correct Category.Id. Note that you don't need (and I would recommend getting rid of Product.CategoryId).
Now why does this work with session.Load(), but not session.Get()... With session.Get(), NHibernate has to return the object or null. In .NET, there is no way for an object to replace itself with null after the fact. So NHibernate is forced to go to the database (or L1 cache) to verify that the "FD" Category actually exists. If it exists, it returns an object. If not, it must return null.
Let's look at session.Load(). If the object is not present in the database, it throws an exception. So NHibernate can return a proxy object from session.Load() and delay actually hitting the database. When you actually access the object, NHibernate will check the database and can throw an exception at that point if the object doesn't exist. In this case, we're saving a Product to the database. All NHibernate needs is the Category's PK, which it has in the proxy. So it doesn't have to query the database for the Category object. NHibernate never actually needs to hydrate an actual Category object to satisfy the save request.

DDD confused with Repository Pattern and Reports

I am new to DDD and the Repository pattern, so my understanding of it might be totally wrong. But I am trying to learn it. Having said that I need to create an application, which shows the zones of a store. I create a ZoneRepository for that purpose, which works so far with my few methods. Now in that application I also need to show the distinct styles for that store. The list of styles will be used to drag them into the individual zones. Now my question is where does the styles class belong to, since its kind of a mini-report. Does that "StyleReport" belong into the repository? Does it belong somewhere else? How you know where it belongs to? Please help me to understand.
Repositories only act on Aggregate Roots. Aggregates are a boundary around one or more objects that are treated as a unit. By that I mean, when you operate on that data (inserting, updating, deleting, etc.), all of the objects within that boundary are affected accordingly. Every aggregate has a root. This root is what is referenced externally by other parts of the software. I guess one way to describe it is "something that doesn't rely on something else".
It's a little challenging to derive the proper definition of your domain from a description of your existing models. Furthermore, the design should be based on the business model and needs, not how your UI or application works. So, you should model it on the general problem you are solving, not on how you think you'd like to solve it.
It sounds like you have an entity Store. A Store can be divided up into one or more Zones. Each Zone then has one or more StyleReports. It sounds to me like the Zones are dependent on a Store, so the Store is the aggregate root. Now, perhaps these StyleReport entities are a global set of objects that you offer in your problem domain (meaning you define the StyleReports separately, application-wide, and refer to them in your Zones). In that case, perhaps StyleReport is also an aggregate root.
Here are some example models (C#, not sure what language you're using). However, don't take this as the absolute word. If I don't know the specifics about your domain, I can't very well model it.
public class Store
{
public Int32 ID { get; }
public String Name { get; set; }
public IList<Zone> Zones { get; private set; }
public Store()
{
Zones = new List<Zone>();
}
public void AddZone(Zone zone)
{
Zones.Add(zone);
}
}
public class Zone
{
public Int32 ID { get; }
public String Name { get; set; }
public IList<StyleReport> Styles { get; private set; }
public Zone()
{
Styles = new List<StyleReport>();
}
public void AddStyle(StyleReport style)
{
Styles.Add(style);
}
}
public class StoreRepository : Repository<Store>
{
public Store Get(Int32 id)
{
// get store from persistence layer
}
// find, delete, save, update, etc.
}
public class StyleReportRepository : Repository<StyleReport>
{
public StyleReport Get(Int32 id)
{
// get style from persistence layer
}
// find, delete, save, update, etc.
}
And so when modifying a store's zones and adding styles, maybe something like this
IRepository<Store> storeRepository = new StoreRepository();
IRepository<StyleReport> stylesRepository = new StyleReportRepository();
Store store = storeRepository.Get(storeID); // store id selected from UI or whatever
// add a zone to the store
Zone someZone = new Zone { Name = zoneNamea }; // zone name was entered by the UI
someZone.AddStyle(styleRepository.Get(styleID)); // style id was selected from UI
storeRepository.Update(store);

Question about Repositories and their Save methods for domain objects

I have a somewhat ridiculous question regarding DDD, Repository Patterns and ORM. In this example, I have 3 classes: Address, Company and Person. A Person is a member of a Company and has an Address. A Company also has an Address.
These classes reflect a database model. I removed any dependencies of my Models, so they are not tied to a particular ORM library such as NHibernate or LinqToSql. These dependencies are dealt with inside the Repositories.
Inside one of Repositories there is a SavePerson(Person person) method which inserts/updates a Person depending on whether it already exists in the database.
Since a Person object has a Company, I currently save/update the values of the Company property too when making that SavePerson call. I insert / update all of the Company's data - Name and Address - during this procedure.
However, I really have a hard time thinking of a case where a Company's data can change while dealing with a Person - I only want to be able to assign a Company to a Person, or to move a Person to another Company. I don't think I ever want to create a new Company alongside a new Person. So the SaveCompany calls introduce unnecessary database calls. When saving a Person I should just be able to update the CompanyId column.
But since the Person class has a Company property, I'm somewhat inclined to update / insert it with it. From a strict/pure point of view, the SavePerson method should save the entire Person.
What would the preferred way be? Just inserting/updating the CompanyId of the Company property when saving a Person or saving all of its data? Or would you create two distinct methods for both scenarios (What would you name them?)
Also, another question, I currently have distinct methods for saving a Person, an Address and a Company, so when I save a Company, I also call SaveAddress. Let's assume I use LinqToSql - this means that I don't insert/update the Company and the Address in the same Linq query. I guess there are 2 Select Calls (checking whether a company exists, checking whether an address exists). And then two Insert/Update calls for both. Even more if more compound model classes are introduced. Is there a way for LinqToSql to optimize these calls?
public class Address
{
public int AddressId { get; set; }
public string AddressLine1 { get; set; }
public string AddressLine2 { get; set; }
public string City { get; set; }
public string PostalCode { get; set; }
}
public class Company
{
public int CompanyId { get; set; }
public string Name { get; set; }
public Address Address { get; set; }
}
public class Person
{
public int PersonId { get; set; }
public string FirstName { get; set; }
public string LastName { get; set; }
public string Email { get; set; }
public Company Company { get; set; }
public Address Address { get; set; }
}
Edit
Also see this follow up question. How are Value Objects stored in a Database?
I myself have used the IRepository approach lately that Keith suggests. But, you should not be focusing on that pattern here. Instead, there are a few more pieces in the DDD playbook that can be applied here.
Use Value Objects for your Addresses
First, there is the concept of Value Objects (VO) you can apply here. In you case, it would be the Address. The difference between a Value Object and an Entity Object is that Entities have an identity; VOs do not. The VO's identity really is the sum of it's properties, not a unique identity. In the book Domain-Drive Design Quickly (it's also a free PDF download), he explains this very well by stating that an address is really just a point on Earth and does not need a separate SocialSecurity-like identity like a person. That point on Earth is the combination of the street, number, city, zip, and country. It can have latitude and longitude values, but still those are even VOs by definition because it's a combination of two points.
Use Services for combining your entities into a single entity to act upon.
Also, do not forget about the Services concept in the DDD playbook. In your example, that service would be:
public class PersonCompanyService
{
void SavePersonCompany(IPersonCompany personCompany)
{
personRepository.SavePerson();
// do some work for a new company, etc.
companyRepository.SaveCompany();
}
}
There is a need for a service when you have two entities that need both need a similar action to coordinate a combination of other actions. In your case, saving a Person() and creating a blank Company() at the same time.
ORMs usualyl require an identity, period.
Now, how would you go about saving the Address VO in the database? You would use an IAddressRepository obviously. But since most ORMs (i.e. LingToSql) require all objects have an Identity, here's the trick: Mark the identity as internal in your model, so it is not exposed outside of your Model layer. This is Steven Sanderson's own advice.
public class Address
{
// make your identity internal
[Column(IsPrimaryKey = true
, IsDbGenerated = true
, AutoSync = AutoSync.OnInsert)]
internal int AddressID { get; set; }
// everything else public
[Column]
public string StreetNumber { get; set; }
[Column]
public string Street { get; set; }
[Column]
public string City { get; set; }
...
}
From my recent experience of using the repository pattern I think you would benefit from using a generic repository, the now common IRepository of T. That way you wouldn't have to add repository methods like SavePerson(Person person). Instead you would have something like:
IRepository<Person> personRepository = new Repository<Person>();
Person realPerson = new Person();
personRepository.SaveOrUpdate(realPerson);
This method also lends itself well to Test Driven Development and Mocking.
I feel the questions about behavior in your description would be concerns for the Domain, maybe you should have an AddCompany method in your Person class and change the Company property to
public Company Company { get; private set; }
My point is; model the domain without worrying about the how data will be persisted to the database. This is a concern for the service that will be using your domain model.
Back to the Repository, have a look at this post for good explanation of IRepository over LinqToSql. Mike's blog has many other posts on Repositories. When you do come to choose an ORM I can recommend HHibernate over LinqToSql, the latter is now defunct and NHibernate has a great support community.