Repository design for complex objects? - nhibernate

What is the best way to design repositories for complex objects, assuming use of an ORM such as NHibernate or Entity Framework?
I am creating an app using Entity Framework 4. The app uses complex objects--a Foo object contains a collection of Bar objects in a Foo.Bars property, and so on. In the past, I would have created a FooRepository, and then a BarRepository, and I would inject a reference to the BarRepository into the FooRepository constructor.
When a query is passed to the FooRepository, it would call on the BarRepository as needed to construct the Foo.Bars property for each Foo object. And when a Foo object is passed to the FooRepository for persistence, the repository would call the BarRepository to persist the objects in the Foo.Bars property.
My question is pretty simple: Is that a generally accepted way to set up the repositories? Is there a better approach? Thanks for your help.

In domain-driven design, there is the concept of a "root aggregate" object. The accepted answer to a related question has good information on what it is and how you would use it in your design. I don't know about the Entity Framework but NHibernate does not require the usage pattern you are describing. As long as all the nested objects and their relationships are properly mapped to tables, saving the aggregate root will also save all its child object. The exception is when a nested object has specific business logic that needs to performed as part of its access or persistence. In that case, you would need to pass the "child" repositories so you are not duplicating that business logic.

Repository pattern helps grouping of business transactions among related entities. Meaning if you have two domain objects foo and bar and have a common transactions like GetList(),Update() then a common repository like FoobarReporsitory can be created. You can even abstract that to an interface called IFoobarReporsitory to make application loosely coupled.

Related

Should repositories have update/save/delete methods?

I want to implement Repository design pattern for my project but it's not clear to use CRUD operations in repositories or not. Some resources say you shouldn't use update/save/delete methods because the repository is only for saving objects in memory and you should services for other actions.
Which one is the best way?
Thanks.
A summary of Martin Fowler’s definition of the Repository pattern:
Mediates between the domain and data mapping layers using a collection-like interface for accessing domain objects.
So if we have both add and update methods, I could claim it’s not a collection-like interface, right? I shouldn’t need to bother checking if an object’s already there when adding to a set-like collection.
There are two common approaches about add/update:
Collection-oriented repositories try to mimic an in-memory collection, so you shouldn’t need to re-add an object if it was updated and already in the collection. The repository (or layers hidden below it, such as an ORM) should handle the changes to an entity and track them. You just add an object when you first create it and then no more methods are needed after the entity is changed.
Persistence-oriented repositories are aware that an object needs to be explicitly “saved” after any changes, so you can call the entity.save() method when an object is created or modified.
(Those are my interpretations of the definitions by Vaughn Vernon in Implementing Domain-Driven Design.)
delete is fine, but perhaps remove would be a better name.

What problems does the Abstract Factory design pattern solve?

The intent of the Abstract Factory design pattern is to
"Define an interface for creating families of related or dependent objects
without specifying their concrete classes." [GoF]
This is a short statement of what the design pattern does (solution),
but it isn't clear what particular design problems it solves.
I would define the
following design, refactoring, and test problems,
but I am not sure whether this list is complete.
Design Problems
Creating Objects and Object Families
How can a system support creating different families of objects
so that which family to create can be selected and changed dynamically?
How can a system be configured with a family of objects?
And how can the whole family of objects be exchanged dynamically?
How can the way objects are created (which classes are instantiated)
be changed independently?
How can a system be independent of how its objects are created?
Creating Consistent Object Families
How can be ensured that a system creates objects from only one of different
families at a time?
Refactoring Problems
Distributed Creation Code
How can instantiating concrete classes throughout an application be refactored?
How can creation code that is distributed across many classes be centralized?
Testing Problems
Unit Tests
How can creating objects and object families be designd
so that object creation can be mocked easily for unit testing?
Keeping the long story short - if in the future a new group of objects is introduced in your current OO design, a new factory will be derived from AbstractFactory, encapsulating creation of all concrete objects related to that group. It’s that simple.
As addition is also important to say that
“This pattern defines an interface for creating an object, but let subclasses decide which class to instantiate. Factory Method lets a class defer instantiation to subclasses".
In short we need a class here which will do all the common tasks and expose a virtual or abstract function.
So creating AbstractFactory will encapsulate common functionalities with an additional overridable (virtual or abstract) method and then recreate our SubFactoryA and SubFactoryB. By doing so - you'll achieve common architecture, propagate minimum/default set of practices, standards etc. Here is a very good article about all this.

Instantiation of a composite object with lots of validation rules

I have an object that I would like to create. This object is composed of other objects that I don't want the client class to be responsible for creating. There are lots of validation rules that must pass before the object can be created.
So I would like to abstract away the creation of this complex object into a "factory" class. I have 2 questions really, the first is purely about semantics:-
What should I call the class which is creating my object? The factory method pattern and abstract factory pattern are both related to abstracting away creation of concrete classes of different types. However, I'm creating an object of a single type, so using the term factory might be confusing?
Is this an appropriate solution? Are there any patterns/examples of this being done?
Thanks in advance for any help/guidance.
You can use the term factory because we all use it in its broadest sense unless we use a more unique name like Factory Method design pattern or Abstract Factory design pattern.
Builder pattern is typically used if you have an object build process that should still be used if the same master steps should be used in creating different types of objects. But in your case you just have one type. So there's no need for a better solution since there's no special problem to solve. Just do the validation in the simplest form you can.

Where IdentityMap belongs: UnitOfWork or Repository?

If I implement some simple OR/M tool, where do I put identity map? Obviously, each Repository should have access to its own identity map, so it can register loaded objects (or maybe DataMapper is the one who registers objects in IdentityMap?).
And when I commit unit of work, I also need to access the identity map to see which entity is dirty and which is clean (or I am wrong again and there is some outer object which calls RegisterClean/RegisterDirty methods of my UnitOfWork class? Then what object does this?).
Does this mean that I should implement IdentityMap as a completely independent object which contains inner IdentityMaps for each entity type?
Really confused about how IdentityMap, Repository and UnitOfWork work all together.
With our .NET O/R Mapper, LightSpeed we placed the identity map inside the unit of work class. This has worked very well for us and feels quite natural as it effectively acts as a level 1 cache for querying purposes during the unit of work's life.
Generally, inject or somehow provide a UoW for your Repository class so that you have an effective scope and gateway to querying.
I hope that helps.

Where should I be creating the entity objects?

I have an entity class and an entity DAO class.
Should it be the responsibility of the DAO class to create instances of the entity class, or should there be an entity creator/manager class that uses the DAO class only to get the data from the database to create the entity class.
Thanks,
Chris
It should be the responsibility of the DAO to load a persistent object from the datastore and returning a transient instance. Why add another layer of abstraction here?
For creating new Entities, a Factory (or Assembler) might be involved. However, usually this is only justified when entity creation is complex enough. A simple constructor fits the bill just fine in most cases.
I usually let the DAO know about the entity assembly and return a fully hydrated entity. Why? Because, usually the DAO only exists to support that entity. If its role is isn't bound to supporting that entity or related entities, then you may want to look at an intermediate layer.
I'm assuming you're talking about a persistent entity and something that manages that persistence. In my opinion, there is no value in using a factory to simply create the POJO. Use conventional means and then use a DAO, an EntityManager, whatever, to deal with the persistence. I think the key point is not to let the persistence strategy/implementation bleed past your business API.