Evil Code #007: Overloads

Time to do a bit of Evil Code again. Let’s look into following set of classes first.

public class BaseParameter { }
public class DerievedParameter :BaseParameter { }

public class BaseClass
{
   public void Foo(DerievedParameter param) => Console.WriteLine($"Inside {nameof(BaseClass)}");
}

public class DerievedClass : BaseClass
{
   public void Foo(BaseParameter param) => Console.WriteLine($"Inside {nameof(DerievedClass)}");
}

The client code looks like following.

var instance = new DerievedClass();
instance.Foo(new DerievedParameter());
instance.Foo(new BaseParameter());

What could be output of the above ? There might be tendency that the one might be inclined to think about an output that resembles following.

Inside BaseClass
Inside DerievedClass

But interestingly that is not quite right. The overload rules ensures that when there is a probable method in the most derieved compile type, the derieved method is chosen, even if there is a better choice in base class. The output of the code would be as following.

Inside DerievedClass
Inside DerievedClass

This is one of the reasons why overloading of base class methods are not recommended.

Let’s take a step further and introduce IEnumerable as method parameters. That’s when things get even more interesting.


public class BaseClass
{
  public void Foo(DerievedParameter param) => Console.WriteLine($"Inside {nameof(BaseClass)}");
  public void Bar(IEnumerable<DerievedParameter> paramList) => Console.WriteLine($"Inside {nameof(BaseClass)}");
}

public class DerievedClass : BaseClass
{
  public void Foo(BaseParameter param) => Console.WriteLine($"Inside {nameof(DerievedClass)}");
  public void Bar(IEnumerable<BaseParameter> paramList) => Console.WriteLine($"Inside {nameof(DerievedClass)}");
}
 instance.Bar(new List<DerievedParameter> { new DerievedParameter(), new DerievedParameter() });
instance.Bar(new List<BaseParameter> { new BaseParameter(), new BaseParameter() });

What could be the output of above ? As per our earlier knowledge, the output would be

Inside DerievedClass
Inside DerievedClass

Well, the actual answer is slightly more complicated. If you are running the code in a framework above 4.0, then you are bang on target. But, if the target framework is lesser, you are in for a surprise.

Inside BaseClass
Inside DerievedClass

The reason for the above scenario is that post 4.0, C# generic interfaces support covariance and contravariance, which wasn’t the case for frameworks prior to that. This results in above scenario.

Happy Coding

Advertisements

Design Pattern : Memento Pattern

Memento Design Pattern allows to capture internal state of an object in an external object and restore it to the desired checkpoint when required, all the while being in compliance with encapsulation.

The Memento Design Pattern comprises of 3 actor classes.

  • Originator : The class which needs to have the ability to store its internal state and restore itself to checkpoint when required.
  • Memento : Contains the internal state of Originator.
  • Caretaker : The shepherd class who is in charge of storing and restoring Originator from Memento.

Let’s go ahead and implement the actor classes

Classic Approach

public class Memento
    {
        public string FName { get; set; }
        public string LName { get; set; }

    }

 public class Caretaker<TSource>
    {

        private IList<Memento> _stateMemory;

        public Caretaker()
        {
            _stateMemory = new List<Memento>();
        }

        public Memento GoBack(int level) =>  _stateMemory.Reverse().Skip(level-1).First();

}

 public class Originator: IOriginator
    {
        public string FName { get; set; }
        public string LName { get; set; }

        public void RestoreState(Memento memento)
        {
            this.FName = memento.FName;
            this.LName = memento.LName;
        }

        public Memento Save()
        {
            return new Memento() {
                LName = this.LName,
                FName = this.FName
            };
        }

    }

The above code showcases the implementation of Memento in its simplest form. You could step up things by making the Memento generic so that it can be reused with other classes as well.

Generic Memento with Serialization.

Instead of defining each properties of the Originator class, we could create a completely generic version by utilizing the powers of serialization.

In the following example implementation of Memento class, I have used ProtoBuf for serializing the class.

public class Memento<TSource>
    {
        private byte[] _state;

        public Memento(TSource data)
        {
            using(var stream = new MemoryStream())
            {
                ProtoBuf.Serializer.Serialize<TSource>(stream, data);
                _state = stream.ToArray();
            }
        }

        public TSource Value
        {
            get
            {
                using(var stream = new MemoryStream(_state))
                {
                    return ProtoBuf.Serializer.Deserialize<TSource>(stream);
                }
            }
        }
    }

