Should POCOs be derived from DTOs or better not? - c#

When creating an n-tier solution, I don't want to expose my business objects, but use DTO's instead of this. On the other side, I don't want to doubly define objects and write copy-code all the time.
Now my idea would be to write DTOs that contain all necessary fields and properties, but no logic (only state).
Then I would derive my business objects from those DTOs, extending them with my business logic, working on the DTO base classes properties. These objects also would be the objects persisted in the ORM used (NHibernate).
With that approach, on the server side I could work on the business objects and pass them directly to the client (they are derived, so down-castable). I would not be forced to expose my business logic that way and save a lot of code.
Do you think that approach is sensible?
Regards,
Sebastian

You may want to consider the following:
"...,
because keeping the DTO unaware of the
domain objects enables you to reuse
the DTO in different contexts.
Likewise, you do not want the domain
objects to know about the DTO because
that may mean that changing the DTO
would require changing code in the
domain logic, which would lead to a
maintenance nightmare.
The best solution is to use the Assembler pattern, which creates DTOs from business objects and vice versa. Assembler is a specialized instance of the Mapper pattern also mentioned in Patterns of Enterprise Application Architecture...."
from Pattern and Practice: Data Transfer Object
Also, I have not used it by myself, but you may want to check out AutoMapper as well.

Sounds reasonable to me. In Linq to SQL, business objects are derived from the DTO's by the use of partial classes.

"Then I would derive my business objects from those DTOs" Have in mind that DTOs might look different from BO they might contain properties from 2 or 3 BO

Related

Adding functionality to my Entity Framework POCO classes

I've built a web application with Entity Framework using POCO.
I'm using these POCO classes as my business objects and not just for persisting data which works fine until...
Now I need to add some logic into these classes to do thing like total up sales, order lines, etc.
Should I add methods to my POCO classes to enable this functionality or leave them purely for persisting data and create some kind of 'processor' whereby I pass in the business objects and get the values I require out.
Is there a best practice for this?
What is the architectural design you are using or want to use?
For example, if these are your domain entities, you should put as much as possible logic in them. If they are merely data containers and you don't have a real architecture in place, your logic would probably in some business component.
So if you provide your question with some more details, we can help you better.

Repository Pattern with multiple tables

Recently I have been reading up on using the repository pattern and DI to help create easily testable code, I think I understand it for the most part. However I'm having difficulty with one issue. I need to create a Rules object for my applications business layer. To create a rule, I need the ability to read and write to two tables. How would you go about implementing a repository that uses two tables for one object?
for example:
ICollection<type> GetAllRules();
What would I put in for type as it requires two tables?
Thanks
Steve
I wouldn't insist on having a repository for that.
As Fowler says
Conceptually, a Repository encapsulates the set of objects persisted in a data store and the operations performed over them, providing a more object-oriented view of the persistence layer.
This is probably why most implementations tend to expose pure domain objects rather than derivatives (which your Rule object seems to be).
I would have two repositories for the two tables you mention, then I would have a unit of work to expose all repositories and then I would have a business layer service responsible for the compound processing.
An advantage of such approach would be that the repository layer remains clean, there is no business processing involved here, no unclear rules introduced to the persistence layer.

Sharing content between business objects and DTOs

All,
My typical approach for a medium sized WCF service would be something like:
Define the interface using WCF data contracts and service operations. The data contracts would be POCO DTOs with no CRUD or domain logic.
Model the domain using fully featured business objects.
Provide some mechanism to go from DTO to BO and vice versa (see related question: Pattern/Strategy for creating BOs from DTOs)
Now, a lot of the time (if not always) the data content of the business object and the DTO is near identical. How do people feel about creating a library of content objects which are shared by the BO and the DTO. E.g. if we had a WibbleDTO and a WibbleBO, we could create an IWibbleContent interface which both implement. We could even create an IWibbleContent interface and a WibbleContent class which both the DTO and BO hold a reference to.
So, specific questions:
Do you ever share content/data interfaces between your DTOs and BOs?
Do you ever share data content classes between your DTOs and BOs?
If not then I guess, as per my related question, we're left with tedious copying code, or we use something like AutoMapper.
Any comments appreciated.
We are using quite similar approach as you describe with DTOs and BOs.
We rarely have common interfaces, either they are very basic (eg. interface to get BusinessId) or they are specific for a certain implementation, eg. a calculation which could be made on the client or on the server.
We actually just copy properties. They are usually trivial enough that it is not worth to share code.
At the end, more code is different then similar.
We have many attributes on these classes, which almost never are the same.
Most Properties are implemented as get; set; on the server, but with OnPropertyChangedEvent on the client, which requires the use of explicit fields.
We don't share much code on client and server side. So there is no need for common interfaces.
Even if many of the properties are the same on both classes, there is actually not much to share.
I usually create POCOs and use them through all of my layers - data access to business to ui. In the business layer I have managers that have the POCOs pased back and forth. We are going to look at the Entity Framework and/or NHibernate so I am not sure where that will lead us.
Yeah, we write some extra code but we keep everything lean and mean. We are using MVC for our UI which for me was a godsend compared to the bulk of webforms, I'll never go back. Right now our battle is should we send JSON to the ajax callbacks or use partial views, the latter is what we do most of the time.
Are we correct? Maybe not but it works for us. So many choices, so little time.

Level of separation of database objects in DAL

