Making OR/M loosely coupled and abstracted away from other layers - nhibernate

In an n-tier architecture, the best place to put an object-relational mapping (OR/M) code is in the data access layer. For example, database queries and updates can be delegated to a tool like NHibernate.
Yet, I'd like to keep all references to NHibernate within the data access layer and abstract dependencies away from the layers below or above it. That way, I can swap or plug in another OR/M tool (e.g. Entity Framework) or some approach (e.g. plain vanilla stored procedure calls, mock objects) without causing compile-time errors or a major overhaul of the entire application. Testability is an added bonus.
Could someone please suggest a wrapper (i.e. an interface or base class) or approach that would keep OR/M loosely coupled and contained in 1 layer? Or point me to resources that would help?
Thanks.

It sounds like you are looking for the repository pattern. If you need more decoupling, you can inject the data dependencies with an Inversion of Control container.

Service Facade Pattern is one name. Simple contracts between business logic and data layer.
Service classes or beans (call it what you want) define and implement the contract, and orchestrate the lower data layer, often handling the transactional logic across data objects.
In Spring, you define an Interface, and then implement it. One implementation might be an OR/M, another might be raw JDBC or ADO.NET. In some frameworks, Aspect Oriented Programming allows you to inject declarative transactional logic without writing any code. It saves a lot of headache.
One caveat: When dealing with some OR/Ms like Hibernate, there is the use of proxy classes. This does pollute things, because there are a few instances where the proxy classes cause problems. In my opinion, that is an implemtation detail that should not escape the service layer. But with Hibernate, it does. Not sure about the .NET implementation.

Related

Are fromXYZ methods inside entities an antipattern?

I am developing a Symfony-Application but I guess my question is mostly independent of
framework-usage.
This is the situation:
I got a very lightweight entity that is actually not even managed by the ORM as it is just used to aggregate and communicate information of another entity.
I read that we should keep business-logic out of the model but I also thought that it would
proof quite useful to me if I had a fromXYZ-method in my lightweight-entity to create a SPOC for instanciation based off of the "big entity".
But technically this from-method performs logic which contradicts what I read to be good practice.
So would this be an antipattern? How would I resolve this in a more suitable way, if yes?
What are you talking about is static factory method. It's pretty ok to use it, but it shouldn't do anything fancy because it will be hard to test your code since you can't mock it.
If you feel that your method won't create any problems in testing, you can create it without any doubt. Otherwise, you can encapsulate your creation logic in a separate factory.
Your "lightweight entity" could be referred to as a DTO.
One way to keep the terminology straight.
Entities are managed by the ORM.
DTOs are unmanaged. Often used to convey a subset or aggregation of entities.
Constructing one object from another by copying its fields is not something I would consider business logic, unless there are complex transformations prescribed by business requirements.
The real problem with fromXYZ methods is that they implement a dependency on XYZ. You have to be careful about which direction such dependencies are pointing. For example, if you construct a DTO by passing it an Entity, that DTO now has a dependency on the persistence layer of your application. If you then use that DTO in a service, your service layer now has a (transitive) dependency on your persistence layer. This is referred to as tight coupling.
One way to keep business logic decoupled from persistence, view, etc., is to point dependencies in the other direction: into the services rather than out of them.

DDD: Where to put persistence logic, and when to use ORM mapping

