Joe

Mister Doctor Professor
posts - 23, comments - 19, trackbacks - 134

Thursday, January 10, 2008

Extension Methods and Fluent Interfaces

File under stupid semantic tricks.

Extension methods (which seem ripe for abuse and all kinds of bad code) provide some great flexibility when working with fluent interfaces.  For example, take the following extensions to the date class

 

    public static class ExtensionMethods
    {
        public static bool IsBefore(this DateTime dt, DateTime other)
        {
            return other > dt;
        }
    }

 

This allows us to better express our intent

 

    public class WorkingWith
    {
        public void Test1()
        {
            DateTime myBirthday = new DateTime(2008, 3, 1);
            DateTime christmans = new DateTime(2008, 12,25);
            
            if (myBirthday.IsBefore(christmans))
            {
                Console.WriteLine("yes");
            }
 
        }
    }

Which is nice, but can get better by wiring in a call to a utility class

 

    public static class ExtensionMethods
    {
        ...
 
        public static IsBetweenDateRange IsBetween(this DateTime dt, DateTime lowDate)
        {
            return new IsBetweenDateRange(dt, lowDate);
        }
    }

which allows a readable (as opposed to parse-then-translate-able) statement such as

        public voidTest2()
        {
            DateTime myBirthday = new DateTime(2008, 3, 1);
            DateTime halloween = new DateTime(2008, 10, 31);
            DateTime christmans = new DateTime(2008, 12,25);
            
            if (halloween.IsBetween(myBirthday).And(christmans))
            {
                
            }
        }

 

The utility class in this case being

    public class IsBetweenDateRange
    {
        private DateTime _baseDate;
        private DateTime _lowDate;
 
        public IsBetweenDateRange(DateTime baseDate, DateTime lowDate)
        {
            _baseDate = baseDate;
            _lowDate = lowDate;
        }
 
        public bool And(DateTime highDate)
        {
            return _baseDate > _lowDate && _baseDate < highDate;
        }
 
    }

posted @ Thursday, January 10, 2008 8:52 AM | Feedback (10) |

Powered by: