Saturday, April 16, 2011

Data Transfer Objects

While writing softwares there can be a need of any/all of the following:
  • Transferring data across applications/boundaries/network
  • Sending a long list of parameters to a function
  • Returning multiple objects

  • When you communicate over a network, multiple calls may be involved in order to accomplish a single task. 
  • Sending a long list of parameters may incur unnecessary errors, as the developer might make a mistake in giving input parameters.
  • Although returning multiple objects is possible through the "out" parameter, a long list of "out" parameters is cumbersome.

When faced with such a dilemma it is wise to use a design pattern called a "Data Transfer Object".

MSDN describes DTO as:

A DTO is a simple container for a set of aggregated data that needs to be transferred across a process or network boundary. It should contain no business logic and limit its behavior to activities such as internal consistency checking and basic validation. Be careful not to make the DTO depend on any new classes as a result of implementing these methods.

From the above definition we gather that a DTO:
  • may be a simple class with properties exposed.
  • may contain only basic validation code.
  • should not contain any business logic.

MSDN also gives two possible ways of writing DTOs:

  1. Writing Custom Classes: Let's say you have an application that requires login. For login applications normally have a user object with properties like User Name, Password, Creation Date, Permissions etc. This information is normally validated through database. But there is also a possibility that data is required from different sources.
    Whatever the case, the user object remains the same. Remember that Data Transfer Objects do not contain any business logic, therefore, it does not make any difference from where the data is obtained. You simply need to create a class with properties for User Name, Password, Creation Date, Permissions etc.

  2. Using Collections:
    Let's say you need to invoke a Web Method which would require sending a long list of parameters. In this case you can change the signature of the web method so that it expects one Array List (or any other collection) instead of a list of parameters.

    Here you'll simply have to create an object of Collections (System.Collections in .Net) and fill in the required values in the collection.

    The disadvantage with this approach is that each parameter/field would loose it's actual data type. You'll have to add all the required fields after casting them into a particular data type, say Object or string. And this would require casting them back to their original data types later on, which may incur errors.

Referenced Links:

No comments:

Post a Comment