Home
About
Contact
Sunday, July 19, 2009

At QCon London 2009, Dan Bergh Johnsson had a talk on the DDD track about how to make use of Value Objects (VO's) (The Power of Value - Power Use of Value Objects in Domain Driven Design (PDF)). In his talk he took a piece of code and refactored it into a better piece of code by using VO's. By doing this Dan showed some really good concepts of using VO's. Even though I knew about the concept of VO's before his talk, he made me realize many new scenarios where they are applicable. And more importantly that it is not limited to DDD.

So what is a VO anyway? Is it related to value type in .NET?

To answer the last question first: The real answer is no, but the way I see it there is a relation. A value type in .NET is everything that is not an object. Typically simple types like int, char, double, but also enums and structs. The relation is that often you find yourself creating VO's where value types was previously used. It is however not limited to value types.

Now to the first question. I first came across VO's after reading Evans DDD book (commonly known as the blue book). In DDD a Value Object is an object without an Id and are usually immutable. In examples of VO's, Address is commonly used, which I don't find particularly useful. I think Address way too often has an Id and people have a hard time relating to that as a Value Object. I find the Amount example I gave in an earlier post to a better example or the one below illustrated as an interface (borrowed from Dan):

public interface IPhoneNumber {
  bool IsValid {get;}
  string Number {get;}
  string AreaCode {get;}
}

How many times have you used the concept of a phone number in your code? Like mobile, fax, fixed etc… How often have you kept it as a string? How much code do you have for doing different types of validation, getting area code etc? Do you have it all in one place or scattered around in different places? Other examples are Money, ZipCode etc… These are great candidates for Value Objects.

Now that we know what Value Objects are, what is so powerful about them and why should I use them more? Great question :-) Below is my three reasons:

  1. Code readability - I find that using Value Objects greatly improve the overall code readability and eliminates comments. Just like good names on methods and properties does.
  2. DRY (Don't Repeat Yourself) - By having a Value Object for PhoneNumber, you avoid writing code to handle specific cases around phone numbers and you reuse them wherever the concept of a phone number is used.
  3. Helps people getting back into OO thinking – We who have been living in the Microsoft .NET world for a long time have been thought to think of programming from a data/database perspective and not object oriented programming as we once learned it. In other words: think of behavior instead of data.

When I started to use VO's, I soon discovered I used them all over. They really add great value to my code. As an example, lets implement the IPhoneNumber above:

public class PhoneNumber : IPhoneNumber
{
    private readonly string _phoneNumber;
    public PhoneNumber(string phoneNumber)
    {
        _phoneNumber = phoneNumber;
    }
    public bool IsValid
    {
        get { return Regex.IsMatch(_phoneNumber, @"^[01]?[- .]?(\([2-9]\d{2}\)|[2-9]\d{2})[- .]?\d{3}[- .]?\d{4}$"); }
    }
    public string Number
    {
        get { return _phoneNumber; }
    }
    public string AreaCode
    {
        get
        {
            return Regex.Match(_phoneNumber, @"^[01]?[- .]?(\([2-9]\d{2}\)|[2-9]\d{2})").ToString();
        }
    }
}

The above code handles US phone numbers. To be used in a production system there should probably be even more validation in the regexp's, but I hope the example gives you and idea of what I'm thinking.

.Net | Architecture | CSharp | DDD | Patterns
Sunday, July 19, 2009 1:29:12 PM (W. Europe Daylight Time, UTC+02:00)
Tuesday, June 23, 2009

Recently I worked with a colleague on some code using decimal.TryParse() and tried to find a better way of using it. Specifically I had a string value representing a currency amount entered by a user in a web form. The amount needed more than just normal validation, so I needed to do some stuff with it.

Here's the code I started with:

public void SomeMethod(string userEnteredAmount)
{
    decimal amount;
    if(decimal.TryParse(userEnteredAmount, out amount) {
        //Do some stuff with amount
    }
    else {
        //Show message to user about invalid amount
    }
}

I've recently found many cases where I find the use of Value Objects to be very applicable. I found this case to be a particularly interesting example. Anyway, I created a Value Object called Amount to abstract away the TryParse stuff. Below is the class I created.

public class Amount
{
    private readonly decimal _value;
    private readonly bool _isValid;
    public Amount(string amount)
    {
        _isValid = decimal.TryParse(amount, out _value);
    }
    public decimal Value
    {
        get { return _value; }
    }
    public bool IsValid
    {
        get { return _isValid; }
    }
}

See how clean it got? At least I think so. The important part though is that it's usage is so much easier to understand and read:

var amount = new Amount(userEnteredAmount);
if(amount.IsValid) {
    //Do some stuff with amount.Value
}
else {
    //Show message to user about invalid amount
}

It's more code, but cleaner. Or did I say that already? :-) And of course it's reusable other places where amount has a meaning.

.Net | CSharp | DDD | Patterns
Tuesday, June 23, 2009 12:17:10 AM (W. Europe Daylight Time, UTC+02:00)
Sunday, February 08, 2009

Greg Young is sharing his wisdom around DDD at the first ever European ALT.NET meeting at 7PM GMT. Attendee URL: http://snipr.com/virtualaltnet (Live Meeting)

Friendly reminder: If you don’t have the Live Meeting client installed you should do that before the meeting starts. Just click on the attendee URL above and follow the instructions.

.Net | DDD | Events
Sunday, February 08, 2009 9:54:28 PM (W. Europe Standard Time, UTC+01:00)
Saturday, February 07, 2009

This interview kind of slipped my radar. Actually I didn’t have time until now to actually watch it. Now when I had however, I sincerely recommend everybody who’s slightly interested in DDD to watch it. It’s only 30 minutes.

One of the more interesting things he talked about, was have the domain model care only about writes. This is something for my x co-workers at Contiki to have a look at (guys, I believe this could help you out). Why is this interesting and not only nuts!? Well, it opened up a door for me related to my concerns around the usage of DTO’s. Why would I want to transform all my domain objects to DTO’s for the sake of moving it to some client to display data on a screen?

Greg suggest using DTO’s for displaying data to the user (think of it as a report), and pushing all your writes through your domain model (all changes to your domain). By doing this you get domain objects without getters and setters! That shouldn't be a goal in itself, but think about what it really means… Done thinking? Let me add a few more … (dots) Ok, ok… It means (as I interpret it) you create a separation between what your system needs to show to the end user and what your domain should care about. Why clutter the domain with reports?

If you have any thoughts about this, please let me know. Thanks.

Saturday, February 07, 2009 8:48:03 PM (W. Europe Standard Time, UTC+01:00)
Tuesday, November 25, 2008

On the DDD mailing list a few days ago Richard Pawson posted that he and his team have created a DDD framework for .Net. Since I’ve had my head down in DDD for the last couple of months I thought I’d check it out. When posting this I’ve still not tried it, but I’ve watched some of the videos which you can find here:  http://www.nakedobjects.net/demo/demo_intro.shtml

Honestly I’m not sure what I think of DDD frameworks in general. By definition I’m skeptical :-), but I promise to try it out and come back with some sort of conclusion of my findings and impressions. Btw. I’ve not been approached by Naked Objects to review their product in case you were wondering :)