We are taking a long, hard look at our (Java) web application patterns. In the past, we've suffered from an overly anaemic object model and overly procedural separation between controllers, services and DAOs, with simple value objects (basically just bags of data) travelling between them. We've used declarative (XML) managed ORM (Hibernate) for persistence. All entity management has taken place in DAOs.
In trying to move to a richer domain model, we find ourselves struggling with how best to design the persistence layer. I've spent a lot of time reading and thinking about Domain Driven Design patterns. However, I'd like some advice.
First, the things I'm more confident about:
We'll have "thin" controllers at the front that deal only with HTTP and HTML - processing forms, validation, UI logic.
We'll have a layer of stateless business logic services that implements common algorithms or logic, unaware of the UI, but very much aware of (and delegating to) the domain model.
We'll have a richer domain model which contains state, relationships, and logic inherent to the objects in that domain model.
The question comes around persistence. Previously, our services would be injected (via Spring) with DAOs, and would use DAO methods like find() and save() to perform persistence. However, a richer domain model would seem to imply that objects should know how to save and delete themselves, and perhaps that higher level services should know how to locate (query for) domain objects.
Here, a few questions and uncertainties arise:
Do we want to inject DAOs into domain objects, so that they can do "this.someDao.save(this)" in a save() method? This is a little awkward since domain objects are not singletons, so we'll need factories or post-construction setting of DAOs. When loading entities from a database, this gets messy. I know Spring AOP can be used for this, but I couldn't get it to work (using Play! framework, another line of experimentation) and it seems quite messy and magical.
Do we instead keep DAOs (repositories?) completely separate, on par with stateless business logic services? This can make some sense, but it means that if "save" or "delete" are inherent operations of a domain object, the domain object can't express those.
Do we just dispense with DAOs entirely and use JPA to let entities manage themselves.
Herein lies the next subtlety: It's quite convenient to map entities using JPA. The Play! framework gives us a nice entity base class, too, with operations like save() and delete(). However, this means that our domain model entities are quite closely tied to the database structure, and we are passing objects around with a large amount of persistence logic, perhaps all the way up to the view layer. If nothing else, this will make the domain model less re-usable in other contexts.
If we want to avoid this, then we'd need some kind of mapping DAO - either using simple JDBC (or at least Spring's JdbcTemplate), or using a parallel hierarchy of database entities and "business" entities, with DAOs forever copying information from one hierarchy to another.
What is the appropriate design choice here?
Martin
Your questions and doubts ring an interesting alarm here, I think you went a bit too far in your interpretation of a "rich domain model". Richness doesn't go as far as implying that persistence logic must be handled by the domain objects, in other words, no, they shouldn't know how to save and delete themselves (at least not explicitely, though Hibernate actually adds some persistence logic transparently). This is often referred to as persistence ignorance.
I suggest that you keep the existing DAO injection system (a nice thing to have for unit testing) and leave the persistence layer as is while trying to move some business logic to your entities where it's fit. A good starting point to do that is to identify Aggregates and establish your Aggregate Roots. They'll often contain more business logic than the other entities.
However, this is not to say domain objects should contain all logic (especially not logic needed by many other objects across the application, which often belongs in Services).
I am not a Java expert, but I use NHibernate in my .NET code so my experience should be directly translatable to the Java world.
When using ORM (like Hibernate you mentioned) to build Domain-Driven Design application, one of good (I won't say best) practices is to create so-called application services between the UI and the Domain. They are similar to stateless business objects you mentioned, but should contain almost no logic. They should look like this:
public void SayHello(int id, String helloString)
{
SomeDomainObject target = domainObjectRepository.findById(id); //This uses Hibernate to load the object.
target.sayHello(helloString); //There is a single domain object method invocation per application service method.
domainObjectRepository.Save(target); //This one is optional. Hibernate should already know that this object needs saving because it tracks changes.
}
Any changes to objects contained by DomainObject (also adding objects to collections) will be handled by Hibernate.
You will also need some kind of AOP to intercept application service method invocations and create Hibernate's session before the method executes and save changes after method finishes with no exceptions.
There is a really good sample how to do DDD in Java here. It is based on the sample problem from Eric Evans' 'Blue Book'. The application logic class sample code is here.

Is the idea to hookup all business logic classes in my WinForms app via IOC? Or if not is there a guidance re which classes to use IOC on?

Getting going now with NInject... :)
For a WinForms application, and in particular the business logic classes used within it, is there a rule of thumb in terms of which Classes once should hook up using IOC? For example if you have a Domain Model which is modelled by C# classes is the concept that all classes should be wired together using IOC?
IOC/DI allows you to design loosely coupled systems and manage your dependencies smartly and flexibly. This means that you can use these concepts anywhere including the presentation layer e.g. PRISM. That being said, you don't have to apply them to each and every class. For example, some classes provide basic building block type functionality such as string class in .NET that it is ok to take a dependency on the concrete implementation. Otherwise, you will end with an overly complex looking code that may go against keep it simple principle. Ask yourself if you want to test your classes and how hard it is to write a unit test. If the code and the dependencies are getting in the way of easily and quickly producing unit tests, then you might want to invert those dependencies to be in charge of controlling them.

What exactly is "persistence ignorance"?

Persistence ignorance is typically defined as the ability to persist & retrieve standard .NET objects (or POCOs if you really insist on giving them a name). And a seemingly well accepted definition of a standard .NET object is:
"...ordinary classes where you focus on the business problem at hand without adding stuff for infrastructure-related reasons..."
However, I see people describing NHibernate as a framework that allows persistence ignorance, and yet it is a framework that cannot work on any standard .NET object, only standard .NET objects that adhere to particular design requirements, for example (source):
All classes must have a default constructor
Some features don't work unless classes are unsealed and all members are virtual
Object identity doesn't work properly unless you abuse Equals/GetHashCode
(Aside: Before anybody gets upset, I don't mean to pick on NHibernate here, it's just a frequently quoted example of a framework that supposedly permits persistence ignorance. I'm sure similar arguments could be applied to other ORMs that claim the same.)
Now although the class in itself does not have any persistence-framework-specific attributes or base classes etc., to me it is not really "persistence ignorant" because it must follow a set of design guidelines to facilitate use by the chosen persistence framework. You must design and implement the class with the requirements of the persistence framework in mind; if you are ignorant of it the class may not work with it.
Where I'm having trouble with the definition of "persistence ignorance"/"POCO" is that I don't see how, conceptually, this is really any different to adding attributes such as [Serializable] or [DataContract] or [XmlType] or any other persistence-framework-specific annotations that facilitate the persistence and retrieval of the entity using that framework.
So, what exactly is "persistence ignorance"?
Clearly the definition of it as being able to persist "ordinary classes" is a fallacy because the NHibernate ones are only ordinary insofar as not referencing framework-specific classes, whereas they are extraordinary inasmuch as they require unusual design choices such as default constructors and all-virtual members and Equals/GetHashCode implementations on mutable types.
Is it therefore reasonable to say that "persistence ignorance" is true when objects facilitate the use of a persistence framework (either in design and structure or by use of framework-specific annotations) but do not perform any persistence logic themselves?
I would claim that, like most things, its a sliding scale. There are things that we make that want to have the property of persistence. On one end of the scale is this thing having all of the guts, dependencies, and code that is custom built to persist just this one thing in its particular way. On the other end of the scale is something that just magically happens, all without us doing much more than adding a token or setting a property somewhere that causes that thing to 'just persist'. In order to get to the magical side of the scale, there are frameworks, design guidelines, conventions, etc that assist the magic in happening. I think you could argue that a tool could be produced that had fewer requirements and restrictions than NHibernate but pursued the same goal; that hypothetical tool would be further along our scale.
I don't know that I like the term 'persistence ignorance' so much; its really about an object being ignorant of the implementation, the backing store, the cache, that sort of thing - an object is typically aware of whether or not it is persistent, though. But that's just semantics.
I don't believe your understanding (or definition) of "Persistence Ingorance" is wrong.
The real issue is that of leaky abstractions. Quite simply, the existing technology makes it very difficult to implement true PI.
A persistant ignorant class, is a class that is not tied to a persistancy framework.
That is, the class has absolutely no knowledge that there's a persistancy framework present, it does not inherit from a class that is defined by that framework nor does it implement an interface that is required for that persistance framework in order to work.
I agree with Mikeb - "persistance ignorance" is a sliding scale, not a true/false property of a given ORM.
My definition of true 100% PI would be that you could persist ANY possible POCO class, no matter how convoluted and linked to other classes, without otherwise changing the class in any way.
Adding ID fields, decorating with attributes, inheriting from ORM classes, having to design your classes so they map well to the underlying tables in an RDB - all reduce the "PI score" below 100%.
This said, I've chosen to use Fluent NHibernate Automapping because it seems to have the highest PI score of any of the ORM options I've looked at.
I'd agree with your definition:
Is it therefore reasonable to say that
"persistence ignorance" is true when
objects facilitate the use of a
persistence framework, but do not
perform any persistence logic
themselves?
The code (as opposed to atributes) in your classes has no features that are intrinsic to persistence. Default constructors might be needed for persistence, but have no code that actually does persistence. The persistence layer could be changed quite substantially, different databases could be used and the business logic would remain unchanged.
While there may be certain minor constraints that any given persistence-ignorance framework requires, persistence-ignorance nevertheless remains in place.
While a class in your domain model (transparently persisted with NHibernate) must have a no-arguments constructor so that it can be constructed "dynamically," it is not required to have a certain base class dictated by the framework nor is it required to have or override certain framework-specified methods.
In my opinion, "persistence ignorance" is a property of your model (domain model, business model or whatever you might refer to it as). The model is persistence ignorant because it retrieves instances of the entities it contains through abstractions (sometimes referred to as repositories). These abstractions can be implemened by using an ORM directly, but as you state yourself this may sometimes add requirements to the objects that do not naturally belong in your model. Therefore I would not say that a model that adheres to some requirements of a specific ORM is 100% persistence ignorant.
you can implement persisrtence ignorance using a class for the domain or you application and a POCO class in the persistence, when you are going to persist the domain object map it into your persistence class and use the persistence object to store with nhibernate o other framework
your domain class must to ignore how is persisted the information, so you must no include any rules of a persistence framework like (empty constructor, virtual properties etc.)
these persistence framework rules can be in your persistence class.

WCF Object Design - OOP vs SOA

What is the proper way to handle polymorphic business objects in a WCF/SOAP world?
It seems to me that SOA and OOP are at odds with each other - to expose a clean WSDL you need concrete objects, typically not even utilizing inheritance. On the other hand, presumably in the underlying system, you'll want to follow proper OO design.
What do people typically do here? Build a set of WCF contract objects, forgoing OOP principles, then convert to and from another set of objects in the actual logic layers?
What do people typically do here? Build a set of WCF contract objects, forgoing OOP principles, then convert to and from another set of objects in the actual logic layers?
Yes.
The way WCF serializes things ends up putting a lot of limitations on what you can and can't do with the contract objects. What you can't do ends up being "most anything useful".
I've found it makes things much clearer if you think of the WCF-contract objects as just a data transfer mechanism. Basically like strongly/statically typed XML.
Instead of converting your business object to an XML string (and back again), you convert your business object to a WCF-contract object (and back again), but it's otherwise similar
After reading the Thomas Erl library, I came to the following conclusion:
Think of the WCF Contracts/SOAP Message as simply a message that the Services use to communicate (don't tightly tie that to Objects in your code).
You can then use OOP to design a code-base that gracefully handles those messages using common OOP techniques.
You use an abstraction (interface type) annotated with WCF attributes in order to define your Service contract.
This is both depending on abstraction, which is according to OOP, as well as defining a service endpoint, which is SOA.
In general, if you find that you are getting business objects with dependencies, you should consider pulling such dependencies up to the service business layer as opposed to inject dependencies into the business objects.
The service business layer will then act as a mediator acting on both the WCF service proxy as well as the business objects. As opposed to having the business objects acting on the WCF service proxy.
All great comments on this topic! I'll add my vote to the notion of an adapter for mediation between your service orientation and object orientation. I also like Thomas Erl's approach where in his service model he introduces the notion of "application services" and "business services." These are the way to go for your integration points with your specific application/business environment (i.e. your object oriented and component oriented framework/API). This way should result in much better composability and thus capability, for you enterprise framework gurus out there.