In a search for flawless Visitor (design pattern) Part II

Part I | Part II | Part III | Part IV

The Goal

Following our discussion from Part I we can state our requirements for prospective flawless Visitor (or whoever else it would be) and name it “Object” for now.

While the goal remains the same - to dispatch subtypes of some polymorphic structure to corresponding processing methods (processors) - we would like to have

  1. Separation of concerns between Object and set of processors.
  2. Complete absence of dependencies between object and polymorphic structure and vice versa.
  3. One generic Object for any polymorphic structure.
    That is we do not want to create another subclass for Object each time we have to introduce a new set of actions.
  4. Ability to map processors incrementally at run time. That is having any processor to be pluggable, which adds even more flexibility to architecture design.
    We want to be able to set as many processors as we’d like to, without any concerns about other subtypes of polymorphic structure, which might be just skipped from processing.
  5. Ability to package final code in a shared library as self-contained implementation and have no reasonable needs to ever modify its code in a future. (Comply with OCP)

It looks quite ambitious. But let’s see, if we can get there.


The Idea

After close examination and trials of several ideas, which didn’t fulfill all requirements, the following one appeared to be the most promising.

  1. Establish generic Class, the generic type parameter of which we will use to indicate to our “Object” the base type of polymorphic structure.
  2. Implement mapping between Types to be processed and corresponding Methods (actions) with generic Dictionary.
  3. Declare generic public method for setting/mapping desired Methods (actions) for subtypes of polymorphic structure.
  4. Declare generic public method with parameter for incoming subtype of polymorphic structure to be processed. (Kind of Visitor’s “Visit” method)

But there are couple of challenges have to be solved in order to implement it.


Solving Challenges

  1. The problem with Polymorphic assignments to variables of generic delegate types.
  2. The challenge of retrieving correct subtype for corresponding Method (action) without type checking.

Since we have to map Methods (actions) we have to use delegates to store those methods.

And since we deal with polymorphic structure, it seems like we have to leverage polymorphism here as well and be able to assign different methods allotted for any subtype to a variable of some delegate base type.

While those assignments are trivial with other types, they are tricky with generic delegates due to Covariance and Contravariance in Generics. (http://msdn.microsoft.com/en-us/library/dd799517.aspx)

Let’s say, had we choose to work with Action<T> delegate we have a problem to assign instance of Action<TDerived> type to a variable of Action<TBase> type due to Contravariance of Action<T> delegate.

(For details see the most rated answer to question here.)

And indeed the method, which represented by Action<TDerived> delegate and promises to accept the TDerived type as a parameter does not fulfill the commitment of method, represented by Action<TBase> to accept related supertype if we try substitute the former in place of the latter. So it won’t work.

In opposite to Action<T> the Func<T> delegate is covariant, so we will not have problem with assignments and at first glance it looks like we can use Func<T> delegate to solve our second challenge somehow making the function represented by Func<T> delegate to return the correct subtype of polymorphic structure, so we can then dispatch it to correct Method (action).

But unfortunately it won’t work either.

When we invoke the function, that supposed to return correct subtype, but being assigned to Func<TBase> delegate – we will always get TBase type instead, since this is what this delegate makes all assigned to it functions to return.

Therefore we have achieved nothing here again.

So let’s get back to Action<T> and start all over again. May be we are missing something? Let’s take a closer look on our problem.


Overcoming contravariant nature of Action<T> delegate

From one side we Have to assign to variable of Action<TBase> delegate the function which takes only TBase as parameter.

From the other side we have to somehow get into our system the processing Method (operation), which takes TDerived type as a parameter (not to mention retrieving correct subtype for Method (operation) somewhere in the middle of the road from one side to another).

Had we choose to work with Action<T> delegate as a parameter in generic public method which we were going to declare for our magic “Object” as stated in statement 3 from section above (named “The Idea”), we would very conveniently pass for mapping our Method (operation) as an argument.

Therefore both sides of the problem (with a little nuisance in the middle) appear to be located in that method:

public void SetActionFor<T>(Action<T> action) where T : TBase

Stop for a moment and think!

The solution might not appear in front of you right away from the beginning but it is amazingly simple and charming at the same time when you get it!

*************************************************

We are going to solve it with Adapter Design Pattern to be implemented as anonymous method, (lambda expression). At the same time we will solve our little nuisance in the middle - retrieving correct subtype for Method (operation), using generic type parameter <T> as a "hint".

public void SetActionFor<T>(Action<T> action) where T : TBase
{
    //substitutes (for now) storing slot 
    //in generic Dictionary:
    Action<TBase> ActionStoringSlot;  

    ActionStoringSlot = baseType => action((T)baseType);
}

We assign lambda expression with signature expected by delegate to variable of Action<TBase> type and within this lambda expression we make a call to Method (action), casting our baseType to type we get from generic parameter, right before it gets in to its processing Method. The Method (action) - is who dictates what subtype should be and this is good - our "Object" does not depend on any type therefore.

We solved the assignments problem by eliminating the need of polymorphic assignment altogether by means of encapsulating methods for subtypes into lambda expression which steps forward as a method that takes basetype as a parameter. By encapsulating Methods (actions) for subtypes - lambda expression always adapts those methods to be assignable to the variable of Action<TBase> delegate.

We will see what we have finally got in Part III.


Alex Movshovich.

Software Developer.

License

This article, along with any associated source code and files, is licensed under The Code Project Open License (CPOL)

© 2012 softomiser

More by this Author


Comments

No comments yet.

    Sign in or sign up and post using a HubPages Network account.

    0 of 8192 characters used
    Post Comment

    No HTML is allowed in comments, but URLs will be hyperlinked. Comments are not for promoting your articles or other sites.


    Click to Rate This Article
    working