DDD: What are good reasons for you to loosely-couple Entities? - interface

Back in December, there was this post that was answered with "it is ok to use concret types [for simple object]".
But I keep seeing more and more simple entities with interfaces in sample projects, and even the very large Enterprise application I just took control over (counting 89 interfaces and going).
Is it that people are not picking the best approach, and just shotgunning the project with the "my project is loosely-coupled!" approach?
Or, am I missing something. I can unit test with concret types for my IService, IFactory and IRepository implmentations I have (and works quite well). I am also building my first "Anticorruption Layer" for abstracting a lot of these 3rd party tools out away from the main domain. This anticorruption layer has a number of Facades, Translators, and Adapters - all of which are loosely coupled (or planned to be).
So, is there something I missing about Entities having Interfaces?
public interface IContent
{
Int32 ContentID {get; set;}
}
IList<IContent> list = new List();
Edit: I should also mention that that the enterprise app I have that has all of these interfaces, has zero unit tests. lol

It is more important that entities that have responsibility conform to an interface than it is for simple data objects. If you can define the entity in terms of methods, then, yes, you'll benefit from an interface. I can't see that an object that will simply be used as a DTO within the application gains any great advantage by having an interface.
That said, there is certainly benefit from abstracting away "entities" created by a third party tool, or a framework like L2S, in my opinion.

Related

Shared Entities in Clean Architecture

I'm reading into clean architecture and I want to apply it to some software that I wrote. In this software, entities such as User and Group play a very central role. For this reason, it would make sense to share these entities across the code in order to avoid repetition but it is somehow also against the rules of clean architecture.
What is the right decision to be made in this case? Should I just throw in a "shared/entities" folder in core?
The project that I am working on in programmed mainly in flutter, if that's important to the answer.
I know zero about Flutter or Dart (apart from what I just Googled), but it looks like it supports interfaces.
A good approach is not to throw users and groups into a shared folder, but to create some really light-weight representations of them, and throw those into a shared folder / common library. An interface is a great way to do this because in the interface you can specify the important basics that parts of your application need to generically know about, without adding implementation specific baggage and dependencies.
When designing your interfaces, be sure to be aware of principles like SOLID - especially the Interface segregation principle (the I in SOLID).
To elaborate a bit more:
Define IUser interface
Have your User class implement IUser
Have someway of instantiating IUser using your implelentations, like User.
Where your application references User - switch this to use IUser.
Update in response to comment
My usual starting point architecture would be to define DTO's which I share across all layers of the app (UI, Biz Logic / Data Access), basically like what I think you're suggesting. For me, DTO's are as light-weight as possible - basically information carriers. These are shared across all layers, in a common package, as per clean architecture so that different layers of the architecture (e.g. biz logic and data access) are not tightly coupled to each other.
However, users can be bit of a special case in that they can have security / identity / credential related stuff which can become quite specialized and/or implementation & technology specific. This, I suspect, is partly where #duffymo's comment about tight-coupling comes in.
With my answer I'm basically saying that, yes, you can put DTO's into a common folder - and for tricky cases (like Users) you always have the option of defining interfaces on them as well... e.g. the User DTO might have properties which are interfaces rather than concrete properties.
class UserInfo
{
string FirstName { get; set; }
string LastName { get; set; }
ITaxData TaxData { get; set; }
}
I admit it's entirely possibly I'm over-complicating things with the '(some) DTO properties as interfaces' idea.

Domain Driven Design - Shared entities across bounded contexts

