A pragmatic coding excercise for C# developer’s job interview

Job interview questions are efficient when testing the theoretical knowledge of a developer however good answers do not necessarily indicate solid practical skills. If you cannot afford long interviews with multiple rounds then your possibilities are very limited. While complex development tasks needs too much time (and usually insight as well), small tasks are far too simple to involve enough conceptual issues.

The following exercise can solve these problems (within reason). Instead of asking for a proper design demo take a snippet of bad code and ask the developer to fix it without changing the original semantics. It is important to keep the original functionality to enforce fixing all the flaws and keep the task well focused. When creating the code snippet you can hide any OOP principle or language idiom inside the faults. But take care, too much of such code can be very confusing to clean out.

The example below demonstrates a test snippet. The basic OOP design principles inheritance, polymorphism, data hiding, encapsulation issues and some C# language elements are also hidden within flaws. Note, that the code compiles without any error or warning!


internal class Client
{
    public object Id;
    internal string RegistrationFilePath = "c:\\tmp\\tmp.txt";
    internal int status;
    public int STATUSREGISTERED = 1;
    public int STATUSNOTREGISTERED = 2;

    internal void RegisterClient(string z)
    {
        status = STATUSREGISTERED;
        var x = new System.IO.StreamWriter(RegistrationFilePath);
        x.WriteLine(Id + ": " + z);
    }
}

public class EnterpriseClient
{
    private Client _client = new Client();
    public void SetId(int id) { _client.Id = id; }
    public void RegisterClient(string s) { _client.RegisterClient(s); }
}

public class PrivateClient
{
    private Client _client = new Client();
    public List _remarks;
    public void SetId(Guid id) { _client.Id = id; }
    public void StoreRemarks(IEnumerable remarks)
    {
        if (remarks == null)
        {
            throw new Exception("Invalid remarks for private client.");
        }
        IEnumerator remarkEnumerator = remarks.GetEnumerator();
        _remarks = new List();
        do
        {
            _remarks.Add(remarkEnumerator.Current);
        } while (remarkEnumerator.MoveNext());
    }
    
    internal void RegisterClient(string s)
    {
        Console.WriteLine(_client.Id + ": " + s
            + ", remark count: " + _remarks.Count);
    }
}

The Singleton Pattern – Design patterns in practice II.

The Singleton pattern is one of the most well-known and probably the most often used design pattern. It is used to enforce that only a single instance of a class can be instantiated within an application (To be more precise within an AppDomain. For more details please see remarks at the bottom). The key of this pattern’s success is its well focused object and easy implementation.

Despite all the merits there are a lot of misunderstanding around the proper implementation and usage of the Singleton pattern.

First of all it is a code smell to use the singleton pattern extensively since it introduces a kind of global memory. When used for instrumentation it is fine. However my experience shows that in a lot of cases too much business logic is put into this structure needlessly going against design principles. Here a nice description can be found over the deficiencies of the Singleton pattern.

The simplest implementation of the singleton pattern is shown in Example 1. The instance of the class is stored within a static field and is instantiated in the field initializer. If the construction of the instance is more complex then a static constructor can be used. Usually this solution works perfectly and easy to implement and understand.

Example 1:


public class Singleton
{
   private static Singleton _instance = new Singleton();
   
   public static Singleton Instance
   {
      get { return _instance; }
   }
   
   private Singleton()
   {
      Console.WriteLine("Singleton created");
   }
}

The reason many refuse this simple implementation is the lack of lazy initialization. The basic idea is to instantiate the singleton class only on demand to save memory and gain more control over the life-cycle of the singleton. But if an application always instantiates the Singleton then there is little use of lazy initialization in terms of memory usage. Often there is neither real need for the life-cycle control.

When lazy initialization is beneficial double checked locking can server as a simple but efficient solution. The first check is to avoid any locking if the singleton is already created. The following lock statement ensures that only single thread can enter the critical section of object creation at a time. Since multiple concurrent threads can be blocked by this lock a second check is needed within the critical section to avoid the recreation of the singleton. Note that to support multi-thread environment the volatile keyword must be used. The implementation of double checked locking is shown in Example 2.

Example 2:


public class Singleton
{
   private static object _instanceLock = new Object();
   private static volatile Singleton _instance;
   
   public static Singleton Instance
   {
      get
      {
         if (_instance == null)
         {
            lock(_instanceLock)
            {
               if (_instance == null)
               {
                  _instance = new Singleton();
               }
            }
         }
         return _instance;
      }
   }
   
   private Singleton() { Console.WriteLine("Singleton created"); }
}

There is a more elegant solution that omits any explicit locking. The C# 4.0 language specification (10.12) says

The static constructor for a closed class type executes at most once in a given application domain. The execution of a static constructor is triggered by the first of the following events to occur within an application domain:

  • An instance of the class type is created.
  • Any of the static members of the class type are referenced.

Buildt upon the fact that the body of the static constructor executes at most once locking becomes avoidable. In Example 3 a private inner class is introduced with a single static field that holds the singleton instance and a static constructor that initializes it. According to the specification the instance is instantiated when the Instance property accessor of the Singleton class gets called. And this is exactly how lazy initialization must work.

Example 3:


public class Singleton
{
   public static Singleton Instance
   {
      get { return _InstanceContainer.Item; }
   }
   
   private class _InstanceContainer
   {
      public static readonly Singleton Item;
      static _InstanceContainer()
      {
         Item = new Singleton();
      }
   }
   
   private Singleton()
   {
      Console.WriteLine("Singleton created");
   }
}

As mentioned in the introduction the scope of static items is AppDomain. But this can be overriden. If a field is decorated with the attribute ThreadStatic then the scope narrows to thread level. That is, every single thread in the AppDomain will have its own instance of the static field.

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.