Refactoring tips: Encapsulate your Condition

We, the developer almost on daily basis write hundreds of line code each day. We write code to perform certain tasks, to achieve certain goals. Most of this task has to be done through some kind of conditional checking. Those who are not aware of clean code they often does these checking in such a way that we easily lost focus from the main part of the program. What I mean is that because of too much conditional checking developer easily get distracted from what they actually intended/planed to do.
Believe me, it’s not rare that you find yourselves agonizing for losing focus from the portion where you actually should have locked your attention.

Refactoring_EncapsulateCondition_2
So some of you might come up with similar picture that I showed below to keep your self focused on the portion of code where you actually should have.

Refactoring_EncapsulateCondition_1
If you find yourself on such scenario you need to do refactoring and that’s where today’s tutorial could be a life saver for you.

REFACTORING technique: Before doing a particular task if you have to go through multiple checking, it’s always good practice to extract the condition into an easy to read property or method.

Lets see this topic with an example:
Before refactoring:

public class HomeController : Controller
{
    public class Blog
    {
        public string Heading { get; set; }
        public int MinLength { get; set; }
        public int MaxLength { get; set; }
        public bool hasPermission { get; set; }
        public DateTime CreatedDate { get; set; }
        public List<int> DraftList { get; set; }

        public void SaveAsDraft(string heading, int minLength, int MaxLength, bool permission, DateTime createdDate)
        {
            if (heading != null && minLength > 5 && MaxLength < 100 && (permission = true) &&
                createdDate <= DateTime.Now.Date)
            {
                Console.WriteLine("Congratulation! I Just saved your life :p ");
                Console.Read();
            }

        }
    }
}
class Program
{
    static void Main(string[] args)
    {
         Blog myBlog = new Blog();
         myBlog.SaveAsDraft("My Heading", 12, 80, true, DateTime.Now.Date);
    }
}

In this example, inside the method SaveAsDraft(string heading, int minLength, int MaxLength, bool permission, DateTime createdDate) before processing certain task we are checking too much things which actually distracted us from the main portion of the body. In the next example I have shown the refactored version of my previous code.

After Refactoring (1) :

    public class Blog
    {
        public string Heading { get; set; }
        public int MinLength { get; set; }
        public int MaxLength { get; set; }
        public bool hasPermission { get; set; }
        public DateTime CreatedDate { get; set; }
        public List<int> DraftList { get; set; }

        private bool ConditionExtender
        {
            get
            {
                return Heading != null && MinLength > 5 && MaxLength < 100 && (hasPermission = true) &&
                       CreatedDate <= DateTime.Now.Date;
            }
        }

        public void SaveAsDraft(string heading, int minLength, int MaxLength, bool permission, DateTime createdDate)
        {
            this.Heading = heading;
            this.MinLength = minLength;
            this.MaxLength = MaxLength;
            this.hasPermission = permission;
            this.CreatedDate = createdDate;

            if (ConditionExtender)
            {
                Console.WriteLine("Congratulation! I Just saved your life :p ");
                Console.Read();
            }
        }
    }

class Program
{
    static void Main(string[] args)
    {
         Blog myBlog = new Blog();
         myBlog.SaveAsDraft("My Heading", 12, 80, true, DateTime.Now.Date);
    }
}

As you can see here in the example, we have encapsulate the whole condition with a property and used the property for further use. This makes the code much more readable. It is obviously good and handy then the previous one.

In case if you don’t need to parse any information from method parameter you could do the refactoring more easily, following code demonstrate this :

public class Blog
    {
        public string Heading { get; set; }
        public int MinLength { get; set; }
        public int MaxLength { get; set; }
        public bool hasPermission { get; set; }
        public DateTime CreatedDate { get; set; }
        public List<int> DraftList { get; set; }

        private bool ConditionExtender
        {
            get
            {
                return Heading != null && MinLength > 5 && MaxLength < 100 && (hasPermission = true) &&
                       CreatedDate <= DateTime.Now.Date;
            }
        }

        public void SaveAsDraft()
        {
            if (ConditionExtender)
            {
                Console.WriteLine("Congratulation! I Just saved your life :p ");
                Console.Read();
            }
        }
    }
class Program
{
    static void Main(string[] args)
    {
          Blog myBlog2 = new Blog
          {
                Heading = "My Heading",
                MinLength = 12,
                MaxLength = 90,
                hasPermission = true,
                CreatedDate = DateTime.Now.Date
            };
            myBlog2.SaveAsDraft();
    }
}

I did not bring SRP(Single Responsible Principle) in consideration while creating this code sample. I only tried to highlightEncapsulate Condition Refactor technique. In a production code you are advised to bring other factors in consideration.

Advertisements

2 thoughts on “Refactoring tips: Encapsulate your Condition

Leave a Reply

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

WordPress.com Logo

You are commenting using your WordPress.com 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