What's the difference between a Controller and a Service? - oop

I'm looking for how to structure the layer of my app between the presentation layer and the model / business object layer. I see examples using Controller classes and others using Service classes. Are these the same things with different names for different methodologies, or is there a more fundamental difference?
Edit:
To put the question in context, this is a PHP app using Doctrine as the ORM.

I would say terms like Controller are basically same names for potentially very different things depending on what methodology / framework you are using. At a very high level, they may perform the same action - hence the generic name usage - but their responsibilities and scope within the context of the framework will usually be much more specific and different.
Eg: The Controller in MVC has little or nothing in common with the Controller layer in WCSF.
I think these terms like Controller / Service etc are generic and hence have been used in many frameworks but they have a special meaning within the framework of reference.
Also, specifically, a controller and a service to me are two completely differing concepts.
Controller is something like a layer that is responsible for orchestrating logic within the application / or an aspect of the application
Service , to me, is basically the external API through which you expose aspects of your application in a standard manner

Related

Implementing localization in DDD pattern - Infrastructure/Persistance Layer?

I'm working on a Blogging platform in .NET Core and one of the key requirements is to have different translations based on the user's selected language. It's clear to me that majority of this part belongs to the UI layer, but I want to let bloggers submit different translations of their posts by themselves.
So far I modified my Domain that it now contains the Language property and I also created Localized attribute to mark properties that are multilingual. In my approach I want to keep all localization-related logic in the Infrastructure layer so it saves/loads proper translations to/from another table containing translations for Localized properties automatically without the Application layer (or services) knowing about it.
I'm also implementing UnitOfWork pattern and normally I would use repositories through it, like in a following way: UnitOfWork.BlogPosts.Add(post) and after all operations are done: UnitOfWork.CommitChanges(), but I assume that now UnitOfWork would contain both repositories: for BlogPost and for Localization and the whole logic of saving/loading localized data would need to be implemented in a UnitOfWork so instead I would have to call a method that manages both repositories, like this: UnitOfWork.AddBlogPost(post) (also IUnitOfWork interface would require these methods).
So my question is: is it a good design appraoch and is UnitOfWork a proper place to implement such logic? I want to keep it as automated as possible and if it doesn't cause any issues that I'm currently not aware of - to keep it directly in a persistance layer.
Edit: My second idea would be to simply keep the two repositories in UnitOfWork and implement saving/loading BlogPost + Localization in an Application layer (in commands handlers and queries using CQRS pattern). But unfortunately this way I would have to implement the same logic for saving/loading for every command and query...

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.

Re-using MVC4 components in WebAPI

I have a sizable investment in an MVC4 site that has a large array of custom model binders, value providers etc.
I now want to add some WebAPI controllers to the site and re-use some of the MVC4 components. It appears that there are many parallel concepts in MVC and WebAPI (e.g. model binding), but the base classes and interfaces live in separate namespaces, meaning the types are not interchangeable.
Is there an established pattern for adapting MVC classes to their WebAPI equivalents? Specifically I'm interested in being able to reuse a System.Web.Mvc.IModelBinder as a System.Web.Http.ModelBinding.IModelBinder.
The problem are not the interfaces but the fact that the model binding rules used by the two model binders are completely different and based on different concepts. That's why the interfaces are defined in two different namespaces otherwise they would have used exactly the same interface. There is a parallelism between the two interfaces but they represent two different concepts. In other words the syntax is similar but the semantic is different so you cannot have a one to one mapping among 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.

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

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.