dedicated to write powerful yet elegant software by using minimum code and maximizing the benefits for all our clients.

Design Patterns - A deep dive 3 by Sunny 06/Jul/2008 23:14:00

Welcome to a series of articles on design patterns. 

In the previous articles, we have covered the following areas:

Part 1 - looks at design patterns at a high level to understand what they can/can't do.

Part 2 - looks at the basic categorization of the patterns & a one-line definition of each pattern under that category.

The previous two parts have been a very high level overview of design patterns. The articles henceforth will concentrate on a single pattern & hopes to provide an insight  regarding coding the pattern, uses of that pattern & some common gotcha's while using that pattern. 

This article (Part 3) looks at one of the simplest and most commonly used type of Creational Design Pattern called as the Singleton Design Pattern. 

What is a Singleton Pattern?

An instance of a class is considered Singleton if it meets the following criteria:

  1. There is only one instance of the class during the lifetime of that application
  2. Any attempt to instantiate another instance of this class would return the previously created instance
  3. The constructor of this class is either private or protected only.

Why is Singleton Pattern classified as a Creational Pattern?

Creation design patterns are a category of design patterns in which there is some special process in the "creation" of an instance of a class.

In case of Singleton pattern, the constructor of the class is not accessible & so an instance of that class cannot be created. The class will internally create an instance of itself & return a handle to this instance each time.

Due to this special behavior of the constructor, this pattern is classified as a Creational Pattern.

Lets talk code

Consider a simple class called Singleton which implements this pattern as shown:
public class Singleton{
 
    private static Singleton m_INSTANCE = null;
 
    private Singleton(){}
 
    public static Singleton GetInstance(){
 
        if(m_INSTANCE == null)
            m_INSTANCE = new Singleton();
 
        return m_INSTANCE;
    }
}

The interesting features of this class are: the constructor, the method GetInstance() and the private static Singleton type field m_INSTANCE, which we will get into more deeply in the following sections.

The constructor

The constructor of the Singleton class has been declared private. You could also declare it protected. Any other modifier like public or internal would allow a possibility to create an instance of this class & would defeat the purpose of a Singleton.

private Singleton(){}

The main concept to understand here is that we are restricting creating the instance of this class by setting the access modifier to the constructor. So, now no consumer of the class can create an instance of it. The only way we can get get an instance is to call the GetInstance() method & use that instance.

The field m_INSTANCE 

The field m_INSTANCE is a private static field which will hold the object of the Singleton class.

private static Singleton m_INSTANCE = null;

Since this field is lazy-initialized & the GetInstance() method always returns this object, we have been able to control the creation of instances for the Singleton class.

The GetInstance() method

The GetInstance() method is the only way we would be able to get an instance of the Singleton class.

public static Singleton GetInstance(){
 
    if(m_INSTANCE == null)
        m_INSTANCE = new Singleton();
 
    return m_INSTANCE;
}

In the class shown above, we note that we are lazy-initializing the private static Singleton type field m_INSTANCE. This code ensures that there would be only one instance of the type which will be created the first time GetInstance() method is called. For any other call after this, the object stored in m_INSTANCE will be returned without creating a new instance.

The point to note about the GetInstance() method is that it has been declared public static with a return type of Singleton. As mentioned previously, since the constructor is private/protected, we will not be able to create an instance of the class & so we will need this static method to get the instance.

Uses of Singleton Pattern

The Singleton pattern is extremely simple to implement & use. Typically, items which need to be initialized only once during the application life implement this pattern. Some of the common examples of such items can be: User Preferences & Settings, Thread/Connection pools, context objects, handle to Application Services (logging, data access, error handling etc.)

In short: "Singletons are most appropriate for services that donot change change their nature based on their invocation context" (c2.com, 2008)

The Bells & Whistles

In this section, we will look at some interesting items which need to be kept in mind while using the Singleton Pattern which might actually make it evil:

  1. Singleton's v/s Global Variables - IMHO while Singleton's are a classes where we are restricting creating mutiple instances, global variables are more like "declared instances". Given this mindset, I would expect a Global Variable to be changed during the lifetime of an application based on certain conditions in the application, while a Singleton would remain in the same state. One more difference I note is that Global Variables are truly global to the application, but a Singleton could be accessible to a part of the application/thread.
  2. Singleton's & performance - One of the most important decisions while using a Singleton is when do we actually instantiate the members of the class & how expensive is it to keep this instance in memory? In the code sample shown previously, we had lazy initialized the m_INSTANCE member which was sufficient for that case. But given a more complex or expensive resource to create, we need to re-look at our design & check if it makes sense in having a Singleton or use some other mechanism.
  3. Singleton's & state - One of the core concepts of Singleton is that it maintain its state as long as the application lasts. One of the drawbacks of this is that to load a different state (For example: running Unit Tests), we need to expose methods to set the new state, which quite defeats the idea that Singleton's retain their state. The other alternative is to reload the application with a different state for the Singleton instance, but then is this acceptable for a Unit Test?

Wrap up

In this article we have seen how a Singleton class can be created, what are its main elements. I would love to hear your thoughts, ideas & experiences using the Singleton Pattern.

