Posts Tagged ‘lambda’

Using lambdas for handling change

August 9, 2009

I was TDDing an Event Logger. Now the logger takes an event message and then adds a date time stamp. The way you would do it is use DateTime.Now. The problem was how to verify that the date time stamp had been added. Pass into the object a DateTimeServer object. This seemed too much. Create an object. Talk about noisy tests. Instead I just pass this object into my logger and here is some some of the logger code:

        [Test]

        public void should_add_date_time_stamps()

        {

            const string dts = "mm/dd/yyyy 00:00:00 AM";

 

            Func<string> dateTimeStamper = (() => dts);

            var logger = new EventLogger(dateTimeStamper);

            logger.Handle(OperationEstop.EStop);

            logger.Handle(OperationEstop.EStop);

 

            logger.Data().ShouldContainForEachLine(dts);

            logger.Data().Lines().ShouldEqual(2);

        }

Notice in the test ShouldContainForEachLine and Lines methods. These are extension methods. They make the test much more readable.

    public class EventLogger : IListener<OperationEstop>, 
        IListener<StatusMessage>, IListener<LoginSuccessful>,
        IListener<LoginEvent>, IListener<ScheduleLoad>,
        IListener<ScheduleLoadEvent>, IListener<SystemEvent>
    {
        private readonly StringBuilder _sb = new StringBuilder();
        private readonly Func<string> _dateTimeStamp;
 
        public EventLogger(Func<string> stamp)
        {
            _dateTimeStamp = stamp;
        }
 
        public string Data()
        {
            return _sb.ToString();
        }
 
        public void Handle(OperationEstop message)
        {
            AddDateTimeStampToEntry(message.Status());
        }
 
        //Other Handlers ...
 
        private void AddDateTimeStampToEntry(string status)
        {
            if (_sb.Length > 0)
                _sb.AppendLine();
 
            _sb.AppendFormat("{0} {1}", _dateTimeStamp(), status.Trim());
        }
    }