Archives

Archives / 2008 / May
  • Avoid returning "null" and use the Null Object pattern?

    When I build applications and add methods to return a list of objects, I make it robust. So I always return an instance of the list instead or returning null. The reason is because I like the use of Count and also use foreach. I don't want to add extra code to see if the method returns null. For example:

    Read more...

  • Avoid "else" as much as possible, use "?:" instead

    To have a 10 week old baby Chihuahua takes a lot of time… the housekeeping is not so easy. I need to go up twice at night to let the little baby boy do his stuff. But it’s really wonderful to have such a small dog in my home, I bought a lot of books about how to be a pack leader.. I love reading books about leadership etc so it should be interesting to read those books about packs. Here is a video on YouTube where I play with him, if anyone is interested to see a dog that has the same size as a cat puppy. http://www.youtube.com/watch?v=KOWZjHTBiKo

    Read more...

  • Use "constraints" instead of argument validation for int and double etc

    I will still continue with the argument validation track in this post also, I think it's an interesting topic.

    If you haven't read my earlier posts about this topic, take a look at the following posts on my blog:

    http://weblogs.asp.net/fredriknormen/archive/2008/05/07/lazy-developers.aspx

    http://weblogs.asp.net/fredriknormen/archive/2008/05/08/how-to-validate-a-method-s-arguments.aspx

    This time I will focus on argument of type int and double etc. Lets assume we have a method which should be used to set a price on a product:

    public class Product
    {
        public void SetPrice(double price)
        {
            price.RequireArgument("price")
                 .GreaterOrEqualTo(0);
    
            //..
        }
    }

    Note: I will use my friend Roger Alsing cool argument validation solution in this example you can read more about it on his blog.

    I use a Set method instead of a property in this example.

    I use a validation here to make sure price is not lesser then 0. Here is another method that takes three argument, year, month and day as integers:

    public void SetDate(int year, int month, int day)
    {
        year.RequireArgument("year")
            .InRange(1900, 3000);
    
        month.RequireArgument("month")
            .InRange(1, 12);
    
        day.RequireArgument("day")
           .InRange(1, 31);
    
       //...
    }

    Note: The Day argument here is special, as we know there is not always 31 days in each month, so another kind of validation is needed, but I make this code only simple for this post.

    Now lets change this code and make sure the int and double is not an argument that can take a number larger and lesser than the validation. What we do is to create a Price, Year, Month and a Day class and use them as an argument instead of double and int.

    public class Price
    {
           private double _price;
    
           public Price(double price)
           {
               price.RequireArgument("price")
                    .GreaterOrEqualTo(0);
    
               this._price = price;
           }
    
           //...
       }
    
    
       public class Year
       {
           private int _year;
    
           public Year(int year)
           {
               year.RequireArgument("year")
                   .InRange(1900, 3000);
           }
    
           //...
       }
    
    
       public class Month
       {
           private int _month;
    
           public Month(int month)
           {
               month.RequireArgument("month")
                  .InRange(1, 12);
           }
       }
    
    
       public class Product
       {
           public void SetPrice(Price price)
           {
               //..
           }
    }
    
    
    public void SetDate(Year year, Month month, Day day)
    {
        //...
    }

    Note: I skip the Day struct because of not adding to much code, you still get the basic ideas from the other structs.

    As you see now the method takes a Price, Year, Month and a Day object, not a double or int and it will directly add a constraint. The user of the method can't pass in a invalid value. I also moved the validation to the classes instead. The Price class could be replaced with the Money pattern Fowler mention in his book if we want it to handle Money.

    What do you think, is this something you use today?

    Read more...

  • How to validate a method's arguments?

    Yesterday I wrote a post about developers that skip validation of arguments. In this post I will give some example of how validation can be done. There are probably better way to do it, and that is why I need your feedback and comments.

    The first example is a simple method that uses a simple validation by using “If”.

    public string DoSomething(int value1, string value2)
    {
        if (value1 > 10 || value1 < 0)
           throw new ArgumentException("The value must be between 0 or 10", "value1");
    
        if (string.IsNullOrEmpty(value2))
           throw new ArgumentException("The value can't be null or empty", "value2");
    
        //...
    }


    I started to use this solution to validate arguments, but what I notice really fast was that I repeat my self over and over again when I created more methods. I solved this by creating an ArgumentHelper class where I add my validation logic.

    public static class ArgumentHelper
    {
        public static void RequireRange(int value, int minValue, int maxValue, string argumentName)
        {
            if (value > maxValue || value < minValue)
               throw new ArgumentException(string.Format("The value must be between {0} and {1}", minValue, maxValue), argumentName);
        }
    
        public static void RequireNotNullOrEmpty(string value, string argumentName)
        {
            if (string.IsNullOrEmpty(value))
               throw new ArgumentException("The value can't be null or empty", argumentName);
        }
    }

    public string DoSomething(int value1, string value2)
    {
        ArgumentHelper.RequireRange(value1, 0, 10, "value1");
    
        ArgumentHelper.RequireNotNullOrEmpty(value2, "value2");
    
        //...
    }


    With C# 3.0 we now have Extension Methods, so why  not use Extension Methods to do the validation for a given type? Here is an example where I use Extension methods instead of an ArgumentHelper class:

    public static class ArgumentHelperExtension
    {
        public static void RequireRange(this int value, int minValue, int maxValue, string argumentName)
        {
            if (value > maxValue || value < minValue)
                throw new ArgumentException(string.Format("The value must be between {0} and {1}", minValue, maxValue), argumentName);
        }
    
    
        public static void RequireNotNullOrEmpty(this string value, string argumentName)
        {
            if (string.IsNullOrEmpty(value))
                throw new ArgumentException("The value can't be null or empty", argumentName);
        }
    }

    public string DoSomething(int value1, string value2)
    {
        value1.RequireRange(0, 10, "value1");
        
        value2.RequireNotNullOrEmpty("value2");
    
        //...
    }

    As you can see the ArgumentHelper class have no changes, well the "this" key word is added to the first argument in the methods. I can then simply use my argument and call an Extension method that will do the validation.

    I recently had a discussion with my friend Roger Alsing and he had some interesting ideas. If we take a look at the Extension Method example, we can see that we add validation extension method to a given type. Let assume we don't want to add several Extension method to the type Int, instead only one method and that method returns a given "interface" which we can extend instead. For example to Int we can have a Extension method called Require and let it return a Numeric<T>, and then we can create Extension methods for the Numeric<T> class instead:

    public static string DoSomething(int value)
    {
        value1.Require().InRange(0, 10, "value1");
    
        //...
    }

    Another interesting solution Roger had is the following:

    static void MyMethod(string arne)
    {
        RequireNotNull( () => arne);
    }

    static void RequireNotNull<T>(ArgDelegate<T> del)
    {
        T value = del();
    
        FieldInfo[] fields = del.Target.GetType().GetFields(BindingFlags.NonPublic | BindingFlags.Public | BindingFlags.Instance);
        if (fields.Length != 1)
           throw new NotSupportedException("Invalid argument");
    
        string argName = fields[0].Name;
    
        if (value == null)
           throw new Exception(string.Format("Parameter '{0}' may not be null", argName));
    }

    By using this solution we don't need to pass the name of the argument as a string like in the following solutions:

    ArgumentHelper.RequireRange(value1, 0, 10, "value1");
    
    value1.RequireRange(0, 10, "value1");
     
    Instead reflection is used to get the name of the argument. This can of course affect performance.

    How do you implement your validation code, do you have some cool solution?

    Why can't we just have Design By Contract support for C#... ;)

    Read more...

  • Lazy Developers?

    When I was out with my new dog (I Chihuahua, wonderful dog), I was thinking about Defensive Programming and Design by Contract. I like to do some refactoring and help other people to write cleaner code etc,  not that I’m an expert in the area but I think most of developers can see stuff that blinds other developers during development. I remember a scenario that made me kind of mad, I often notice that some developers doesn’t even care to validate arguments on public API or other methods, they assume the caller pass in the right values. When I started to develop apps, I didn’t validate arguments (In know I was a noob ;)). But since I started to do validation, it reduces the number of bugs in my code, and the difference was big. But that isn’t the only reason I like to do validation. Another  reason is because the caller of the method should know if they have passed a wrong value, there are of course some other reasons also, but the main reason is make sure the caller or the method pass in the correct value, and if they do, they will get what they want.

    I notice that several developers today don’t care about validation, I ask them why and they all gave me the same argument “Why should I, it will only make me add more code and it’s boring to write code that checks values”. Can this be summarized that some developers are lazy?

    Maybe I’m stupid because I get mad when I hear that kind of argument, but I’m special ;)

    Read more...