Should a Trim method generally in the Data Access Layer or with in the Domain Layer?

Posted by jpierson on Stack Overflow See other posts from Stack Overflow or by jpierson
Published on 2010-05-11T11:16:25Z Indexed on 2010/05/12 3:14 UTC
Read the original article Hit count: 254

Filed under:
|
|
|
|

I'm dealing with a database that contains data with inconsistencies such as white leading and trailing white space.

In general I see a lot of developers practice defensive coding by trimming almost all strings that come from the database that may have been entered by a user at some point. In my oppinoin it is better to do such formating before data is persisted so that it is done only once and then the data can be in a consistent and reliable state. Unfortunatley this is not the case however which leads me to the next best solution, using a Trim method.

If I trim all data as part of my data access layer then I don't have to concern myself with defensive trimming within the business objects of my domain layer. If I instead put the trimming responsibility in my business objects, such as with set accessors of my C# properties, I should get the same net results however the trim will be operating on all values assigned to my business objects properties not just the ones that come from the inconsistent database.

I guess as a somewhat philisophical question that may determine the answer I could ask "Should the domain later be responsible for defensive/coercive formatting of data?" Would it make sense to have a set accessor for a PhoneNumber property on a business object accept a unformatted or formatted string and then attempt to format it as required or should this responsibility be pushed to the presentation and data access layers leaving the domain layer more strict in the type of data that it will accept? I think this may be the more fundamental question.

Update: Below are a few links that I thought I should share about the topic of data cleansing.

Information service patterns, Part 3: Data cleansing pattern

LINQ to SQL - Format a string before saving?

How to trim values using Linq to Sql?

© Stack Overflow or respective owner

Related posts about ddd

Related posts about n-tier