In the next article, we will look at another Creational Design Pattern.

Currently rated 4.0 by 1 people

  • Currently 4/5 Stars.
  • 1
  • 2
  • 3
  • 4
  • 5

Tags: , ,

Category: Design Patterns | Development

The ICallbackEventHandler by Sunny 21/Jun/2008 18:17:00

So, you are interested in knowing about the ICallbackEventHandler which can be "used to indicate that a control can be a target of a callback event on the server" according to MSDN.

A very consise and correct definition of the interface which explains everything, except I can see you scratch your head & wonder whats in it for you. Stick along with this article & hopefully you would have a new toy to impress your peers at work!

The problem:

Suppose you need to build a simple ASP.NET 2.0 web page which has a section to show some quotes. You want to randomize these quotes such that the user sees new quotes every few seconds (this is because of the crappy content, but try telling that to the content writer!) 

A few possible solutions:

  1. Postback the complete page after a few seconds & put in random quote, with big usablility & server load issues as a side-effect.
  2. Put in a UpdatePanel around the section and reload the section by setting a Timer, which is a better solution compared to option 1 in terms of usability, but really no difference on the server load.
  3. Implement custom code to fetch the data from the server using the XMLHTTP object, which is a good choice since it does not have the issues aforementioned.
  4. Implement the ICallbakEventHandler, which... happens to be the point of this article, isn't it?

Solution I prefer:

I would prefer using the ICallbackEventHandler interface to solve this problem for the following reasons:

  1. The ICallbackEventHandler is a wrapper on XMLHTTP & there would not be a lot of javascript code to get it working
  2. There are no complex web controls which need to be rendered on the UI because of this call to the server
  3. As the target web site is in ASP.NET 2.0, I would prefer using the implementation of the framework out of the box
  4. The load on the server is limited to calling the methods needed without the burden of a full page postback

Show me to code:

I know you are excited to see this implemented, so now would be a good time to download the source code for the sample application & use it as a reference for the remaining sections of this article.

All this while, we have been talking about the ICallbackEventHandler interface which looks like so:

public interface ICallbackEventHandler
{
    string GetCallbackResult();
    void RaiseCallbackEvent(string eventArgument);
}

Implementing this interface & getting the code to work is as simple as the 3 steps listed below.

Step 1: implement the interface on the Page/UserControl class

To keep our code a bit organized, I create a RandomQuotesUserControl.ascx user control which would, surprisingly, contain the logic to show a random quote. This user control is then registered on the page which needs to show these quotes. In our sample application, I have registered this control on the default.aspx page itself. Alternatively you could create a MasterPage, register this control on the MasterPage & derive the other pages on the web site from that MasterPage.

The inheritence of the RandomQuotesUserControl class would be like so:

public partial class RandomQuoteUserControl 
        : System.Web.UI.UserControl
        , ICallbackEventHandler

Step 2: Writing implementation for the interface methods

I start by implementing the RaiseCallbackEvent like so:

public void RaiseCallbackEvent(string eventArgument)
{
    m_callbackResult = 
    "document.getElementById('randomQuote').innerHTML ='" 
    + this.getQuote() + "'";
}

In this method, I am setting a string to the a local member which will contain the final output which needs to be placed on the UI when the GetCallbackResult method is called. This method has been implemented like so:

public string GetCallbackResult()
{
    return m_callbackResult;
}

Step 3: Register the client callback reference

In this step, we will be registering the client callback javascripts with the Page so that our client side will understand what to do to get our code working. This is coded in the Page_Load event like so:

protected void Page_Load(object sender, EventArgs e)
{
    // Creating the scripts which need to be called
    string clientScript = "function serverRequest(args, context){{ "
    + Page.ClientScript.GetCallbackEventReference(this, "args", "getResult",
    "context") + "; }} function getResult(result, context){{ eval(result); 
    callServer(); }} function callServer(){
    setTimeout('serverRequest();', 3000);} callServer();";
 
    // Register the client script
    Page.ClientScript.RegisterClientScriptBlock(this.GetType(), 
    "RandomQuoteCallback", clientScript, true);
}

Thats it, compile & run the application to see the quotes changing every 3 seconds. 

This is a very simple example of what can be done using the ICallbackEventHandler interface. You could have a lot more complex implementation like sorting a grid or show tool tips or do something really cutting edge. The options are limitless.

This works for me & hopefully it works for you too.

Happy programming! 

ICallbackEventHandler1.zip (3.83 kb)

Be the first to rate this post

  • Currently 0/5 Stars.
  • 1
  • 2
  • 3
  • 4
  • 5

Tags: , , ,

Category: Development

Convert to TryParse by Sunny 14/Jun/2008 17:52:00

Consider that you are assigned to a project to create a very cool application which captures the name, age and date of birth of the user and saves all the data to the database. Yay!

So you go ahead & design a cool form, complete with two text boxes to capture the name & age and add a date picker control to select the date of birth. Sweet!

Now comes the tough part - saving the values to the database. The DBA's really out-did themselves on this one and designed a table which could hold all this information like so:

CREATE TABLE Users
(Name VARCHAR(50), Age INT(3), DateOfBirth DATETIME)

Oh, the wicked people! You quake in fear, since your controls expose only a text property and return the values a text. Surely the DBA's could have designed with this in mind. But they work in a different world that you don't quite understand (or control) & so grudgingly you look at what you could do to convert your string values to the types the table expects.

After burning the midnight oil, you come up with a solution like so:

private void saveUser()
{
    try{
        string name = txtName.Text;
        int age = Convert.ToInt32(txtAge.Text);
        DateTime dateOfBirth 
                = Convert.ToDateTime(txtDateTime.Text);
 
        // Code to save to the database
 
    }
    catch(System.Exception ex){
        // Code to do something with the error
    }
}

Nice, so you managed to convert the values to the types needed by the database and you threw in the try-catch block to handle anything going wrong in your code. You think you are almost done so you call in the new fresh-out-of-college-dude who joined your team last week to show off your master-peice. One look & he has the nerve to mention Validation controls on the client-side so that you would save the server round-trip if the data is invalid.

You throw him a few dagger looks and put in some Validator controls so that the data can be validated on the client. You can hear the drums beating, the bugles sounding as you push out your code to your manager for some review & feedback while you head out for a celebration. Surely, he would be impressed.

The next day, you inbox has a single line cryptic mail from your manager: "Doesn't work, JS disabled." Now you have two headaches - the hangover and the mail. You need to act on them, fast!

So you make your way out to your geek friend who happens to be good at fixing code issues. "Dude" you say, "could you please look into this code, I think I didnot handle the OnServerValidate event of the Validation controls". While he peers at you code, you take a walk to find something for that hangover.

By the time you are back, your geek god has changed your code like so:

private void saveUser()
{
    try{
        
        string name; int age; DateTime dateOfBirth;
 
        if(!String.IsNullOrEmpty(txtName.Text) 
            && int.TryParse(txtAge.Text, out age) 
            && DateTime.TryParse(txtDateOfBirth.Text
                   , out dateOfBirth))
        {
            // Code to save to the database
        }
        else
        {
            // Show validation error
        }
    }
    catch(System.Exception ex){
        // Code to do something with the error
    }
}

You groan out load! You had asked him to handle the OnServerValidate event for each control & he just wrote a few lines of code which you donot understand, you can feel your headache starting up again. You want to ask him about it, but have a reputation to protect. Besides you could always look it up on Google to know what it is & if there is any performance benefit in doing this.

So, you decide to let the code remain as is - if it is good enough for the geek, it should be good enough for your manager. So you fire off an answering mail to your manager with an equally cryptic: "Please review & comment" and get out of the office - time to hit the sack.

When you get to work the third day, the first thing you notice is that the fresh-out-of-college-dude is now a fresh-out-of-college-dude-with-wide-eyes, the second thing you notice is there is no mail in your inbox from your manager (no news, is good news) & finally it dawns on you that your application has shipped bug free - touch wood.

A new project? Bring it on, you say, life is good. 

Be the first to rate this post

  • Currently 0/5 Stars.
  • 1
  • 2
  • 3
  • 4
  • 5

Tags: ,

Category: Development

Wrapping v/s deriving a control by Sunny 15/Feb/2008 21:08:00

When programming, usually you come across a tricky situation where you need to decide if you want to "wrap" a control or "derive" a control. Although this seems to be quite a simple question, the implications are quite different.

CASE 1: When do I "derive" a control?

In my experience, usually you can derive a control when the base control is native to the development environment. For example, assuming you are working in ASP.NET, a custom text box implementation would be "derived" from the System.Web.UI.WebControls.TextBox control.

For me, the major advantage is that since the base control is native to the environment, you can be pretty sure that it would be well supported, documented & (usually) thoroughly tested before being released to the world, not to mention the advantages of deriving (inheritence) in an OOP's world, besides its programming model would be similar to what you would be expecting to code in your application.

CASE 2: When do I "wrap" a control?

Ideally whenever you use controls which don't satisfy case 1 - i.e. for all 3rd party controls!

Although I agree this defeats the purpose of using a 3rd party control in the first place, my take is that a 3rd party control introduces its own "style" of coding into your application code & then replacing a 3rd party control in your application at a later stage is far more difficult.

In our example, if I plan to use a 3rd party text box implementation - say Acme.TextBox control, I would wrap the control completely such that it is referenced & used only within the class which wraps it. The advantage of this is that, even though I am using the control in my code, I am not forced to use the 3rd party implementations for the properties/methods/fields anywhere else in my application. So, even if I need to replace the control at a later stage, the impact would be internal to the wrapper itself.

VERDICT:

In today's world our clients expect us to provide the most "cutting-edge" applications. Usually the native controls fail to meet these expectations & we, as developers, reluctantly use 3rd party implementations to satisfy our paymasters.

But keeping in mind the above two options, I think we would be in a position where the vagaries of implementations don't impact our application to a great extent.

Let me know what you people think. 

Be the first to rate this post

  • Currently 0/5 Stars.
  • 1
  • 2
  • 3
  • 4
  • 5

Tags: , ,

Category: Development