EvilRob.org -> Weblog

Sysadmin Field Notes

Value Objects in C#: Things to keep in mind

March 22, 2006

Ran into a few interesting defects that quickly turned our codebase into a C# trivia contest this week.

We have a value object in our domain that three possible values, and they were being stored as readonly references in static variables. So of course the references are readonly, but the objects weren't (because we are persisting with NHibernate which seems to be requiring read/write parameters).

So, if you change something in a unit test (which I'm not sure why it happened anyway), be careful not to change one of your permanent copies, lest you end up with unit tests that break in the suite but work fine individually. Yuck.

Lesson two was about distribution. Reference equality looks nice, but is no fun when serializing your objects, since your object coming from a deserialization isn't going to be the same object as the static readonly private reference. Whoops again. So implement .Equals() and remember to use it.

Better designs to solve #1 we're thinking about including a read-only subclass that at least throws exceptions when it changes that we'll assign instances out as. #2 is less fun, because I don't want to override ==, since I strongly believe that should stick to it's meaning. We'll see if an intense education campaign can keep us out of trouble.

Posted by rmeyer at 9:56 PM

This is Rob Meyer's weblog, a weblog focused on software development and system administration based on 10 years of experience. Want to explore further? You can find out more me or see the rest of my website.

Wondering if I've written on something in particular? Try searching:

You might want to take a look at some of the more requested postings (as judged by incoming traffic):

Want more? Subscribe to this site or contact me at rob at big dis dot com.

See my writings on:


Powered by Movable Type | Technorati Profile