Showing posts with label better coding. Show all posts
Showing posts with label better coding. Show all posts

Wednesday, 16 November 2011

Better ways to validate using Func

public class Movie
    {
        public string Title { get; set; }

        public int ReleaseYear { get; set; }

        public int Length { get; set; }
    }

    public static class MovieValidator
    {
        public static bool IsValid1(Movie movie)
        {
            if (movie.Title.IsNullOrWhiteSpace()) return false;

            if (movie.ReleaseYear < 1900) return false;

            if (movie.Length <= 0) return false;

            return true;
        }

        public static bool IsValid2(Movie movie)
        {
            Func[] rules =
                                {
                                    m => m.Title.IsNotNullOrWhiteSpace(),
                                    m => m.Length > 0,
                                    m => m.ReleaseYear > 1900
                                };

            return rules.All(rule => rule(movie));
        }

        public static bool IsNullOrWhiteSpace(this string value)
        {
            return string.IsNullOrEmpty(value) || value.Length.Equals(0);
        }

        public static bool IsNotNullOrWhiteSpace(this string value)
        {
            return !value.IsNullOrWhiteSpace();
        }
    }

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