The entire source code shown in this example are available in my GitHub.

Pass Property as Expression

I recently needed to pass a property of a class as an expression to a method and read value from it. I found the code that I finally ended up interesting and thought it might be useful to share it here.

void Main()
{
var instance = new Test();
instance.FName= "jia";
PrintMethod(x=>x.FName,instance);
}
public void PrintMethod(Expression<Func> action,dynamic instance)
{
var memberExpr = action.Body as MemberExpression;
var propInfo = memberExpr.Member as PropertyInfo;
var value = propInfo.GetValue(instance);
Console.WriteLine(value);
}

class Test
{
public string FName{get;set;}
public string LName{get;set;}
}

It might look I could have passed the value directly instead of as an expression, but the real life scenario was much complex than one demonstrated in the example.

Design Patterns : Adapter Pattern

There is already a large amount of literature on the Internet which discusses Adapter Pattern. However, the purpose of article is to showcase the implementations of the Adapter Pattern, rather than discussing the application of the pattern. In this post, adapter class is implemented using

1. Inheritance
2. Dependency Injection
3. Generics

Consider your old legacy code, which has a single method, GetEmployeeList.

public interface IHRSoftware
    {
        List<string> GetEmployeeNameList();
    }
    public class HRSoftware : IHRSoftware
    {
        public List<string> GetEmployeeNameList()
        {
            return new List<string>() { "Jia", "Anu", "Sreena" };
        }
    }

Client, consumes the class as follows.

            IHRSoftware hrsoft = new HRSoftware();
            foreach (var item in hrsoft.GetEmployeeNameList())
            {
                Console.WriteLine(item);
            }

Now, it so happened that the Client has gone through an overhaul and is now looking to use a new contract (interface), namely INewAgeSoftware, which exposes a property EmployeeList, replacing the GetEmployeeNameList Method. The interface declaration is as shown below.

    public interface INewAgeHRSoftware
    {
        List<string> EmployeeList { get;  }
    }

You however, would like to use your old existing code, without actually going ahead and making the changes in your legacy code. This is where adapter pattern come in handy. Following are different implementations of Adapter Class

1. Using Inheritance.

    public class AdapterWithInheritence : HRSoftware, INewAgeHRSoftware
    {

        public List<string> EmployeeList
        {
            get
            {
                return this.GetEmployeeNameList();
            }
        }
    }

2. Using Dependency Injection

    public class AdapterWithDI : INewAgeHRSoftware
    {
        private IHRSoftware _HRInstance;
        public AdapterWithDI(IHRSoftware HRSoftInstance)
        {
            _HRInstance = HRSoftInstance;
        }
        public List<string> EmployeeList
        {
            get
            {
                return _HRInstance.GetEmployeeNameList();
            }
        }
    }

3. And Finally, using Generics

    public class AdapterWithGenerics<T> : INewAgeHRSoftware where T : HRSoftware
    {
        private T _HRInstance;
        public AdapterWithGenerics(T Instance)
        {
            _HRInstance = Instance;
        }

        public List<string> EmployeeList
        {
            get
            {
                return _HRInstance.GetEmployeeNameList();
            }
        }
    }

Your new Client class would now look as follows

 Console.WriteLine("Fetching from NewAgeHRSoftware - Adapter via Inheritence");
            INewAgeHRSoftware newhrsoftInheritence = new AdapterWithInheritence();
            foreach (var item in newhrsoftInheritence.EmployeeList)
            {
                Console.WriteLine(item);
            }
            Console.WriteLine("Fetching from NewAgeHRSoftware - Adapter via DI");
            INewAgeHRSoftware newhrsoftDI = new AdapterWithDI(new HRSoftware());
            foreach (var item in newhrsoftInheritence.EmployeeList)
            {
                Console.WriteLine(item);
            }

            Console.WriteLine("Fetching from NewAgeHRSoftware - Adapter via Generics");
            INewAgeHRSoftware newhrsoftGenerics= new AdapterWithGenerics<HRSoftware>(new HRSoftware());
            foreach (var item in newhrsoftGenerics.EmployeeList)
            {
                Console.WriteLine(item);
            }