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

Design Patterns - a deep dive 1 by Sunny 28/Jun/2008 17:16:00

A colleague of mine asked me a question few days back: "If an application is created using the correct design patterns, does it ensure that the application would be bug/performance issues free?"

The answer to the question gave me an idea to put in a series of articles to look at what are design patterns, what design patterns can/can't do & hopefully get some interesting dialog started with you readers about your experiences & inputs.

Let us start this journey with a small step in understanding a few definitions regarding design patterns, and look at what design patterns are all about at a very high level. The subsequent articles will focus on details of each pattern & a few scenarios where we can use these patterns. 

What is a design pattern?

"In software engineering, a design pattern is a general reusable solution to a commonly occurring problem in software design" - (Wikipedia, 2008

IMHO, a design pattern is a probable way to solve a design problem in software. I use the term "probable" because even though a design pattern might "seem" to solve the issue you are facing, you still need to analyze the problem & ensure that the solution/pattern offered is valid in the context of your development effort.

This judgement is acquired only by experience in either using the pattern successfully or having burnt your fingers in the process. Experienced Architects, Designers & Developer will tell you that even if you have had used a pattern many times in your previous projects, you will still need to evaluate using the pattern in your current project simply because the requirements/project environment/time-of-the-day is different from the last time you used it.

"Patterns are about design and interaction of objects, as well as providing a communication platform concerning elegant, reusable solutions to commonly encountered programming challenges." - (Data & Object Factory, 2008)

The key word in the definition above is the idea of a "communication platform". A design pattern not only helps in communication between objects, but also provides a communication platform in discussing your ideas with your peers.

For example, it would be easier in telling someone that you are planning to use a Facade pattern instead of a MVC & they would instantly know the "structure" of what you plan to do. So you could directly get into a discussion about the merits/demerits of using a particular pattern & focus on what meets your business requirements rather than spend time explaining what you plan to do.

Note: The above statement is assuming that the "someone" also understood design patterns; else you can always point them out to this series for more information Tongue out

What is NOT a design pattern?

These are a few items that come to mind & I will keep updating this list if you have some more items to add here. So, here goes:

  • Design patterns are not architecture patterns - design patterns specifically deal with the problems at a software design (object creation, communication & behavior) level, while architecture patterns deal with the problems at the software engineering (communication, operation, maintenance, enviroment, physical/logical layers in the application) level
  • Design patterns are not solutions to your problem - design patterns are generic solutions to generic problems. Your application is not a generic application, so if you need to "customize" a design pattern to solve the specific problem you are facing. This customization would be valid only within the confines of your application to address that specific problem. You will need to start this analysis all over again in a different problem/project.
  • Design patterns are not algorithms - design patterns are not implementations, they are only a "framework" for a solution, while algorithms are implementation of a problem solutions to a problem. So, while algorithms may be directly used in your application (For example, an algorithm for a bubble sort), design patterns need to be tailored for your application
  • Design pattern is not a hammer looking for a nail
  • Design patterns are not answers looking for questions (this is a good quote from my friend & colleague Vasanth)

Why do I need design patterns?

Frankly, you could continue with the rest of your programming life without knowing a single design pattern & you could do just fine. As long as a piece of software meets its business goals, who cares what it does under the hood, really?

Then again, do you see a productivity benefit in using a proven development paradigm instead of re-inventing the wheel (unless the wheel was square, ofcourse)?

Would you prefer eliminating those hard to fix logical bugs in your application by using a standard template of avoiding such issues?

Do you like to appear cool (or a nerd, depending on the audience) by explaining the nuances of MVC/MVP patterns, or start a flame-war if MVC is really a design pattern or an architecture pattern?

If your answers to the above questions is a resounding YES, then unfortunately you do need to know what design patterns are.

On the bright side - you now have a new way to screw up your code & people might actually understand where you screwed up & help out with solutions!

Great, when do we start?

If you still didnot notice, we are already on our way!

This was the first of the series of articles & I hope to bring out the next one ASAP. Till then, you could go through my previous articles, which really have no connection to this article whatsoever, but interesting enough, I hope.

The Answer

Regading the answer I gave my colleague to his question posed at the start of this article, I realized that my colleague had two positives going in his favour:

  1. He realized that all software projects inherently had bugs/performance issues in them - to a detected or un-detected extent
  2. He was curious if his new-found knowledge could help him solve these issues
Since two positives still make a positive, I had replied: "Yeah, right!"

Currently rated 5.0 by 1 people

  • Currently 5/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

Moving to BlogEngine.NET 1.3.1.0 by Sunny 12/Jun/2008 13:53:00

Over the last weekend, this site has moved from BlogEngine.NET v1.3.0.0 to v1.3.1.0

The reason being a "security flaw [ed. which] makes it possible to access BlogEngine.NET user passwords". More

Being a conscientious blogger, I will "refrain from spelling out exactly how to attack sites that havn't been updated yet"; not that I know what this issue is Tongue out

"Archive" & "Categories" sections have been added to the pages & hopefully you would take time to browse through anything that catches your fancy.

Carry on.

Be the first to rate this post

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

Tags:

Category: Development

Code formatter for blogs by Sunny 17/Feb/2008 20:16:00

Have you ever tried to put in code snippets into your blog?

Well, using this tool: http://www.manoli.net/csharpformat/ you will be able to format code for c#, VB, HTML/XML/ASPX, t-sql & msh. Although this is a nice to have feature in BlogEngine.NET, I would imagine it would come about in a later release.

For the time, I will use the formatter to get the HTML needed & paste the output in my blog for professional-looking code snippets. Let me know if you know of such useful tools which help in yor day-to-day work.

Be the first to rate this post

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

Tags:

Category: Development | Tools