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)

One of the code smells I see most often in C# and other OO languages is the misuse of switch/case statements. When I was a young Jedi (some might argue I still am :-)) I didn't see anything wrong with using the switch statement. Actually there still are a few cases where it's still applicable, but most usages I come across should have been solved differently. So why is this? What is so bad with the switch statement?

As Dan North tweeted me when I asked for the perfect refactoring solution for switch statements :-) :

A switch is often a sign of behaviour that should live elsewhere - so where should the code in the cases live?

Functions should only do one thing, the one thing which they state. Like CalculateInterest and ConvertDateToString should do exactly that; calculate interest and convert a date to string. Since switch always reside inside functions it almost always violates that principle.

Let's look at what Uncle Bob (Robert C. Martin) says in his Clean Code book about switch statements:

Even a switch statement with only two cases is larger than I'd like a single block or function to be. It's also hard to make a switch statement that does one thing. By their nature, switch statements always do N things.

My answer to Dan's question above was using polymorphism. The cases should live in their own classes. By doing that you don't have to modify existing code when introducing new behavior, you just create a new state (read class). Btw Dan is really good at asking questions to questions where you end up answering your own question :-)

Enough with the coding theory. Below is a method using a switch statement for getting messages from different systems. Typically these are systems that another system depends on (the system containing the below code). The messages might be if the system is available or not, or if there are any maintenance planned.

public string GetSystemMessage(System system)
{
    switch (system)
    {
        case System.System1:
            return GetSystem1Message();
        case System.System2:
            return GetSystem2Message();
        case System.System3:
            return GetSystem3Message();
        case System.System4:
            return GetSystem4Message();
        default:
            throw new ApplicationException("System not found");
    }
}

This is actually quite a good switch. It uses return instead of break and it only has one line per case. If you can't avoid writing a switch, this is how you should do it.

Now let's pull it apart and make it better and extendable. Time for refactoring.

Polymorphism by using Strategy Template Pattern
Here's my code using the Strategy pattern:

public interface ISystemStrategy
{
    string GetMessage();
}
public class System1Strategy : ISystemStrategy
{
    public string GetMessage()
    {
        return "System1";
    }
}
public class System2Strategy : ISystemStrategy
{
    public string GetMessage()
    {
        return "System2";
    }
}
public class System3Strategy : ISystemStrategy
{
    public string GetMessage()
    {
        return "System3";
    }
}
public class System4Strategy : ISystemStrategy
{
    public string GetMessage()
    {
        return "System4";
    }
}
public class SystemMessenger
{
    private readonly ISystemStrategy _system;
    public SystemMessenger(ISystemStrategy system)
    {
        _system = system;
    }
    public string GetMessage()
    {
        return _system.GetMessage();
    }
{
}

First I define an interface to be used by the different systems (ISystemStrategy) and next each system (1-4) implements that interface, resulting in a class for each case in the switch.In addition I have a class called SystemMessenger that is responsible for accessing the system and get a message.

The switch can now be replaced by this code:

public string GetSystemMessage(ISystemStrategy system)
{
    return new SystemMessenger(system).GetMessage();
}

Note that the "client" only relates to the SystemMessenger class and not to the different implementations of ISystemStrategy.

The benefit of this code might not be obvious. Actually it might give the impression that this was a lot of code for almost nothing. Well, don't be fooled. The strongest aspect of the above solution is that you don't have to change the GetSystemMessage later when/if a new system is added, you just implement a new class.

To prove the above, here's what I need to do to introduce a new system:

public class System5 : ISystemStrategy
    public string GetMessage()
    {
        return "System5";
    }
}

To use the new system, an instance of System5 will be sent into GetSystemMessage just as before, and SystemMessenger handles the rest as before. No code change!

Dictionary
Another refactoring option is using some type of lookup table. In my example I'll use a dictionary together with the Func<TResult> delegate. However, I don't recommend doing this unless you have a really good reason to do so. Stick with the Strategy pattern if you can.

public class SystemMessengerDictionary
{
    private readonly Dictionary<System, Func<string>> _systems;
    public SystemMessengerDictionary()
    {
        _systems = new Dictionary<System, Func<string>>
                           {
                               {System.System1, GetSystem1Message},
                               {System.System2, GetSystem2Message},
                               {System.System3, GetSystem3Message},
                               {System.System4, GetSystem4Message}
                           };
    }
    public string GetSystemMessage(System system)
    {
        return _systems[system]();
    }
    //GetSystemX Methods
    ...
}

I decided to show this example even if I don't like it. The reason is that it is better than the switch. The worst about this in my eyes is that the enum is still there. I just hate enums! When reading the code they look like classes with interesting behavior, but then you discover they're just glorified int's :-|

Conclusion
Hopefully this example will help you understand why switch is something you should avoid and also give you an example of how it should be done. But before you consider doing any refactoring of existing code, consider a second question Dan asked (answered?) me:

How would it evolve if you added a few more cases? And how likely are a few more cases?

This is an important question, because you don't want to refactor just for the sake of refactoring. Keep this in mind before making use of any of the suggested solutions above.

Sunday, July 19, 2009 12:53:15 AM (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)
Thursday, April 30, 2009

A good friend of mine, Mark Nijhof, will be doing a presentation on FubuMVC at the next European Virtual Alt.NET meeting. Mark is actively involved with the alternative MVC framework for ASP.NET together with Chad Myers and Jeremy D. Miller. Mark will also do a Fubu presentation at NNUG Bergen 27th of May (invitation will be available soon).

If you want to know more about FubuMVC you can check out the interview I did with Chad on InfoQ and of course their public website. I encourage you to download Fubu and try it out, cause it has some interesting differences which I personally like compared to ASP.NET MVC.

Also, Jeremy Miller is coming to Bergen and NNUG in mid June just before NDC (thanks Mark for organizing this!), so I’m really looking forward to that. A lot of stuff happening at the local community in Bergen at the moment!

.Net | ASP.NET | NNUG | Patterns
Thursday, April 30, 2009 9:07:29 PM (W. Europe Daylight Time, UTC+02:00)
Tuesday, April 28, 2009

image Is there anything more annoying than standing on a red light, when there is no car, motorcycle or carbon life form in sight? Maybe traffic lights elsewhere in the world are more intelligent, but at least where I live this happens from time to time. So what have this to do with developers? Good question, but let me first try to answer another one: Why do we have traffic lights?

From Wikipedia:

Traffic lights, also known as traffic signals, stop lights, traffic lamps, stop-and-go lights, robots or semaphore, are signaling devices positioned at road intersections, pedestrian crossings, and other locations to control competing flows of traffic.

I read: bla bla bla bla… control competing flows of traffic. I would probably have said something like this:

To avoid cars running into each other and avoid have people run over in a cross road. It’s a very logical way of saying stop or drive (red and green). Yellow is the same as green, but for taxis only. Traffic lights are regulated by sensors in the ground detecting where there is traffic and not + a algorithm to give green lights in a predefined order.

Now back to the first question, answered by asking a new one: What’s the equivalent of traffic lights in development? No, not red, green, refactor :-) I was thinking about frameworks, internal DSL’s and the like. Stuff that good developers create, which the not so good developers should use. To keep them from “hurting” themselves or the company they work for. Do you find that to be ok?

Tuesday, April 28, 2009 7:35:35 AM (W. Europe Daylight Time, UTC+02: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)
Tuesday, September 02, 2008

As mentioned before, I created a small tool for sending out emails to our members in NNUG. When implementing tools like these I always make sure to experiment with new language features, patterns or similar. This time it was the fluent interface to be tested.