I am new to domain driven design and trying to learn and implement in my project. My project structure up till now similar to this.
Maintainance Folder Maintainance.Data(Class
Library) Maintainance.Domain(Class Library)
Maintainance.Domin.Tests(test project)
MovieBooking Folder MovieBooking.Data(Class
Library) MovieBooking.Domain(Class Library)
MovieBooking.Domain.Tests(test project)
SharedKernel Common things
Web Application MovieBooking MVC Web
Application(which have reference to MovieBooking Domain)
In Maintainance boundned context I am keeping all CRUD, GetAll type things for say Movie, Country, Category, Subcategory entities in Maintainance DBContext.
Now in MovieBooking data layer I will also need to use these entities (mostly to display name or dropdown fills in view, kind of subset needed - not all properties needed, only few like Id, name)
There are few ways I can access this entities in Movie booking Bounded Context
Via web services - Need to create web api for common entities like Movie,Country,Category,Subcategory and call web api in web project (to fill Dropdowns or get name from entities)
Via Reference Context (Seperate Dbcontext) - Need to configure Dbset and then map a database view (with only require fields) to Dbset
Example :
modelBuilder.Entity().ToTable(ViewName);
For (1) it can be long term implmentation solution for me
(2) I have to create view (with only few properties) for each require table and it will increase my number of views in my DB drastically as I have enterprise level application.
Is there any other way I can achieve this? Anything I am missing in DDD to look for ?
Option 2, while it will save you time, is actually a very bad idea from the DDD perspective as it allows for violations of the transactional boundary guarantees that each aggregate is meant to enforce\represent.
Option 1 seems a better option, although there are still quite a bit of wiggle room for interpretation based on your brief description of your proposed solution. If I understood correctly, it is generally recommended to follow the below:
Do not expose your aggregate state directly since this exposes internals and increases coupling. Simple create meaningful DTO's and use something like Automapper to map your Aggregates to DTO's easilly and with little effort before sending it over.
Have a duplicate of the DTO definition in your client. This will reduce coupling and allow for easier deployments.
I strongly recommend reading the DDD orange book although I have to say that I cannot recall specifically on which chapter this is discussed. You will also benefit a lot by reading about hexagonal architecture (and I would search for that term in the orange book to find more info about your question).
There is actually one alternative that I can think of: if you're publishing events from your BC's you can create a workflow to translate the domain events to "public" events and then in the other BC listen for the public events that you need to and store the data that you need somewhere inside there. The difficulty of this ranges from very easy to quite problematic depending on your infrastructure. Be aware that it is not a very good idea to re-use your domain events for transmitting data to other BC's since this closely couples the two BC's.
I hope this helps. Please do not hesitate to elaborate if I did not understood the question well enough.

Persistence ignorance and DDD reality

I'm trying to implement fully valid persistence ignorance with little effort. I have many questions though:
The simplest option
It's really straightforward - is it okay to have Entities annotated with Spring Data annotations just like in SOA (but make them really do the logic)? What are the consequences other than having to use persistance annotation in the Entities, which doesn't really follow PI principle? I mean is it really the case with Spring Data - it provides nice repositories which do what repositories in DDD should do. The problem is with Entities themself then...
The harder option
In order to make an Entity unaware of where the data it operates on came from it is natural to inject that data as an interface through constructor. Another advantage is that we always could perform lazy loading - which we have by default in Neo4j graph database for instance. The drawback is that Aggregates (which compose of Entities) will be totally aware of all data even if they don't use them - possibly it could led to debugging difficulties as data is totally exposed (DAO's would be hierarchical just like Aggregates). This would also force us to use some adapters for the repositories as they doesn't store real Entities anymore... And any translation is ugly... Another thing is that we cannot instantiate an Entity without such DAO - though there could be in-memory implementations in domain... again, more layers. Some say that injecting DAOs does break PI too.
The hardest option
The Entity could be wrapped around a lazy-loader which decides where data should come from. It could be both in-memory and in-database, and it could handle any operations which need transactions and so on. Complex layer though, but might be generic to some extent perhaps...? Have a read about it here
Do you know any other solution? Or maybe I'm missing something in mentioned ones. Please share your thoughts!
I achieve persistence ignorance (almost) for free, as a side effect of proper domain modeling.
In particular:
if you correctly define each context's boundary, you will obtain small entities without any need for lazy loading (that, actually becomes an antipattern/code smell in a DDD project)
if you can't simply use SQL into your repository, map a set of DTO to your db schema, and use them into factories to initialize entity classes.
In DDD projects, persistence ignorance is relevant for the domain model itself, not for repositories, factories and other applicative code. Indeed you are very unlikely to change the ORM and/or the DB in the future.
The only (but very strong) rational behind persistence ignorance of the domain model is separation of concerns: in the domain model you should express business invariants only! Persistence is an infrastructural concern!
For example without persistence ignorance (and with lazy loading) the domain model should handle possible exceptions from the db, it's complexity grows and business rules are buried under technological details.
Personally I find it near impossible to achieve a clean domain model when trying to use the same entities as the ORM.
My solution is to model my domain entities as I see fit and ensure that any ORM entities don't leak outside of the repositories. This means that my repositories accept and return domain entities.
This means you lose "most of your ORM goodness" and end up "using your ORM for simple CRUD operations".
Both of these trade-offs are fine for me, I would rather have a clean domain model that I can use, rather than one polluted with artefacts from my DB or ORM. It also cuts down the amount of time I spend "wrestling with my ORM" to zero.
As a side-note, I find document databases a much better fit for DDD.
Once you will provide persistence mapping in you domain model:
your code depends on framework. If you decided to change this framework, you want to change persistence layer and model layer source code - more work, more changes, more merging of code etc.
your domain model jar file depends on spring/nhibernate jars etc.
your classes become larger and larger how business code and persistence related code grows
I've to admit that I dont understand harder and hardest option.
We used separated interfaces and implementations for domain entities. Provide separated mapping files using Hibernate along with repositories.
Entities are created using factory (or repository later), identifier is generated within persistence layer, entity does not need it until it's being persisted.
Lazy loading is provided by special implementation of List once:
mapping of an entity contains it
entity/aggregate is fetched from persistence layer
The only issue is related to transaction as when you use lazy-loaded collection out of transaction scope, it fails.
I would follow the simplest option unless I ran into a stone wall. There are also pitfalls such as this when you adopt pi principle.
Somtimes some compromises are acceptable.
public class Order {
private String status;//my orm does not support enum
public Status status() {
return Status.of(this.status);
}
public is(Status status) {
return status() == status;//use status() instead of getStatus() in domain model
}
}

