Using lambdas for handling change

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:


        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);







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)
        //Other Handlers ...
        private void AddDateTimeStampToEntry(string status)
            if (_sb.Length > 0)
            _sb.AppendFormat("{0} {1}", _dateTimeStamp(), status.Trim());

Tags: ,

Leave a Reply

Fill in your details below or click an icon to log in: Logo

You are commenting using your account. Log Out / Change )

Twitter picture

You are commenting using your Twitter account. Log Out / Change )

Facebook photo

You are commenting using your Facebook account. Log Out / Change )

Google+ photo

You are commenting using your Google+ account. Log Out / Change )

Connecting to %s

%d bloggers like this: