Sunday, July 23, 2017

Interpreter Pattern


Interpreter design pattern majorly used with languages and notations. This pattern can be useful to convert from one language to another. This pattern allows to write multiple rules or grammar for language to interpret and extend easily. Interpreter Pattern falls under behavioral pattern of GOF (Gang of Four) pattern.

When to use –


Interpreter Pattern is useful to interpret languages where rules/grammar are complex part which you can easily extend using this pattern. The pattern works on hierarchy of expression. The expression can be classified as Terminal or Non-Terminal. The terminal expression is standalone and can be Interpreted immediately. The non-terminal expression may contain one or more terminal or non-terminal expressions.  

Major components of Interpreter pattern –


Client – This client class responsible for build context, terminal and non-terminal expression objects. It also responsible to make call to interpret method of respective expression.
Context – This is context class used to store input/output data and other information required by expression.
Expression – This is an interface which defines Interpret method which will be implemented by sub classes.
TerminalExpression – This class will implement Expression interface and implements Interpret method.
NonTerminalExpression – This class will implement Expression interface and implements Interpret method similar to TerminalExpression class. This class may contain one or more terminal or non-terminal expressions and invoke Interpret method respectively.

There are many examples available for Interpreter design pattern. I would like to take simple example to understand the intent and implementation for Interpreter design pattern. In my example I would like interpret numbers to words. So I’ll provide number as input and that will be interpreted by pattern to words. Similarly, you can add multiple rules to interpret as per your requirement.

See below example of Interpreter pattern.

Code –
//Client class
class Program
{
    static void Main(string[] args)
    {
        Context ctx = new Context(5642);
        IExpression exp1 = new WordExpression();
        exp1.Interpret(ctx);

        Context ctx1 = new Context(397);
        SubExpression subExp = new SubExpression();
        subExp.Expression1 = new WordExpression();
        subExp.Interpret(ctx1);

        Console.ReadLine();
    }
}
//Context class
public class Context
{
    public int Input { get; set; }
    public Context(int inputValue)
    {
        Input = inputValue;
    }
}
//Expression Interface
public interface IExpression
{
    void Interpret(Context context);
}
//Terminal expression class
public class WordExpression : IExpression
{
    public Dictionary<int, string> numberWord = new Dictionary<int, string>() {
        { 1, "One" }, { 2, "Two" }, { 3, "Three" }, { 4, "Four" }, { 5, "Five" },
        { 6, "Six" }, { 7, "Seven" }, { 8, "Eight" }, { 9, "Nine" }, { 0, "Zero" } };
    public void Interpret(Context context)
    {
        Console.Write("Input Value {0} - ", context.Input);
        string value = context.Input.ToString();
        if (value.Length > 0)
        {
            foreach (char chr in value)
            {
                int number = (int)Char.GetNumericValue(chr);
                Console.Write("{0} ", numberWord[number]);
            }
            Console.WriteLine();
        }
    }
}
//Non-terminal expression class
public class SubExpression : IExpression
{
    public IExpression Expression1 { get; set; }
    public void Interpret(Context context)
    {
        Console.WriteLine("Running Sub Expression 1");
        Expression1.Interpret(context);
    }
}

Output –


As you can see in this example, user set context value to 5642 and Interpret it to words via calling WordExpression which is terminal expression. User also set value another context object ctx1 and set 397 value to Interpret to word via calling SubExpression which is non-terminal expression and contains reference of terminal expression. You can add multiple conversion rules and interpret methods via adding multiple expressions as per your requirement.

You can download full code from Gist.

I hope this article helps you to know more about Interpreter Design Pattern. Please leave your feedback in comments section below.

References –

See Also –

Saturday, June 10, 2017

Async and Await - Asynchronous Programming


Microsoft introduced Async and Await keyword with .Net framework 4.5. Async and Await keyword can be used to improve your application’s overall responsiveness by using asynchronous programming. Asynchronous programming is essential when your application is doing some activity which makes UI unresponsive. You can move that activity to execute asynchronously so it doesn’t block UI and your application will be responsive.

You should consider using Async and Await when you want to keep your application responsive. Async method provides easier way to do long running work in background without blocking thread. Ideally method is decorated with Async keyword should contain one await statement. If you don’t write await statement in Async method, it won’t give compile error but execute as synchronous method.

Below are few things to remember about Async and Await method.

  • The method should contain async modifier.
  • Async method return type should be
    • Task
    • Task<T>
    • Void
  • The method usually includes at least one await expression.

Let’s have a look on below example.

Code –

public partial class MainWindow : Window
{
    public MainWindow()
    {
        InitializeComponent();
    }
    public async void DoSum(int number)
    {
        Console.WriteLine("Task started");
        var result = Calculate(number);
        Console.WriteLine("Task completed");
        if (!result.IsCompleted)
            await result;
        Answer.Text = result.Result.ToString();
        Console.WriteLine(string.Format("Answer is {0}", result.Result.ToString()));
    }
    public async Task<int> Calculate(int number)
    {
        var sum = 0;
        Task myTask = new Task(() =>
        {
            for (int i = 1; i <= number; i++)
            {
                System.Threading.Thread.Sleep(1000);
                sum += i;
            }
        });
        myTask.Start();
        await myTask;
        return sum;
    }

