Guess Who?

You may not know the guy in black; but you sure should be knowing the guy in green. Don't know him?

I am not a patron of his philosophies against planned design. But he sure is a great guy with lots of good ideas. It was nice having an hour long chat with him.

Invoking methods with out and ref - Finale !!!

Alright, it is a long wait. And I am going to keep it short.

Recap of the problem: Why did the ref variable in SomeMethod not get the expected result (DayOfWeek.Friday) when called from a different thread?

Boxing. Yes, that is the culprit. Sometimes, it is subtle to note. DayOfWeek is an enum - a value type. When the method is called from a different thread, we put the argument (arg3) in an object array, and that's where the value gets boxed. So we happen to assign the resultant value to the boxed value.

So how do resolve the issue? Simple.......assign the value back from the object array to the ref variable.

int SomeMethod(string arg1,
    string arg2,
    ref DayOfWeek arg3)
{
    if (Dispatcher.CheckAccess())
    {
        var funcDelegate = (Func<string, string, DayOfWeek, int>)SomeMethod;

        var args = new object[] {
            arg1,
            arg2,
            arg3
        };

        int retVal = Dispatcher.Invoke(funcDelegate, args);
        arg3 = args[2];
        
        return retVal;
    }

    // No more implementation
    arg3 = DayOfWeek.Friday;

    return 1234;
}

It may not be worth the wait but it is subtle enough to plant a bug in the code; tough enough to be noted.

Invoking methods with Out and Ref !!!

Straight to code.....

int SomeMethod(string arg1,
    string arg2,
    ref DayOfWeek arg3)
{
    // Wildest implementation!
}

The above method had to be executed on its dispatcher thread. So let unravel a bit of the wildest implementation above.

int SomeMethod(string arg1,
    string arg2,
    ref DayOfWeek arg3)
{
    if (Disptacher.CheckAccess())
    {
        var funcDelegate = (Func<string, string, DayOfWeek, int>)SomeMthod;

        return Dispatcher.Invoke(funcDelegate,
            arg1,
            arg2,
            ref arg3);
    }

    // Wilder implementation!!
}

Before you say anything, yes, the compiler spat the following errors:-

Error 1  No overload for 'SomeMethod' matches delegate 'System.Func<string,string,DayOfWeek,int>

Error 2 The best overloaded method match for 'System.Windows.Threading.Dispatcher.Invoke(System.Delegate, params object[])' has some invalid arguments

Error 3  Argument '4': cannot convert from 'ref System.DayOfWeek' to 'object'

I had some experience with Error 3 earlier, and I had written about it. That came in handy to resolve Error 3. So code is getting better...

int SomeMethod(string arg1,
    string arg2,
    ref DayOfWeek arg3)
{
    if (Disptacher.CheckAccess())
    {
        var funcDelegate = (Func<string, string, DayOfWeek, int>)SomeMethod;

        var args = new object[] {
            arg1,
            arg2,
            arg3
        };

        return Dispatcher.Invoke(funcDelegate, args);
    }

    // Wilder implementation!!
}

Then I was left with one Error 1. I felt I needed a hammer to bang my head to get rid of the error. And it was all nothing but stupidity, or I should have been sleepy. I have been using Func so much that I had got the feeling that it is a keyword (for lack of a better word). To realize that Func delegate had no overload of the type/sort (I was using) took an hour or so.

We can declare a delegate with same name Func as follows:-

public delegate TResult Func<T1, T2, T3, TResult>(T1 arg1,
    T2 arg2,
    ref T3 arg3);

But I declared with a different name to avoid confusion and clear up my misconception. Now the wildness of the implementation was almost unraveled except the method was not working as expected. Let us see the code cleared of all compiler errors:-

int SomeMethod(string arg1,
    string arg2,
    ref DayOfWeek arg3)
{
    if (Disptacher.CheckAccess())
    {
        var funcDelegate = (Func<string, string, DayOfWeek, int>)SomeMthod;

        var args = new object[] {
            arg1,
            arg2,
            arg3
        };

        return Dispatcher.Invoke(funcDelegate, args);
    }

    // No more implementation
    arg3 = DayOfWeek.Friday;

    return 1234;
}

What is that expected behavior that is not experienced? And what is the reason? I will write about in a short while cuz my beer stole the preference.

Hint: Why does not the client code (Code calling SomeMethod) get the correct value in DayOfWeek argument? In our case, DayOfWeek.Friday.

Thinking Currying !!!

Currying is a mathematical concept based on lambda calculus. It is a technique of operating on a function (taking multiple arguments) by splitting and capable of chaining into a series of single argument functions. It is very similar to what a human would attempt to do on paper. For example, if you have to add numbers 1 through 10, what would you do? Class II mathematics....zero in hand, one in the mind, add 0 and 1, so 1 in the mind, then 2 in the hand, ...up to 10. So we compute the addition with one argument at a time.

In the programming world, it is realized by transforming a n-arguments function into a (n-1) arguments function, which takes the remaining one argument. This transformation when applied recursively on each of the single argument functions is the chaining of single argument functions that I discussed earlier. Needless to say, currying is a gift of the functional programming world. In simple words, functional programming is about building functions from other functions, and so functions are treated as first class citizens (like data).

If currying is just transforming a n arguments function into a single argument function, then extension method too is an example of currying.

public static bool Replace<T>(this IList<T> srcList, int position, T item) 
{ 
   // Imagine an implementation here.... 
}

So you would be using the Replace<T> above without explicitly passing the source list to the method; one argument less.

list.Replace(2, newItem);
// instead of Replace(ilistObj, 2, newItem) if extension method was not invented.

Isn't that right? Yes, but that is not the currying from the conventional standpoint of functional programming.

For samples, we will not use the devil (any functional programming language) itself; instead we will use C#, which provides functional programming facilities. Alright, let us curry.

int Add(int x, int y) 
{ 
   return x + y; 
} 

Or to be 'functional', we may (re)write: Func<int, int, int> adderFunc = (x, y) => x + y;

To curry out an increment function, we would write as follows:-

Func<int, Func<int, int>> Incrementer() 
{ 
   return num => Add(num, 1); 
} 

and we use it is as follows:-

var inc = Incrementer(); 
Console.WriteLine(inc(5)); 
Console.WriteLine(inc(12)); 

Is that not better and wise than writing Sum(5, 1)?

If currying is just transforming a n-arguments function into a single argument function, then we should be able to write a generic currying function.

Func<T1, Func<T2, TResult>> Curry<T1, T2, TResult>(Func<T1, T2, TResult> fn) 
{ 
   return x => y => fn(x, y); 
} 

Func<int, Func<int, int>> Adder = Curry(Add); 
var Incrementor = Adder(1); 
var i = Incrementor(5); 

when we may not have actually  encountered a compelling situations to use this in the past

But isn’t this all cryptic? So why would we want to do all such cryptic things when we have not encountered any such situation....in the past? Actually we have.

When simple principles are tough for us to understand, it is our grandma who helps us. Our grandma here is C++; although grandma called it binding.

In C++, many STL algorithms require a functor (roughly equivalent to a function definition) with one argument, where as the desired function was a two or more arguments function. Then we use std::bind1st or std::bind2nd to curry it into unary function.

For instance, the count_if algorithm calculates the number of elements in a sequence that satisfy the predicate, which happens to be a unary function. Suppose we want to count the even numbers in a collection of whole numbers (and imagine this to be a tough calculation). If there was a function that could take a number and return true if it was an even number, it could be fed to count_if. But what if we had a function like the one below - a two argument function.

bool IsDivisible(int number, int divisor)
{
   return number % divisor == 0;
}

The functor we need is nothing but an IsDivisible function with the second argument as 2. We could write an IsEven function which in turn calls IsDivisible. But that could be tedious one we were write such wrappers for a function with 10 arguments. In situations like this, we curry. In C++, we (use) bind.

std::bind1st - A helper template function that creates an adaptor to convert a binary function object into a unary function object by binding the first argument of the binary function to a specified value.
std::bind2nd - A helper template function that creates an adaptor to convert a binary function object into a unary function object by binding the second argument of the binary function to a specified value.