ORM Entities vs. Domain Entities under Entity Framework 6.0

I stumbled upon the following two articles First and Second in which the author states in summary that ORM Entities and Domain Entities shouldn't be mixed up.
I face exactly this problem at the moment as I code with EF 6.0 using the Code First approach. I use the POCO classes as entities in the EF as well as my domain/business objects. But I find myself frequently in the situation where I define a property as public or a navigation property as virtual only because the EF Framework forces me to do so.
I don't know what to take as the bottom line of the two articles? Should I really create for example a CustomerEF class for the entity framework and a CustomerD for my domain. Then create a repository which consumes CustomerD maps it to CustomerEF do some queries and than maps back the received CustomerEF to CustomerD. I thought EF is all about mapping my domain entities to the data.
So please give me some advice. Do I overlook an important thing the EF is able to provide me with? Or is this a problem which can not completely solved by the EF? In the latter case what is a good way to manage this problem?
I agree with the general idea of these posts. An ORM class model is part of a data access layer first and foremost (even if it consists of so-called POCOs). If any conflict of interests arises between persistence and business logic (or any other concern), decisions should always be made in favor of persistence.
However, as software developers we always have to balance between purism and pragmatism. Whether or not to use the persistence model as a domain model depends on a number of factors:
The size/coherence of the development team. When the whole team knows that properties can be public just because of ORM requirements, but should not be set all over the place, it may not be a big deal. If everybody knows (and obeys) that an ID property is not to be used in business logic, having IDs may not be a big deal. A scattered, unexperienced or undisciplined team may need more stringent segregation of code.
The overlap between business logic concerns and persistence concerns. Object oriented design thrives when a class model sticks to SOLID principles. But these principles are not necessarily at odds with persistence concerns. I mean that although the concerns are different, in the end their resultant requirements may be quite similar. For instance, both concerns may require valid object state and correct associations.
There can be use cases, however, in which objects temporarily need to be in a state that absolutely shouldn't be stored. This may be a reason to work with dedicated domain classes. Another reason may be that the entity model just can't fulfill the best segmentation of responsibilities. For instance, a business process "blacklisting customer" may require data that is scattered over so many entity objects that new domain classes must be designed that can encapsulate the data and the methods working on them. In other words: doing this by entities would violate the Tell Don't Ask principle.
The need for layering. For instance, if the data access layer targets different database vendors it may have to consist of interchangeable parts that are vendor-specific (e.g. to account for subtle differences in data types between Oracle and Sql Server or to exploit vendor-specific features). Using the persistence model as domain model would probably bleed vendor-specific implementations into the business logic. That would be really bad. There the data access layer should be precisely that, a layer.
(Very trivial) The amount of data. Creating objects takes time and resources. When "many" objects are involved in a business case it may just be too expensive to build both entity objects and domain objects.
And more, undoubtedly.
So I would always try to be a pragmatist. If entity classes do a decent job, go for it. If the mismatch is too large, create a business domain for appropriate parts of the business logic. I would not slavishly follow a (any) design pattern just because it is a good pattern. Contrary to what is said in the post, it requires a lot of maintenance to map an entity model onto a business model. When you find yourself creating myriads of business classes that are almost identical to entity classes it's time to rethink what you're doing.

