Wednesday, 16 November 2011

Named Parameters, Extension methods and Fluent API's

Let's see how above three techniques help us to write a better code

    public interface ITask
    {
    }

    public class CopyFile : ITask
    {
    }

    public class ScheduledTask
    {
        public ScheduledTask(ITask task, TimeSpan runEvery, TimeSpan expiresOn)
        {
            this.Task = task;
            this.RunEvery = runEvery;
            this.ExpiresOn = expiresOn;
        }

        public ITask Task { get; set; }

        public TimeSpan RunEvery { get; set; }

        public TimeSpan ExpiresOn { get; set; }
    }

    public static class Worker
    {
        public void DoWork()
        {
            //var task = new ScheduledTask(new CopyFile(),
            //                    runEvery : new TimeSpan(0,0,5),
            //                    expiresOn : new TimeSpan(0,0,5));

             var task = new ScheduledTask(new CopyFile(),
                                runEvery : 2.Minutes(),
                                expiresOn : 3.Days());

             var completed = 2.Minutes().Ago();
        }

        public static TimeSpan Minutes(this int value)
        {
            return new TimeSpan(0, 0, value, 0);
        }

        public static TimeSpan Days(this int value)
        {
            return new TimeSpan(value, 0, 0, 0, 0);
        }

        public static DateTime Ago(this TimeSpan value)
        {
            return DateTime.Now - value;
        }
    }

No comments: