Repository pattern and Business logic - repository

I have a repository (CustomerRepository) that retrieves data from the data layer. Most of the business logic is in the entity class (Customer) that the repository either accepts or returns.
However, where do you put the global entity business logic (that applies to all customers)?
For instance, I may not want to return all customers to certain users. I don't want to put that logic in the repository.

I agree with Robert Munteanu.
Basically you roll up your business logic that isn't inherent in your model into a middle tier. The middle tier is the business tier / business objects / business logic layer / etc, but is just referred to as a service tier. It doesn't have to be a webservice, its a broad use of the term service in that it aggregates functionality of a specific application area.
You would basically have a CustomerService class that contains the repository reference. Your presentation layer would reference the service layer class.
There is an additional distinction that can be made as a guess from your name you are using .net, and probably using LINQ to SQL as your repository as outlined in NerdDinner.
The Repository typically returns IQueryable to the service layer, allowing the service layer chain together multiple queries to build different result sets. The Service then evaluates the expression using ToList or another similar method and returns that to the presentation layer.

Put it in another repository (BusinessRuleRepository) and have CustomerRepository use it.
OR
If the business logic is only limiting the results a user can see you might want to use a Facade pattern with a factory. In this case you would have an ICustomerRepository that handles your CustomerRepository and LimitedCustomerRepository (which might encapsulate CustomerRepository), and a CustomerRepositoryFactory that returns the appropriate ICustomerRepository for the user.

Wrap it behind a service.

I think separating these types of functions into a service layer is the way to go.
I recently built a system to do complex forecasting with many entities using historical data. Putting all the data access bits in the repository for each entity. The intricate forecasting logic I kept in a service layer and passed the repository objects in as needed.
Added bonus was that I had an easy way to expose all the forecasting logic to external systems by simply creating a web api layer.

Related

Usage of data entities to exchange between client and microservices (asp.core)

Usually i create dto's to get data from microservice (WebApi) to client (MVC).
But sometimes it's cumbersome to duplicate structure of data entity to dto, especially if entity has multiple fields and many embedded relationships.
So i have to duplicate fields and relations.
Can i use data entity instead of dto?
I use a special assembly for dto's to be exchanged between client (MVC) and given microservice. Should my data entities live in this assembly?
This is a common complaint that derives from not understanding the concept of bounded contexts. Because you're deep in the code, you just see two things that look like the same thing, and you have had, like all developers, the idea beaten into your brain that you should not repeat yourself (DRY).
However, the key word above is that the two things look the same. They are in fact not the same, and that is the critical salient point. They are representations of domain objects from different contexts (data store and application layer, for example). If you use the same object, you are tightly coupling those contexts to the point where they're now inseparable. As such, the very concept of having multiple layers becomes moot.
A related concept here is anti-corruption layers. This is a layer you add to your application to facilitate communication between two different application contexts or domains. An API is a form of anti-corruption layer. Again, because you're building all the apps, it seems like they're all the same thing. However, imagine your MVC app as a third-party application being built by someone else to consume your API. Should they use your entities directly? No. They probably would have their own entity classes and their own data store. The DTO your API uses provides a way for these two different applications to communicate via a common language. If you use your entity classes directly, then any change to your data, necessitates a change to your API, which in turn necessitates a change to any consumers of your API. Imagine if Google changed a database column, and because of that, every single developer using their API(s) had to immediately make changes to their own applications or they would break.
In short, just because two classes look the same, doesn't mean they are the same. Your entity and your DTO are each representations of a concept in different contexts, and therefore you need and should have both.

WCF Message & Data Contract, DTO, domain model, and shared assemblies

I have a web client that calls my WCF business service layer, which in turn, calls external WCF services to get the actual data. Initially, I thought I would use DTOs and have separate business entities in the different layers... but I'm finding that the trivial examples advocating for DTOs, to be, well, trivial. I see too much duplicate code and not much benefit.
Consider my Domain:
Example Domain
I have a single UI screen (Asp.net MVC View) that shows a patient's list of medications, the adverse reactions (between medications), and any clinical conditions (like depression or hypertension) the patient may have. My domain model starts at the top level with:
MedicationRecord
List<MedicationProfile> MedicationProfiles
List<AdverseReactions> Reactions
List<ClinicalConditions> ClinicalConditions
MedicationProfile is itself a complex object
string Name
decimal Dosage
Practitioner prescriber
Practioner is itself a complex object
string FirstName
string LastName
PractionerType PractionerType
PractionerId Id
Address Address
etc.
Further, when making the WCF requests, we have a request/response object, e.g.
MedicationRecordResponse
MedicationRecord MedicationRecord
List<ClientMessage> Messages
QueryStatus Status
and again, these other objects are complex objects
(and further, complicates matter is that they exist in a different, common shared namespace)
At this point, my inclination is that the MedicationRecordResponse is my DTO. But in pure DataContracts and DTO and separation of design, am I suppose to do this?
MedicationRecordResponseDto
MedicationRecordDto
List<ClientMessageDto>
QueryStatusDto
and that would mean I then need to do
MedicationProfileDto
PractitionerDto
PractitionerTypeDto
AddressDto
etc.
Because I have show almost all the information on the screen, I am effectively creating 1 DTO for each domain object I have.
My question is -- what would you do? Would you go ahead and create all these DTOs? Or would you just share your domain model in a separate assembly?
Here's some reading from other questions that seemed relevant:
WCF contract know the domain
Alternatives for Translation Layer in SOA: WCF
SOA Question: Exposing Entities
Take a look on excellent articles
Why You Shouldn’t Expose Your Entities Through Your Services
DTO’s Should Transfer Data, Not Entities
above links don't work, looks like a domain issue (I hope it'll be fix), here is the source:
DTO’s Should Transfer Data, Not Entities
Why You Shouldn’t Expose Your Entities Through Your Services
I've always had an aversion to the duplicate class hierarchy resulting from DTOs. It seems to be a flagrant violation of the DRY principle. However, upon closer examination, the DTO and the corresponding entity or entities serve different roles. If you are indeed applying domain-driven design then your domain entities consist of not only data but behavior. By contrast, DTOs only carry data and serve as an adapter between your domain and WCF. All of this makes even more sense in the context of a hexagonal architecture also called ports and adapters as well as the onion architecture. Your domain is at the core and WCF is a port which exposes your domain externally. A DTO is part of how WCF functions and if you agree that it is a necessary evil your problem shifts from attempting to eliminate them to embracing them and instead focusing on how to facilitate the mapping between DTOs and domain objects. A popular solution is AutoMapper which reduces the amount of boiler plate mapping code you need to write. Aside from the drawbacks, DTOs also bring a lot of benefits. One is that they furnish a buffer between your domain entities and the outside world. This can be of great help in refactoring because you can keep your core domain very well encapsulated. Another benefit is that you can design your DTOs such that they fulfill requirements of the service consumer, requirements which may not always be in full alignment with the shape of your domain objects.
Personally, I don’t like using MessageContract as entities. Unfortunately, I have an existing WCF service that use MessageContract as entities – i.e. data is filled into the MessageContract directly in the data access layer. There is no translation layer involved.
I have an existing C# console application client using this service. Now, I have a new requirement. I need to add a new field in the entity. This is not needed by the client. The new field is only for the internal calculations in the service. I had to add a new property named “LDAPUserID” in the MessageContract which also act as a entity.
This may or may not break the client depending on whether the client support Lax Versioning. Refer Service Versioning.
It is easy to mistakenly believe that adding a new member will not break existing clients. If you are unsure that all clients can handle lax versioning, the recommendation is to use the strict versioning guidelines and treat data contracts as immutable.
With this experience, I believe it is not good to use MessageContract as entities.
Also, refer MSDN - Service Layer Guidelines
Design transformation objects that translate between business entities and data contracts.
References:
How do I serialize all properties of an NHibernate-mapped object?
Expose object from class library using WCF
Serialize subset of properties only

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.

Repository, Service or Domain object - where does logic belong?

Take this simple, contrived example:
UserRepository.GetAllUsers();
UserRepository.GetUserById();
Inevitably, I will have more complex "queries", such as:
//returns users where active=true, deleted=false, and confirmed = true
GetActiveUsers();
I'm having trouble determining where the responsibility of the repository ends. GetActiveUsers() represents a simple "query". Does it belong in the repository?
How about something that involves a bit of logic, such as:
//activate the user, set the activationCode to "used", etc.
ActivateUser(string activationCode);
Repositories are responsible for the application-specific handling of sets of objects. This naturally covers queries as well as set modifications (insert/delete).
ActivateUser operates on a single object. That object needs to be retrieved, then modified. The repository is responsible for retrieving the object from the set; another class would be responsible for invoking the query and using the object.
These are all excellent questions to be asking. Being able to determine which of these you should use comes down to your experience and the problem you are working on.
I would suggest reading a book such as Fowler's patterns of enterprise architecture. In this book he discusses the patterns you mention. Most importantly though he assigns each pattern a responsibility. For instance domain logic can be put in either the Service or Domain layers. There are pros and cons associated with each.
If I decide to use a Service layer I assign the layer the role of handling Transactions and Authorization. I like to keep it 'thin' and have no domain logic in there. It becomes an API for my application. I keep all business logic with the domain objects. This includes algorithms and validation for the object. The repository retrieves and persists the domain objects. This may be a one to one mapping between database columns and domain properties for simple systems.
I think GetAtcitveUsers is ok for the Repository. You wouldnt want to retrieve all users from the database and figure out which ones are active in the application as this would lead to poor performance. If ActivateUser has business logic as you suggest, then that logic belongs in the domain object. Persisting the change is the responsibility of the Repository layer.
Hope this helps.
When building DDD projects I like to differentiate two responsibilities: a Repository and a Finder.
A Repository is responsible for storing aggregate roots and for retrieving them, but only for usage in command processing. By command processing I meant executing any action a user invoked.
A Finder is responsible for querying domain objects for purposes of UI, like grid views and details views.
I don't consider finders to be a part of domain model. The particular IXxxFinder interfaces are placed in presentation layer, not in the domain layer. Implementation of both IXxxRepository and IXxxFinder are placed in data access layer, possibly even in the same class.

How should business level objects be named?

We are building a service-oriented system where we have separated the application into several layers:
SOAP web services (e.g., BuildingService.asmx)
Business logic layer (e.g., BuildingXXX)
Data Access layer (e.g, BuildingProvider)
Types (e.g., Building)
The SOAP web services simply instantiate an object of type BuildingXXX from the business logic layer in order to keep the implementation out of the SOAP web services. BuildingXXX then uses the BuildingProvider from the data access layer to return types defined in the data transfer object layer.
We have been unable to determine what we should call the objects in the business logic layer.
What is the "standard" naming convention for naming these business level entities?
Personally, I would call your business logic layer services "BuildingService" then call the web services "BuildingWebService".
Or you could always go with the generic "BuildingManager" as well for the service layer..
Namespaces are your friends. How about BusinessLayer.Building, BusinessLayer.Facility? Use DataLayer.Building, DataLayer.Facility, etc. You get to call things what they are, yet they get to be different things.
I would naively go with BuildingRules (since this is what they are, right?) but then I don't actually know what are the conventions...
i prefer prefixes instead of suffixes, so that the related layers sort together, e.g.
BizRuleBuilding,
BizRuleFacility,
...