Looking for some general advice here.
Option 1.
Would it be best to have all of the main database objects (say Contact, User, Customer, etc. have their general classes in DAL with nested classes for db objects that depend on the main objects (ContactAddress, UserEmail, etc... these would have multiple values so they are contained in separate tables).
OR
Option 2.
Would it be better to have completely separate DAL classes for things like ContactAddress, etc. and combine these elements in a business layer?
Let me know if I'm not making sense here.
I usually define my objects in the business logic layer and do some translation between DAL objects and business objects. My DAL objects are usually autogenerated by some ORM framework (such as EF or LinqToSQL). The reason for this is that my business logic layer objects are not POCO's but also contains business logic, whereas the DAL objects are purely poco (although they may be decorated with some ORM logic).
It usually aids in discovery if you put all public classes at the namespace level (instead of as inner classes).
The two examples you cited, could be generalized with no harm:
ContactAddress becomes Address
UserEmail becomes Email
This way, you can reuse them later if you wish.

Plain Old CLR Object vs Data Transfer Object

POCO = Plain Old CLR (or better: Class) Object
DTO = Data Transfer Object
In this post there is a difference, but frankly most of the blogs I read describe POCO in the way DTO is defined: DTOs are simple data containers used for moving data between the layers of an application.
Are POCO and DTO the same thing?
A POCO follows the rules of OOP. It should (but doesn't have to) have state and behavior. POCO comes from POJO, coined by Martin Fowler [anecdote here]. He used the term POJO as a way to make it more sexy to reject the framework heavy EJB implementations. POCO should be used in the same context in .Net. Don't let frameworks dictate your object's design.
A DTO's only purpose is to transfer state, and should have no behavior. See Martin Fowler's explanation of a DTO for an example of the use of this pattern.
Here's the difference: POCO describes an approach to programming (good old fashioned object oriented programming), where DTO is a pattern that is used to "transfer data" using objects.
While you can treat POCOs like DTOs, you run the risk of creating an anemic domain model if you do so. Additionally, there's a mismatch in structure, since DTOs should be designed to transfer data, not to represent the true structure of the business domain. The result of this is that DTOs tend to be more flat than your actual domain.
In a domain of any reasonable complexity, you're almost always better off creating separate domain POCOs and translating them to DTOs. DDD (domain driven design) defines the anti-corruption layer (another link here, but best thing to do is buy the book), which is a good structure that makes the segregation clear.
It's probably redundant for me to contribute since I already stated my position in my blog article, but the final paragraph of that article kind of sums things up:
So, in conclusion, learn to love the POCO, and make sure you don’t spread any misinformation about it being the same thing as a DTO. DTOs are simple data containers used for moving data between the layers of an application. POCOs are full fledged business objects with the one requirement that they are Persistence Ignorant (no get or save methods). Lastly, if you haven’t checked out Jimmy Nilsson’s book yet, pick it up from your local university stacks. It has examples in C# and it’s a great read.
BTW, Patrick I read the POCO as a Lifestyle article, and I completely agree, that is a fantastic article. It's actually a section from the Jimmy Nilsson book that I recommended. I had no idea that it was available online. His book really is the best source of information I've found on POCO / DTO / Repository / and other DDD development practices.
POCO is simply an object that does not take a dependency on an external framework. It is PLAIN.
Whether a POCO has behaviour or not it's immaterial.
A DTO may be POCO as may a domain object (which would typically be rich in behaviour).
Typically DTOs are more likely to take dependencies on external frameworks (eg. attributes) for serialisation purposes as typically they exit at the boundary of a system.
In typical Onion style architectures (often used within a broadly DDD approach) the domain layer is placed at the centre and so its objects should not, at this point, have dependencies outside of that layer.
I wrote an article for that topic: DTO vs Value Object vs POCO.
In short:
DTO != Value Object
DTO ⊂ POCO
Value Object ⊂ POCO
I think a DTO can be a POCO. DTO is more about the usage of the object while POCO is more of the style of the object (decoupled from architectural concepts).
One example where a POCO is something different than DTO is when you're talking about POCO's inside your domain model/business logic model, which is a nice OO representation of your problem domain. You could use the POCO's throughout the whole application, but this could have some undesirable side effect such a knowledge leaks. DTO's are for instance used from the Service Layer which the UI communicates with, the DTO's are flat representation of the data, and are only used for providing the UI with data, and communicating changes back to the service layer. The service layer is in charge of mapping the DTO's both ways to the POCO domain objects.
Update Martin Fowler said that this approach is a heavy road to take, and should only be taken if there is a significant mismatch between the domain layer and the user interface.
TL;DR:
A DTO describes the pattern of state transfer. A POCO doesn't describe much of anything except that there is nothing special about it. It's another way of saying "object" in OOP. It comes from POJO (Java), coined by Martin Fowler who literally just describes it as a fancier name for 'object' because 'object' isn't very sexy and people were avoiding it as such.
Expanding...
Okay to explain this in a far more high-brow way that I ever thought would be needed, beginning with your original question about DTOs:
A DTO is an object pattern used to transfer state between layers of concern. They can have behavior (i.e. can technically be a poco) so long as that behavior doesn't mutate the state. For example, it may have a method that serializes itself. For it to be a proper DTO, it needs to be a simple property bag; it needs to be clear that this object is not a strong model, it has no implied semantic meaning, and it doesn't enforce any form of business rule or invariant. It literally only exists to move data around.
A POCO is a plain object, but what is meant by 'plain' is that it is not special and does not have any specific requirements or conventions. It just means it's a CLR object with no implied pattern to it. A generic term. I've also heard it extended to describe the fact that it also isn't made to work with some other framework. So if your POCO has a bunch of EF decorations all over it's properties, for example, then it I'd argue that it isn't a simple POCO and that it's more in the realm of DAO, which I would describe as a combination of DTO and additional database concerns (e.g. mapping, etc.). POCOs are free and unencumbered like the objects you learn to create in school
Here some examples of different kinds of object patterns to compare:
View Model: used to model data for a view. Usually has data annotations to assist binding and validation for particular view (i.e. generally NOT a shared object), or in this day and age, a particular view component (e.g. React). In MVVM, it also acts as a controller. It's more than a DTO; it's not transferring state, it's presenting it or more specifically, forming that state in a way that is useful to a UI.
Value Object: used to represent values, should be immutable
Aggregate Root: used to manage state and invariants. should not allow references to internal entities other than by ID
Handlers: used to respond to an event/message.
Attributes: used as decorations to deal with cross-cutting concerns. May only be allowed to be used on certain objects levels (e.g. property but not class, method but not property, etc.)
Service: used to perform complex tasks. Typically some form of facade.
Controller: used to control flow of requests and responses. Typically restricted to a particular protocol or acts as some sort of mediator; it has a particular responsibility.
Factory: used to configure and/or assemble complex objects for use when a constructor isn't good enough. Also used to make decisions on which objects need to be created at runtime.
Repository/DAO: used to access data. Typically exposes CRUD operations or is an object that represents the database schema; may be marked up with implementation specific attributes. In fact, one of these schema DAO objects is actually another kind of DTO...
API Contracts: Likely to be marked up with serialization attributes. Typically needs to have public getters and setters and should be lightweight (not an overly complex graph); methods unrelated to serialization are not typical and discouraged.
These can be seen as just objects, but notice that most of them are generally tied to a pattern or have implied restrictions. So you could call them "objects" or you could be more specific about its intent and call it by what it is. This is also why we have design patterns; to describe complex concepts in a few words. DTO is a pattern. Aggregate root is a pattern, View Model is a pattern (e.g. MVC & MVVM).
A POCO doesn't describe a pattern. It is just a different way of referring to classes/objects in OOP which could be anything. Think of it as an abstract concept; they can be referring to anything. IMO, there's a one-way relationship though because once an object reaches the point where it can only serve one purpose cleanly, it is no longer a POCO. For example, once you mark up your class with decorations to make it work with some framework (i.e. 'instrumenting' it), it is no longer a POCO. Therefore I think there are some logical relationships like:
A DTO is a POCO (until it is instrumented)
A POCO might not be a DTO
A View Model is a POCO (until it is instrumented)
A POCO might not be View Model
The point in making a distinction between the two is about keeping patterns clear and consistent in effort to not cross concerns and lead to tight coupling. For example if you have a business object that has methods to mutate state, but is also decorated to hell with EF decorations for saving to SQL Server AND JsonProperty so that it can be sent back over an API endpoint. That object would be intolerant to change, and would likely be littered with variants of properties (e.g. UserId, UserPk, UserKey, UserGuid, where some of them are marked up to not be saved to the DB and others marked up to not be serialized to JSON at the API endpoint).
So if you were to tell me something was a DTO, then I'd probably make sure it was never used for anything other than moving state around. If you told me something was a view model, then I'd probably make sure it wasn't getting saved to a database, and I'd know that it's ok to put 'hacky' things in there to make sure the data is usable by a UI. If you told me something was a Domain Model, then I'd probably make sure it had no dependencies on anything outside of the domain and certainly no dependencies on any technical implementation details (databases, services etc.), only abstractions. But if you told me something was a POCO, you wouldn't really be telling me much at all other than it is not and should not be instrumented.
History
Paraphrased from Fowler's explanation: In a world where objects were fancy (e.g. followed a particular pattern, had instrumentation etc.), it somehow encouraged people to avoid using not-fancy objects to capture business logic. So they gave it a fancy name POJO. If you want an example, the one he refers to is an "Entity Bean" which is one of those kinds of objects that have very specific conventions and requirements, etc.. If you don't know what that is --> Java Beans.
In contrast, a POJO/POCO is just the regular ole object that you'd learn out to create in school.
A primary use case for a DTO is in returning data from a web service. In this instance, POCO and DTO are equivalent. Any behavior in the POCO would be removed when it is returned from a web service, so it doesn't really matter whether or not it has behavior.
DTO objects are used to deserialize data into objects from different sources. Those objects are NOT your Model (POCO) objects. You need to transform those objects into your Model (POCO) objects. The transformation is mostly a copy operation. You can fill those POCO objects directly from the source if its an internal source, but its not adviceable if its an external source. External sources have API's with descriptions of the Schema they use. Its much easier then to load the request data in an DTO and after that transform those in your POCO's. Yes its an extra step, but with a reason. The rule is to load the data from your source in an object. It can be JSON, XML whatever. When loaded then transform that data in what you need in your model. So most of times the DTO is an object image of the external source. Sometimes you even get the Schema's of the source providers then you can deserialize even easier, XML works like that with XSD's.
here is the general rule: DTO==evil and indicator of over-engineered software. POCO==good. 'enterprise' patterns have destroyed the brains of a lot of people in the Java EE world. please don't repeat the mistake in .NET land.
Don't even call them DTOs. They're called Models....Period. Models never have behavior. I don't know who came up with this dumb term DTO but it must be a .NET thing is all I can figure. Think of view models in MVC, same dam** thing, models are used to transfer state between layers server side or over the wire period, they are all models. Properties with data. These are models you pass ove the wire. Models, Models Models. That's it.
I wish the stupid term DTO would go away from our vocabulary.

Categories

Resources