So in our case, we will be using bind2nd, as follows:-

std::vector<int> wholeNumbers =  {
   1, 2, 4, 5, 6, 7, 9, 10, 12, 15, 17, 20
};

std::count_if(wholeNumbers.begin(),
   wholeNumbers.end(),
   std::bind2nd(IsDivisible, 2));

Unfortunately, C++ stayed with bind1st and bind2nd, and currying was not that evident or securely possible since C++ did not have required facilities, say something like delegates. So the concept has been in vogue from long time ago. Like every paradigm in programming, functional programming requires (re)aligning our thought (process). Instead of treating functions as just reusable pieces of code (as considered in procedural programming), they have to conceived as the input processors, which may return either data or whole new function; shrinked?

So that is a quick thought on Currying. I will try to share a few other thoughts related to currying, slightly expanding to functional programming but later.

Quiz - (Journey through templates, SFINAE and specialization) !!!

template<typename A, typename B>
class TClass
{
public: TClass()
        {
        }

        // Overload #1
public: std::string SomeMethod(A a, B b)
        {
           std::ostringstream ostr;
           ostr << a << "-" << b;
           return ostr.str();
        }

        // Overload #2
public: std::string SomeMethod(B b, A a)
        {
           std::ostringstream ostr;
           ostr << b << "-" << a;
           return ostr.str();
        }
};

So that is a template class with SomeMethod overloads. Why would somebody write such a class? Imagine it is an adder class, and the method overloads could used to add with parameters specified in either order. Following is the way one could use the above (based on the adder example):-

int i = 45;
double d = 12.3f;

TClass<int, float> t1;
const std::string idText = t1.SomeMethod(i, d); // This calls Overload #1
const std::string diText = t2.SomeMethod(d, i); // This calls Overload #2

Seems cool until you try this simple thing

TClass<int, int> t2;
const std::string idText = t1.SomeMethod(i, i);

The mighty C++ compiler will complain

Error 1 error C2535: 'std::string TClass<A,B>::SomeMethod(A,B)' : member function already defined or declared <YourFileName.cpp>

A well-tuned C++ programmer would have guessed already how to resolve the situation. But we are are going to discuss a few other things related to the problem, besides the solution.

Part 1: Non-member Functions

Let us say TClass was written for hosting SomeMethod overloads. By that I mean to say SomeMethod overloads are self-sufficient and could be made non-member functions (as global methods or methods inside a namespace).

namespace SF
{
   // Overload #1
   template<typename A, typename B> std::string SomeMethod(A a, B b)
   {
      std::ostringstream ostr;
      ostr << a << "-->" << b;
      return ostr.str();
   }
   
   // Overload #2
   template<typename A, typename B> std::string SomeMethod(B b, A a)
   {
      std::ostringstream ostr;
      ostr << b << "-->" << a;
      return ostr.str();
   }
}

Hang on. The above code will still result in a compilation error for SomeMethod<T, T>; same type. We are going to now resolve this situation using one of the tough and less-used powers of C++. We are going have the two overloads, make some changes to one overload using SFINAE principle, and allow instantiation\use of SomeMethod using like or different types. That is not a typo; I spelt it right - SFINAE, a.k.a Substitution Failure Is Not An Error.

SFINAE is a principle adopted by the C++ compiler to prevent resulting in a compilation error when preparing the set of candidate overloads for a particular template instantiation. It is widely used for deliberately excluding one or more template overloads based on some condition. The principle is applied only in the case of templates.