Recently there has been a lot of focus on Domain Specific Languages (DSL's). A Fluent Interface is a specific type of DSL. Martin Fowler and Eric Evans gave this DSL type its name in 2005 which you can read more about here.

To jump right into the usage of my interface here's how to send an email to one person from code:

EmailComponent email = Email
    .To("somebody@torresdal.net")
    .From("anybody@torresdal.net")
    .WithSubject("Anybody out there?")
    .Using.Body("Guess not...");
email.Send();

The above code is nice, but you can't really do anything useful with it. You can send emails from code, but I would rather use an email client for that :-) So lets make it a bit more interesting:

EmailComponent email = Email
    .ToAllIn("recipients.txt")
    .From("anybody@torresdal.net")
    .WithSubject("Anybody out there?")
    .Using.TxtBodyFromFile("someTxtFile.txt")
    .Using.HtmlBodyFromFile("someHtmlFile.html");
email.Send();

Now instead of specifying one single to address we point to a file where all the recipients are found. Also instead of the body text we use a text file and a html file to be used as the email body. In this way, when you send emails, people that can only receive plain text emails will get that, and the others will get the html version. This is done using the AlternateView class in .Net.

But there is more interesting stuff you can do:

EmailComponent email = Email
    .ToAllIn("recipients.txt")
    .From("anybody@torresdal.net")
    .WithSubject("Anybody out there?")
    .Using.TxtBodyFromFile("someTxtFile.txt")
    .Using.HtmlBodyFromFile("someHtmlFile.html")
    .PauseAfter.Every(30).EmailSent.For(20).Minutes;
email.Send();

In the last line we say: Pause after every 30 email sent for 20 minutes. So what would you use that for? If you send out 500 emails, your smtp server might not like you very much, so he/she just reject your request thinking you're a spammer. By splitting it up you still might be a spammer, but the smtp server won't know it.

There are many variants of the above line. Here's a few other examples:

.PauseAfter.Every(10).Minutes.For(1).Hour;
.PauseAfter.Every().Hour.For(2).Hours

How is this done you might ask? First of I read Anders Norås excellent article about fluent interfaces (Behind the scenes of the planning DSL) and Martin Fowler's articles from his coming book about DSL's to get a deeper understanding.

So in essence I've basically picked the right words (hopefully) for the method names and properties to build up an understandable sentence implemented by using Method Chaining. Here's what Martin Fowler says about method chaining:

Method Chaining is an idiom that acheives this through a sequence of modifier calls where each call returns the host object for further modification.

Implementing method chaining is quite simple illustrated by the code below:

public Email To(string emailAddress)
{
    _to = emailAddress;
    return this;
}

This is from my Email class of the fluent interface. See how it returns itself? This is so that you can do subsequent calls to the same class.

If you've been very observant you've seen that the To method returns an Email object, but the object type returned after the "sentence" is finished is an EmailComponent. As Anders accurately describe in his post this is done using an implicit user-defined type conversion operator in C#. It's actually not as difficult as it might sound :-) Check out Anders article for details.

Another good point made by Anders is writing this without "code by example" or TDD is almost impossible. Write your sentences first and then implement the code. Actually, for people trying to learn/master TDD an excellent way of practicing is writing a fluent interface!

Even though this was really cool (at least I think so), is it any useful? If you see where fluent interfaces are used today, they tend to be around configuration. Instead of hacking around in an xml file not really knowing when you miss type something, using a type safe fluent interface might be a good idea. Examples of this is Ninject, NHibernate and others. Is my Email client any good as a fluent interface? If you remove the PauseAfter functionality the answer is: not really. However, the PauseAfter thing actually adds some value to it all. There are other ways of solving that quite nice just using a plain API, but that's no fun is it?! :-)

.Net | CSharp | DSL | Patterns
Tuesday, September 02, 2008 7:57:23 PM (W. Europe Daylight Time, UTC+02:00)
Monday, January 22, 2007
The guys at Microsoft Patterns & Practices have created a new site for upcoming releases. Nice to see what’s going on release wise. Take a look at Tom Hollanders blog to get the complete story.
Monday, January 22, 2007 3:15:26 PM (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!
Different Ways of Refactoring Switch/Case
Refactoring TryParse Into a Value Object
Mark Nijhof on FubuMVC at the next VAN meeting
Developers and Traffic Lights
Greg Young on DDD
Naked Objects - DDD framework for .Net
Fluent email interface
New page at P&P