ArtsAutosBooksBusinessEducationEntertainmentFamilyFashionFoodGamesGenderHealthHolidaysHomeHubPagesPersonal FinancePetsPoliticsReligionSportsTechnologyTravel
  • »
  • Technology»
  • Computers & Software»
  • Computer Science & Programming

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

Updated on February 8, 2013

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. (

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.


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

© 2012 softomiser


    0 of 8192 characters used
    Post Comment

    No comments yet.


    This website uses cookies

    As a user in the EEA, your approval is needed on a few things. To provide a better website experience, uses cookies (and other similar technologies) and may collect, process, and share personal data. Please choose which areas of our service you consent to our doing so.

    For more information on managing or withdrawing consents and how we handle data, visit our Privacy Policy at: ""

    Show Details
    HubPages Device IDThis is used to identify particular browsers or devices when the access the service, and is used for security reasons.
    LoginThis is necessary to sign in to the HubPages Service.
    Google RecaptchaThis is used to prevent bots and spam. (Privacy Policy)
    AkismetThis is used to detect comment spam. (Privacy Policy)
    HubPages Google AnalyticsThis is used to provide data on traffic to our website, all personally identifyable data is anonymized. (Privacy Policy)
    HubPages Traffic PixelThis is used to collect data on traffic to articles and other pages on our site. Unless you are signed in to a HubPages account, all personally identifiable information is anonymized.
    Amazon Web ServicesThis is used to collect data on traffic to articles and other pages on our site. Unless you are signed in to a HubPages account, all personally identifiable information is anonymized. (Privacy Policy)
    CloudflareThis is used to quickly and efficiently deliver files such as javascript, cascading style sheets, images, and videos. (Privacy Policy)
    Google Hosted LibrariesJavascript software libraries such as jQuery are loaded at endpoints on the or domains, for performance and efficiency reasons. (Privacy Policy)
    Facebook LoginYou can use this to streamline signing up for, or signing in to your Hubpages account. No data is shared with Facebook unless you engage with this feature. (Privacy Policy)
    PaypalThis is used for a registered author who enrolls in the HubPages Earnings program and requests to be paid via PayPal. No data is shared with Paypal unless you engage with this feature. (Privacy Policy)
    Google AdSense Host APIThis service allows you to sign up for or associate a Google AdSense account with HubPages, so that you can earn money from ads on your articles. No data is shared unless you engage with this feature. (Privacy Policy)
    Google Custom SearchThis is feature allows you to search the site. (Privacy Policy)
    Google MapsSome articles have Google Maps embedded in them. (Privacy Policy)
    Google ChartsThis is used to display charts and graphs on articles and the author center. (Privacy Policy)
    Google YouTubeSome articles have YouTube videos embedded in them. (Privacy Policy)
    VimeoSome articles have Vimeo videos embedded in them. (Privacy Policy)
    MavenThis supports the Maven widget and search functionality. (Privacy Policy)
    Google AdSenseThis is an ad network. (Privacy Policy)
    Google DoubleClickGoogle provides ad serving technology and runs an ad network. (Privacy Policy)
    Index ExchangeThis is an ad network. (Privacy Policy)
    SovrnThis is an ad network. (Privacy Policy)
    Facebook AdsThis is an ad network. (Privacy Policy)
    Amazon Unified Ad MarketplaceThis is an ad network. (Privacy Policy)
    AppNexusThis is an ad network. (Privacy Policy)
    OpenxThis is an ad network. (Privacy Policy)
    Rubicon ProjectThis is an ad network. (Privacy Policy)
    TripleLiftThis is an ad network. (Privacy Policy)
    Say MediaWe partner with Say Media to deliver ad campaigns on our sites. (Privacy Policy)
    Remarketing PixelsWe may use remarketing pixels from advertising networks such as Google AdWords, Bing Ads, and Facebook in order to advertise the HubPages Service to people that have visited our sites.
    Conversion Tracking PixelsWe may use conversion tracking pixels from advertising networks such as Google AdWords, Bing Ads, and Facebook in order to identify when an advertisements has successfully resulted in the desired action, such as signing up for the HubPages Service or publishing an article on the HubPages Service.
    Author Google AnalyticsThis is used to provide traffic data and reports to the authors of articles on the HubPages Service. (Privacy Policy)
    ComscoreComScore is a media measurement and analytics company providing marketing data and analytics to enterprises, media and advertising agencies, and publishers. Non-consent will result in ComScore only processing obfuscated personal data. (Privacy Policy)
    Amazon Tracking PixelSome articles display amazon products as part of the Amazon Affiliate program, this pixel provides traffic statistics for those products (Privacy Policy)