In our case, when SF::SomeMethod<AnyT, AnyT> is called, right now both the overloads are successful candidates. That is why the compiler complains about method redefinition. Suppose we wrote the code in a way so as to detect that the two template types passed are same ("the condition"), and we exclude one of the overloads (consider overload #2). This would help us bind to the one method (overload #1). Well, SFINAE is exactly for such purposes. Alright, let us (re)write code...

// Alternatively, you can use EnableIf facility from Boost library
template<bool Condition, typename T = void>
struct EnableIf
{
   typename T Type;
};

template<typename T>
struct EnableIf<false, T>
{
};

// Alternatively, you can use IsSameType facility from Boost or Loki library
template<typename A, typename B>
struct IsSameType
{
   enum { Result = false };
};

template<typename A>
struct IsSameType<A, A>
{
   enum { Result = true };
};

template<typename A, typename B>
struct AreDifferentTypes
{
   enum { Result = !(typename IsSameType<A, B>::Result) };
};

namespace SF
{
   // Overload #1    
   template<typename A, typename B> std::string SomeMethod(A a, B b)
   {
      std::ostringstream ostr;
      ostr << a << "-->" << b;
      return ostr.str();
   }
   
   // Overload #2
   template<typename A, typename B>
   typename EnableIf<AreDifferentTypes<A, B>::Result, std::string>::Type // Evaluates to the return type
      SomeMethod(B b, A a)
   {
      std::ostringstream ostr;
      ostr << b << "-->" << a;
      return ostr.str();
   }
}

We have tweaked overload #2 such that while creating the candidate set for overload resolution, it produces an error when the template parameter types substituted are same. AreDifferentTypes<A, B>::Result will evaluate to false if the template parameters are of the same type, as a result of which the specialized version of EnableIf (EnableIf<false, T>) is chosen which does not define the Type member typedef. This is spotted as an error when selecting candidates for overload resolution but ignored (for a good cause). Now the compiler will be able to bind to the only candidate found (Overload #1). So now you can enjoy using SomeMethod:-

void main()
{
   int i = 12;
   float f = 34.56;
   
   const std::string dtText = SF::SomeMethod<int, float>(i, f);
   const std::string stText = SF::SomeMethod<int, int>(i, i);
}

Part 2 - Member Functions

I could feel the SFINAE hangover. Unfortunately, the SFINAE will not work with template member functions. So before we see how to solve our problem in discussion for member functions, let us see why SFINAE will not come for rescue.

For a template method instantiation\call, the C++ compiler first searches for methods (matching the name), which could be a potential candidate for binding to the method call. During this step, the methods are inspected for the signature (and not code). They are rejected if they are detected to produce an error. In the earlier case, AreDifferentTypes returning false thereby making EnableIf devoid of the typedef Type was the error. So this principle is applied to methods (matching the name) with valid signature. In other words, there cannot be an ill-formed method signature from a template instantiation.

In the case of non-member functions (above), the method decorated with EnableIf will always be considered to have a valid method signature. In other words, depending on the template parameters, the method will get an appropriate return type; although it may fail to be a successful candidate for overload resolution (using SFINAE) when the template parameters are of the same type. Irrespective of whether a template method or method inside a template class is used, the compiler will stop with errors if it has an invalid signature.

Aimed with the above information, let us rewrite the TClass as follows and understand why the principle will not work for template member functions.

template<typename A, typename B>
class TClass
{
public: TClass()
        {
        }

        // Overload #1
public: std::string SomeMethod(A a, B b)
        {
           std::ostringstream ostr;
           ostr << a << "-->" << b;
           return ostr.str();
        }

        // Overload #2
public: typename EnableIf<AreDifferentTypes<A, B>::Result, std::string>::Type
           SomeMethod(B b, A a)
        {
           std::ostringstream ostr;
           ostr << b << "-->" << a;
           return ostr.str();
        }
};

You will see a whole of bunch of errors, of which we should be interested in the following:-

Error 1 error C2039: 'Type' : is not a member of 'EnableIf<Condition,T>' <FileName> <Line>

Error 5 error C2556: 'int TClass<A,B>::SomeMethod(B,A)' : overloaded function differs 
only by return type from 'std::string TClass<A,B>::SomeMethod(A,B)' <FileName> <Line>

A template is almost a dead piece of code, until instantiated. Try writing a template method (with valid signature) that has few favorite quotes from Romeo Juliet (instead of C++ code) as its body. Unless you don't instantiate\call that method, the compiler will be tolerant. When a template is instantiated, that's when the real code to bind to is cooked specifically for the parameter types. And when that is done, any invalid code will be flagged as an error. So when the SomeMethod (overload #2) is cooked for TClass<AnyT, AnyT> instantiation, it results in an invalid code. That is our Error 1 above - Trying to access a member that does not exist. This means that the SomeMethod is being cooked without a return type being specified. In C++ (like in C) if you don't specify a return type, it is assumed to be int. Since there already is an other SomeMethod with the same method signature but just differing in the return type, Error 5 above is raised.

Another category of member functions are static template methods inside a non-template class, which are equivalent to non-members. Let us leave applying the above explanation to this category as an exercise.

Does that mean we don't have a solution? No, not using SFINAE. But by another friend - Template Specialization.

template<typename A, typename B>
class TClass
{
public: TClass()
        {
        }

        // Overload #1
public: std::string SomeMethod(A a, B b)
        {
           std::ostringstream ostr;
           ostr << a << "-" << b;
           return ostr.str();
        }

        // Overload #2
public: std::string SomeMethod(B b, A a)
        {
           std::ostringstream ostr;
           ostr << b << "-" << a;
           return ostr.str();
        }
};

template<typename A>
class TClass<A, A>
{
public: TClass()
        {
        }

public: std::string SomeMethod(A a, A b)
        {
           std::ostringstream ostr;
           ostr << a << " - " << b;
           return ostr.str();
        }
};

So, we have solved the problem!

Missing MI !!!

We all know C# does not offer multiple inheritance but offers arguments that programmers can live without it. It is true in almost all cases, especially all cat and animal or employee and manager projects. I have seen a few cases where if C# offered multiple inheritance, the solution would have been natural, elegant and succinct.

Imagine that I have a component (UI, non-UI, doesn't matter). You can make calls into the component, which does some interesting work for you. Imagine that the component takes an interface IComponentCallback to notify its parent. So I would do is have my parent class derive from IComponentCallback interface and pass this to the component. The code would look something like this:-

interface IComponentCallback
{
   void Callback1();
   bool Callback2();
   void Callback3(int old, int new);
}

class SomeComponent
{
   // The parent on whom callbacks are made
   private IComponentCallback _parent = null;
   
   public SomeCompoent(IComponentCallback cmpCallback)
   {
      // Imagine that callbacks would not be made      
      // if cmpCallback is null
      
      _parent = cmpCallback;
   }
   
   // Other methods in which _parent shall be used
   // for making the callbacks.
}

class Parent : IComponentCallback
{
   private SomeComponent _someComponent = null;
   
   public Parent()
   {
      _someComponent = new SomeComponent(this as IComponentCallback);
   }
   
   #region IComponentCallback methods implementation
   
   void IComponentCallback.Callback1()
   {
      // Code making use of this callback
   }
   
   bool IComponentCallback.Callback2()
   {
      // Possible code to provide some    
      return true;
   }
   
   void Callback3(int old, int new)
   {
      // Code making use of old\new
   }
   
   #endregion
}

void Main(string[] args)
{
   // .... code ...
   
   // Instantiating a parent which would create 
   // SomeComponent and establish itself as the
   // callback sink.
   Parent p = new Parent();
   
   // ... Code ...
}

This is a typical case where the instantiator is the callback sink. And this case is natural and usual. There may be cases where one class instantiates and holds the component while a different class acts as the callback sink. That... is not the topic of our discussion.

Now imagine our parent is a Form class. I am sure you might have come across this case where a Form hosts a UI or non-UI component and you want the callback sink as methods in your class so that you can update the UI directly. What follows may necessarily be the common case but I encountered it more than a few times. In our application, any parent could host the component. There were certain things common to do when processing the callback and hence we wrote a (base) class implementing IComponentCallback and which represents the component callback sink. Since C# does not support MI, any of our custom forms could not be derived from the callback sink class, since they are already derived from System.Windows.Form class.

Now it is not wise to argue that one may use delegates or that this implementation is bad or this is a corner case. I have practically encountered this a few times where the component we are talking about is from a third party. In some cases, the component was our own and implemented for callback mechanism, called plugin, whose intent is quite opposite to event notification. Most others might have "No MI in C#" in mind and would have the sink class as a member of the Form (parent). I don't see that natural but compulsion.

Anyways, a case exists, and of course you can live without MI.