Tuesday, February 28, 2017

Puzzle - Pricing engine done for BarclayCard

Working as Software consultant than a full time employment is fun and make us up to date. We can see different architectures, coding practices, deployments and other software practices which will definitely help in case we have plans to start own company in future. But the down side is we had to attend interviews more often and there is no guarantee that when our assignment is over the market will be in good condition. Sometimes we may not get the job in the technology we want.

Recently I was attending many interviews. One of those was BarClay card. After 3-4 rounds of interview, I was asked to code a problem in production quality. It assumes 100% test coverage. Below is the problem.

Problem

An online retail company conducts market research to competitively price their products.Surveyed data contains Product code, Competitor and Price.

The retail company uses a Pricing engine which recommends most frequently occurring price. If multiple prices occur frequently, the least amongst them is chosen.

Products are classified based on parameters like Supply, Demand. Possible values are Low (L), High (H)

If Supply is High and Demand is High, Product is sold at same price as chosen price.
If Supply is Low and Demand is Low, Product is sold at 10 % more than chosen price.
If Supply is Low and Demand is High, Product is sold at 5 % more than chosen price.
If Supply is High and Demand is Low, Product is sold at 5 % less than chosen price.

Prices less than 50% of average price are treated as promotion and not considered.
Prices more than 50% of average price are treated as data errors and not considered.

Input consists of number of products, followed by each Product's supply and demand parameters.

followed by number of surveyed prices, followed by competitor prices.

Output must be recommended price for each product.

Sample inputs and outputs

Input 1:
2
flashdrive H H
ssd L H
5
flashdrive X 1.0
ssd X 10.0
flashdrive Y 0.9
flashdrive Z 1.1
ssd Y 12.5

Output 1:
A 0.9
B 10.5

Input 2:
2
mp3player H H
ssd L L
8
ssd W 11.0
ssd X 12.0
mp3player X 60.0
mp3player Y 20.0
mp3player Z 50.0
ssd V 10.0
ssd Y 11.0
ssd Z 12.0

Output 2:

A 50.0
B 12.1

This has to be completed within 2 days.

Solution

There can be different solutions. Below are some point about the one I did.  

  • For achieving pricing used decorator pattern
  • Coded in C#
  • Tests done using mUnit.
  • Mocks done using Moq library
  • Test coverage using ncover
Code is available in the puzzles repo. It took around 6-8 Hrs for me to complete. Please note that they didn't get back to me after I sent this code. So don't just copy paste the code and use for the same puzzle. May be there is something missing.

Tuesday, February 14, 2017

C# Overloading Action & Func and why {} matters

Basics - Overloading

Let us start with basics of overloading. Will the below code compile?
class SomeClass
{
    void Execute()
    {
 
    }
    int Execute()
    {
        return 10;
    }
}
Certainly not. We know that overloading applies to the arguments. Return type is not considered.

Now look at below code. Will it compile?
internal class SomeClass
{
    void Execute(Action handler)
    {
    }
    int Execute(Func<int> worker)
    {
        return worker() ;
    }
}

Don't spend more time. It will compile. For sure. Will it work as expected? That is tricky question. As of our understanding, we are using strong typed languages to avoid many runtime type related issues. So that we can concentrate on our logical issues more.

Consider the below code and guess what happens
internal class SomeClass
{
    internal void Test()
    {
        this.Execute(() =>  Console.WriteLine("Hi"));
    }
    void Execute(Action handler)
    {
        Console.WriteLine("Inside Execute(Action)");
        handler();
    }
    int Execute(Func<int> worker)
    {
        Console.WriteLine("Inside Execute(Func)");
        return worker() ;
    }
}
SomeClass cls = new SomeClass();
cls.Test();
The output will be
Inside Execute(Action)
hi

The problem

If we call Execute as shown below which function will execute?
internal class SomeClass
{
    int num = 0;
    internal void Test()
    {
        this.Execute(() =>  num++);
    }
    void Execute(Action handler)
    {
        Console.WriteLine("Inside Execute(Action)");
        handler();
    }
    int Execute(Func<int> worker)
    {
        Console.WriteLine("Inside Execute(Func)");
        return worker() ;
    }
}
SomeClass cls = new SomeClass();
cls.Test();
The output will be 
Inside Execute(Func)

Why did this happen? Since the C# language support lambda expressions without explicit return value which is just there it assumed that the intention is to return the incremented value. Sometimes the original intention of developer might be just to increment the num variable. Some conflict happened between the developer and the language.

This is kind of OK scenario. Nothing breaks. Lets see little more complex scenario where it cause trouble.
internal class SomeClas
{
    int value = 0;
    internal void Test()
    {
        this.Execute(() => value++ );
    }
    void Execute(Action handler)
    {
        Console.WriteLine("Inside Execute(Action)");
        handler();
        CleanUp();
    }
 
    int Execute(Func<int> worker)
    {
        Console.WriteLine("Inside Execute(Func)");
        int result = 0;
        Execute(() => result = worker());
        return result;
 
    }
    private void CleanUp()
    {
        Console.WriteLine("CleanUp");
    }
}
The developer wants to do some cleanup after Execute. So he added the CleanUp() inside action and he wanted to avoid CleanUp() in all the other functions. Other functions pass action to so that the CleanUp() will be performed for all the Execute() calls. 

The expected output event with call to Execute(<Func>) is
Inside Execute(Func)
InsideExecute(Action)
Hi

But what happens here is infinite loop. Some clever language geeks might have foreseen thie infinite loop. But normal developer will not.

Fix - Use curly brackets / braces / {}

People think that putting {} is time waste and they avoid it where ever possible. But here it would have saved some time. See the fix below.
internal class SomeClas
{
    int value = 0;
    internal void Test()
    {
        this.Execute(() => value++ );
    }
    void Execute(Action handler)
    {
        Console.WriteLine("Inside Execute(Action)");
        handler();
        CleanUp();
    }
 
    int Execute(Func<int> worker)
    {
        Console.WriteLine("Inside Execute(Func)");
        int result = 0;
        Execute(() => { result = worker(); });
        return result;
 
    }
    private void CleanUp()
    {
        Console.WriteLine("CleanUp");
    }
}

Just adding {} into lambda expressions helps us a lot. If Test() used {} it would have avoided one more function call and could have reached to Execute(Action) directly.

Moral of the story is don't hate braces. Omitting those is not going to save lot of time or decrease size of program.

Considering the API

But please be aware that if we are giving these Execute() methods as APIs there is no guarantee that our customers will use {} always. So we have to overload the functions properly.