views:

220

answers:

2

Hi,

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

+1  A: 

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

Robert Harvey
+3  A: 

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.

Chansik Im
+1 for "changing the DTO would require changing code in the domain logic"
AJ
FWIW, AutoMapper is pretty good.
Gavin Schultz-Ohkubo