    private void Button_Click(object sender, RoutedEventArgs e)
    {
        if (!string.IsNullOrEmpty(Input.Text))
        {
            Console.WriteLine("Sum process started");
            var number = Convert.ToInt32(Input.Text);
            DoSum(number);
            Console.WriteLine("Sum process completed");
        }
    }
}

Output –

Sum process started
Task started
Task completed
Sum process completed
Answer is 55



As you can see in output, the UI doesn’t block and cursor immediately return to UI. The sum is calculated and updated asynchronously after all execution completed.

Now let’s make little change to this programme and use Task.Wait() method to complete task instead of await. I added myTask.wait() instead of await myTask.

public async Task<int> Calculate(int number)
{
    var sum = 0;
    Task myTask = new Task(() =>
    {
        for (int i = 1; i <= number; i++)
        {
            System.Threading.Thread.Sleep(1000);
            sum += i;
        }
    });
    myTask.Start();
    myTask.Wait();
    return sum;
}

Output –

Sum process started
Task started
Task completed
Answer is 55
Sum process completed

As you can see in output, till the sum is calculated UI is blocked and after that sum process is completed. That means myTask.wait() blocks the thread until task completed.

Difference between await and task.wait() - 

Task.wait blocks the thread and await doesn’t block thread and UI.

I hope this article helps you to know more about async and await. Please leave your feedback in comments below.

You can download full code from Gist.

See also –


Sunday, May 28, 2017

Command Pattern

Command design pattern can be used while designing Menu Items, Tool Bar, Status Bar etc functionalities in application. This pattern can also be useful to provide Undo/Redo like functionalities in application. Command Pattern falls under behavioral pattern of GOF (Gang of Four) pattern.

When to use –


Command Pattern encapsulates request under an object and pass it to the invoker object. The invoker object will pass it to proper command object which will execute the command. This pattern commonly used in UI Buttons, Menu, Tool Bar, Status Bar, Progress Bar etc in many applications. This pattern can also be used to provide multiple level Undo/Redo functionalities for applications.  

Major components of command pattern –


Command – This is an interface which specifies execute action.
Concrete Command – This is concrete class which provides implementation for execute operation.
Client – This class creates and executes commands.
Invoker – This class will ask the command to execute their actions.
Receiver – This class knows how to perform action attached with request.

See below example of Command pattern.

Code –
//Command interface
public interface ICommand
{
    void Execute();
    string Name { get; }
}
//Concrete Command class
public class BuyCommand : ICommand
{
    private Product Product;
    public string Name
    {
        get
        {
            return "Buy Command";
        }
    }
    public BuyCommand(Product product)
    {
        Product = product;
    }
    public void Execute()
    {
        Console.WriteLine("Executing {0}", Name);
        Product.Buy();
    }
}
//Concrete Command class
public class SellCommand : ICommand
{
    private Product Product;
    public string Name
    {
        get
        {
            return "Sell Command";
        }
    }
    public SellCommand(Product product)
    {
        Product = product;
    }
    public void Execute()
    {
        Console.WriteLine("Executing {0}", Name);
        Product.Sell();
    }
}
//Receiver class
public class Product
{
    public int Quantity { get; set; }
    public string Name { get; set; }
    public Product(string prodName, int qty)
    {
        Name = prodName;
        Quantity = qty;
    }
    public void Buy()
    {
        Console.WriteLine("Purchased {0} quantities of {1}", Quantity, Name);
    }
    public void Sell()
    {
        Console.WriteLine("Sold {0} quantities of {1}", Quantity, Name);
    }
}
//Invoker class
public class Portal
{
    public string PortalName { get; set; }
    public Portal(string name)
    {
        PortalName = name;
    }
    public List<ICommand> orderList = new List<ICommand>();
    public void AddOrder(ICommand cmd)
    {
        orderList.Add(cmd);
    }
    public void ExecuteOrder()
    {
        Console.WriteLine("Executing all orders from {0}", PortalName);
        foreach(var order in orderList)
        {
            order.Execute();
        }
    }
}
//Client class
class Program
{
    static void Main(string[] args)
    {
        Product laptop = new Product("Laptop", 2);
        BuyCommand buyLaptop = new BuyCommand(laptop);
        SellCommand sellLaptop = new SellCommand(laptop);

        Portal portal = new Portal("Amazon.in");
        portal.AddOrder(buyLaptop);
        portal.AddOrder(sellLaptop);

        portal.ExecuteOrder();

        Console.ReadLine();
    }
}

Output –




As you can see in this example, user can create receiver object and also create objects for multiple commands. In this example Product is Receiver class and Portal is invoker class. The portal object will invoke BuyCommand and SellCommand as per their order. This example can also be extended to add Undo/Redo functionality via using Stack and modifying invoker class.

You can download full code from Gist.

I hope this article helps you to know more about Command Design Pattern. Please leave your feedback in comments section below.

References –

See Also –