The Visitor Pattern – Design patterns in practice I.

It is a common problem that a feature involves of processing elements of a class hierarchy based on their exact type. Using virtual functions is a plausible solution but can be cumbersome if too many features are implemented that way. To decouple the hierarchy of entities and the processing algorithm Visitor pattern is the way to go.

Example 1: There are several types of customers stored in the system. Depending on the type of customer you want to send an Xmas greeting. Enterprise customers are contacted by email, SMS goes to private customers and a memo is added to an external CMS system for every long-term customer. The feature must be designed without significantly changing the existing class structure and keep it as flexible as possible (later Eastern greetings might be needed).

Example 2: In a banking application different sort of account types are handled. At the end of the month a report must be generated per account including account type dependent information. The format of these reports can vary. The reporting process should be easily configurable and open for future changes.

Solution: The visitor pattern applies a different approach. The feature is implemented in a Visitor class that is dynamically called from entities.  As a consequence the feature and the class structure of entities are well separated.

Visitor Pattern UML

UML draft of the Visitor Pattern

Alternative solution 1: An obvious way is to use virtual methods. A base entity class declares an abstract virtual method and every derived class implements it. Then every client call is resolved to the proper instance. This solution is pretty straightforward; however, it affects the class structure even if the implemented feature is not strongly related to it. It can be also cumbersome to make the feature configurable.

Alternative solution 2: Another possibility is to use a static utility method that takes an entity as its parameter. The body of the method is based on a large switch – case statement over the type of the entity. This is a simple and effective solution if the class hierarchy of entities are simple and re-usability is not an issue.

Sample: Below you can find a sample code that corresponds to Example 1.

namespace VisitorPattern
{
    class Client
    {
        static void Main(string[] args)
        {
            Customer[] customers = new Customer[]{};
            XmasCardVisitor xmasCardVisitor = new XmasCardVisitor();
            foreach (Customer c in customers)
            {
                c.Accept(xmasCardVisitor);
            }
        }
    }

    public interface IVisitor
    {
        void Visit(EnterpriseCustomer c);
        void Visit(PrivateCustomer c);
        void Visit(LongTermCustomer c);
    }

    public class XmasCardVisitor : IVisitor
    {
        public void Visit(EnterpriseCustomer c)
        {
            //TODO
        }

        public void Visit(PrivateCustomer c)
        {
            //TODO
        }

        public void Visit(LongTermCustomer c)
        {
            //TODO
        }
    }

    public abstract class Customer
    {
        public abstract void Accept(IVisitor visitor);
    }

    public class EnterpriseCustomer : Customer
    {
        public override void Accept(IVisitor visitor)
        {
            visitor.Visit(this);
        }
    }

    public class PrivateCustomer : Customer
    {
        public override void Accept(IVisitor visitor)
        {
            visitor.Visit(this);
        }
    }

    public class LongTermCustomer : Customer
    {
        public override void Accept(IVisitor visitor)
        {
            visitor.Visit(this);
        }
    }

}

ASP.NET Page Life Cycle Events Order

There are multiple phases that an ASP.NET page goes through while the web server processes it. Understanding the page life cycle and the governing events are a vital part of  development. Developers are likely to know the order of page events but often fail when asked the order of occurrence of a single event in a page with all its child controls.

An ASP.NET page consists of 3 major components: the content page, the master page(s) and the embedded server controls. ( Server controls have the runat=”server” attribute. ) The visual hierarchy is pretty straightforward. A master page can enclose server controls, a content page or a master page. A content page can enclose only server controls.

A simple visual layout of an ASP.NET page.

What developers often misunderstood is that the visual hierarchy of elements differs from the control tree built by the ASP.NET engine. The single most important thing to know about the control tree is that the Page object is the root of the control tree and master pages are all descendants. (Note that all elements – including content and master pages – are derived from System.Web.UI.Control.)

The Control Tree of the depicted ASP.NET page. Note that the Master page is a child element.

When dealing with the order of page events MSDN gives a bit vague description.
About the Init and Unload events the following can be found. The Init event of individual controls occurs before the Init event of the page. (The unload event is) Raised for each control and then for the page. That is the Init and Unload events are raised in a bottom-up manner. The Init (and Unload) event is raised for child controls first and then for the parent control. As a consequence the Page control is always the last in the order.

In case of Load and PreRender events the order of evaluation is the opposite. Parent control comes first and then child controls follow. This results in having the Page control handling the Load and PreRender events first.

Keeping this in mind can help to avoid a lot of confusion. This is specially true when dealing with master pages.

 

ASP.NET MVC Compared to ASP.NET Web Forms – Does It Really Matter?

If you were given a chance to start a new project based on ASP.NET MVC or Web Forms which technology would you use? I think many of us would choose MVC due to its novelty and increasing popularity but good ol’ Web Forms is not a bad choice either. Let me explain.

Recently I have had a discussion with my colleagues about the refactoring/rewriting of an old web application built upon ASP.NET Web Forms. This application is a larger system’s administrative interface with the task of displaying and managing information on thousands of users, groups and other organizational items. As user demands grew we were asked to investigate the possibilities of improving the performance of the app. The key challenge is to provide a responsive user interface besides an excessive increase in the amount of data to display and handle. After a short dispute on the architectural requirements we have agreed that an Ajax based smart client is the most suitable for our needs on the client side. It supports a scalable, easily accessible, efficient and fancy solution. We can finely control the client-server data flow, decrease the pressure on the server by delegating UI tasks to the client and shape the user interface as we like. Having Ajax on the client side what could we have on the server side?

Well, it is really no matter. Both frameworks support Ajax calls and actually that is all we need. If you stick with ASP.NET Web Forms then use web methods with the ScriptMethodAttribute. In case of ASP.NET MVC it is even simpler. Just define a controller action with the proper return type.

But then which framework to prefer? Since both MVC and Web Forms perfectly support Ajax calls the real difference comes from the additional features you can exploit. MVC brings simplicity on modeling and testing side, it lets you to have full control over the generated Html code, provides SEO friendly routing for your applications and more. These features can be valuable but come for a price. MVC is not the best choice for RAD design, requires deeper understanding of Html and requires more investment in terms of development efforts. But in case of dedicated business applications or large applications with private administrative interface implementation speed and the ease of UI development has a higher importance. Nobody needs to optimize for SEO behind password protected sites or to develop fancy UI controls for administrators. The focus is on displaying and manipulating data and Web Forms has a whole family of controls to help.

Novel web applications must deal with high user expectations. There are plenty of ways to satisfy these demands but choosing Ajax gives you the benefits of being OS and browser independent without the need for any pre-installed library. Both Web Forms and MVC are capable to serve Ajax calls at the backend but they have distinctive features in focus. MVC is more suitable for lightweight public applications where control over Html code, custom routing and easy testability is important. In case Rapid Application Development is prefered Web Forms can ease the pressure on development side and can bring shorter time-to-market beside using Ajax on demand. Despite MVC is a new and popular technology with all its pros and cons Web Forms is definitely here to stay.