Leaky Data Access Layer Encapsulation

I’m doing a code review right now of some domain logic layer code. Unfortunately, sprinkled throughout the domain logic layer are properties such as:

This is definitely the database implementation leaking into the domain logic layer. I’m not going to comment (yet?) on whether a string column in the database with “Y” and “N” values is a good idea, but it’s definitely a bad idea in the domain logic layer. Furthermore, notice that the setter doesn’t even check that the value is actually ‘Y’ or ‘N’ (and are ‘y’ and ‘n’ okay too, or are they “right out”?). The convenient use of automatic properties is handy, but in this case completely inappropriate because I could set “Negatory!” – and I probably won’t notice until the database blows up (hopefully). Additionally, because this is a string property I’m forcing all the code that wants to use this property to manually check the value:

Sadly, this further propagates how the database is storing its values, and provides lots and lots of code duplication anywhere this property needs to be used. (Notice also that this would fail if somebody had set the property to “Yes” or “1”).

Therefore, MUCH better is the following, normal .NET code:

By changing the domain logic layer property to be a Boolean property we don’t need to document what the “appropriate” string values are, and we also don’t need to check that the appropriate value is being set. This also makes all use of the property obvious and easy, and unaware of the underlying database implementation:

Notice that this change does not impose any change on the database – the Database Access Layer (DAL) should completely encapsulate how the database actually stores this particular property, and there is no ambiguity in the domain logic layer code and all the higher level layers that use it. This is also the first step towards refactoring the database to store our Boolean property as something other than a VARCHAR…

Part 2: Another leaky encapsulation

Another leaky encapsulation of the database implementation is properties such as:

This of course shares all the same flaws as the previous leaky encapsulation, but also, what the hell are “Inir” and “Inna“?!

MUCH better is to provide a public enumeration in the domain logic layer:

And then change the property to use the enumeration:

Again, the database access layer should be completely and strongly encapsulating the strange codes that the database designers chose to use for the various values.

Conclusion:

Be very aware of how database implementation details can leak into the domain logic layer and beyond, and put a stop to it if you can help it! Your code will be much better off, easier to understand and much easier to maintain and improve over time.

Leave a Reply

Your email address will not be published. Required fields are marked *