Does the DataMapper pattern break MVC?

I have been reading up on multiple PHP frameworks, especially the Zend Framework but I am getting confused about the proper way to go forward.
Zend Framework does not use ActiveRecords but instead uses the Table Data Gateway and Row Data Gateway pattern, and uses a DataMapper to map the contents of the Row Data Gateway to the model, because ActiveRecord breaks down when your models don't have a 1:1 mapping to your database tables. There is an example of this in the Zend Quickstart guide.
To me, their example looks very bloated with a ton of getters and setters all over the place. I came across various blog posts about Domain Driven Design arguing that using so many getters and setters is bad practice because it exposes all the inner model data to the outside, so it has no advantage over public attributes. Here is one example.
My question: If you remove those getters and setters, how will you render your views? At some point the data has to hit the view so you can actually show something to the user. Following the DDD advice seems to break the separation between M and V in MVC. Following the MVC and Zend example seems to break DDD and leaves me typing up a whole lot of getters, setters and DataMappers for all my models. Aside from being a lot of work it also seems to violate DRY.
I would really appreciate some (links to) good examples or more information about how it all fits together. I'm trying to improve my achitecture and design skills here.
Using Value Objects, you can eliminate some of those public setter methods. Here's a description of the difference between Entity and Value Objects. Value Objects are immutable and often tied to an Entity. If you pass all values in with the constructor, you don't need to set these properties from external code.
Something extra, not directly related to an answer, but more focused on DDD:
(Disclaimer: The only thing I know about the Zend Framework is what I read in the linked article.) The Zend Framework is using DataMappers instead of Repositories. Is this really DDD-ish? Well, Fowler's interpretation of a Repository might say no. However, Eric Evans states that a DDD Repository can be very simple. At its simplest, a Repository is a DataMapper (See DDD book). For something more complex and still DDD, see the Fowler article. DDD has a conceptual Repository that may differ from the pattern definition.
I urge you to continue reading about Domain-Driven Design. I think there's a flaw in the assumption that getters and setters violate DDD. DDD is about focusing on the domain model and best practices to accomplish that. Accessors are just a minor detail.
You don't need to implement all the getters/setters, you can use__get() and __set(). What's the problem then?
From my reading of the post, the question is more philosophical rather than practical.
I don't have the time to write in depth, but here is my two cents. While I agree that you want to limit the number of get and set requests because a class should hide its internals, you also need to take into account the Java and PHP are different tools and have different purposes. In the web environment your classes are being built and taken down with each request and therefore the code you write should not depend on huge classes. In the article you pointed out the author suggests placing the view logic in the class. This probably does not makes sense on the web since I will likely want to present the view in multiple formats (rss, html, etc...). Using accessor methods (get & set) therefore is a necessary evil. You still want to use them thoughtfully so that you don't shoot yourself in the foot. The key is to try to have your classes do the work for you instead of trying to force them to do work externally. By accessing your properties with a method instead of directly you hide the internals which is what you want.
Again, this post could use some examples, but I don't have the time right now.
Can someone else provide a few examples of why accessor methods aren't evil?
There are two approaches here: What I call the "tell don't ask approach", and the other is the ViewModel/DTO approach.
Essentially the questions revolves around what is the "model" in your view.
Tell don't ask requires that the only way an object can be externalized, is from the the object itself. In other words, to render an object, you would have a render method, but that render method would need to talk to an interface.
Something like this:
class DomainObject {
....
public function render(DomainObjectRenderer $renderer) {
return $renderer->renderDomainObject(array $thegorydetails);
}
}
In the context of Zend Framework, you can subclass Zend_View and have your subclass implement this interface.
I've done this before, but its a bit unwieldy.
The second option is convert your domain model in to a ViewModel object, which is like a simplified, flattened out, "stringed out" view of your data, customized for each specific view (with one ViewModel per view), and on the way back, convert the POST data to an EditModel.
This is a very popular pattern in the ASP.NET MVC world, but its also similar to the class "DTO" pattern used to transfer data between "layers" in an application. You would need to create mappers to do the dirty work for you (not unlike a DataMapper, actually). In PHP 5.3, you can use reflection to change private properties, so your DomainObject doesn't even need to expose itself either!
Implementing getters and setters has two advantages, in my eyes:
You can choose which properties to make public, so you don't necessarily have to expose all of the model's internals
If you use an IDE with autocomplete, all the available properties will be a TAB away when you start typing "get" or "set"—this alone is reason enough for me.