.Net | Architecture | DDD | Patterns | Software | Tools
Tuesday, November 25, 2008 8:44:41 AM (W. Europe Standard Time, UTC+01:00)
RSS RSS - Comments Twitter LinkedIn
         
SEARCH
 
 
         
TOP POSTS
   
         
NAVIGATION
   
         
CATEGORIES
  .Net (61) ADFS (3) Agile (30) Ajax (5) Architecture (20) Articles (1) ASP.NET (6) ASP.NET-MVC (1) Blogging (12) Books (2) BPEL (1) CleanCode (1) CloudComputing (7) Community (4) CSharp (11) DasBlog (5) Database (2) DDD (5) Deployment (16) DSL (1) Events (38) ExtremeProgramming (6) Fun (6) Gadgets (4) IIS (10) InfoQ (4) Java (2) Lean (3) Linq (2) MemoryLeaks (5) Microsoft (37) MVC (1) NDC (2) NNUG (36) Other (10) Patterns (9) Performance (3) Scrum (17) Security (7) ServiceBus (1) Silverlight (4) Software (19) TeamManagement (11) TechEd (7) Testing (4) Tools (25) TvGuide (1) WCF (8) Web (15) WebDeploy (1) WIF (3) Windows (10) Vista (15) VisualStudio (16) WiX (9) Work (16) Workflow (3)  
         
ARCHIVE
   
         
BLOGROLL
   
         
ON THIS PAGE...
 
Start Using More Value Objects!
Refactoring TryParse Into a Value Object
Don’t forget Monday’s Virtual ALT.NET meeting
Greg Young on DDD
Naked Objects - DDD framework for .Net