Saturday, November 21, 2015

Avoid multiple If-else Or Switch in decision making flow.

Sometime multiple if-else or switch can increase code smell. It’s always Good practice to avoid those to decrease confusion and increase code readability.

In this article we will implement some pattern which can replace simple if-else or switch case. Let’s take one small example to implement same.

    public interface IMessage
    {
        void Send();
    }

    public class SMS : IMessage
    {
        public void Send()
        {
            System.Console.WriteLine("SMS Sending..");
        }
    }
    public class Mail : IMessage
    {
        public void Send()
        {
            System.Console.WriteLine("Mail Sending..");
        }
    }

We have implement IMessage in SMS and Mail classes. Now, here is an Enum to choose the Message type.

enum MessageType { Sms, Mail };

Here is the actual logic to call appropriate class.

      public static void Main(String[] args)
        {
            Dictionary<MessageType, IMessage> ObjectFactory =
new Dictionary<MessageType, IMessage>
            {
                { MessageType.Sms, new SMS() },
                { MessageType.Mail, new Mail() }
            };

            System.Console.WriteLine("0: For SMS, 1: Mail");

            int ReadType = Convert.ToInt32(
            System.Console.ReadLine());

            ObjectFactory[(MessageType)ReadType].Send();
           

            System.Console.ReadLine();
        }

The implementation is very simple one. Just we are maintaining one dictionary by containing object of concrete implementation of the IMessage interface.

Once user input some value, we are getting appropriate object and calling respective function. Here is Full code implementation with output.

using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;

namespace Console
{
    public interface IMessage
    {
        void Send();
    }

    public class SMS : IMessage
    {
        public void Send()
        {
            System.Console.WriteLine("SMS Sending..");
        }
    }
    public class Mail : IMessage
    {
        public void Send()
        {
            System.Console.WriteLine("Mail Sending..");
        }
    }

    enum MessageType { Sms, Mail };
    class Program
    {
        public static void Main(String[] args)
        {
            Dictionary<MessageType, IMessage> ObjectFactory 
                  = new Dictionary<MessageType, IMessage>
            {
                { MessageType.Sms, new SMS() },
                { MessageType.Mail, new Mail() }
            };

            System.Console.WriteLine("0: For SMS, 1: Mail");

            int ReadType = Convert.ToInt32(
            System.Console.ReadLine());
            ObjectFactory[(MessageType)ReadType].Send();
           

            System.Console.ReadLine();
        }
    }
}


No comments:

Post a Comment