Code Snippets

If you are using Microsoft Visual Studio, you are probably used to code snippets, which is kind alike code generation with a few keystrokes. Visual studio comes with a hand full of code snippets, however there are still sometimes where you may want to have your own code snippets. Unfortunately I never found writing code snippets easy, so I usually was skipping my attempts to write a code snippet.

Today i found this open source project at codeplex: Snippet Designer.
It is exactly what I was expecting to have for a long time :) as creating a code snippet is very easy now. I am also practicing TDD (test driven development) for some time,and below is my most popular line of code :

throw new NotImplementedException("Write a unit test");

I write this simple line to compile the code but also fail the test, and I can't tell you how many times I write this simple 1 line.
Today, I installed Snippet Designer tool, and I was checking out a simple way to create a snippet for the above line, and boom it was right there :) I wrote the line, select the line, right click , and the menu was there for me: “Export as Snippet”. I clicked on this, and the next step was this:


It is a straightforward window to fill. The most important part for me is the shortcut section, in my example I wrote “tddnot” so that whenever I write “tddnot” in the visual studio editor and hit tab, I get my most popular line :)

What if you want to have a place holder? Such as you want to have a codesnippet for a test function, and as you are using NUnit you want to have [Test] decoration around your function. I opened one of my existing test functions, highlighted the function, right click on it and click Export as Snippet menu.

This time I highlighted my function name, right click, and select  Mark as Replacement. So whenever you write your code snippet shortcut, you can tab to your Mark as Replacements and change them quickly.

Below is my code snippet for Nunit Test Class that I created using Snippet Designer, and believe or not, it took me less than 1 minute to create this file :)

<?xml version="1.0" encoding="utf-8"?>
<CodeSnippets xmlns="http://schemas.microsoft.com/VisualStudio/2005/CodeSnippet">
  <CodeSnippet Format="1.0.0">
        <Keyword>NUnit Test Template Project</Keyword>
        <Literal Editable="true">
        <Literal Editable="true">
        <Literal Editable="true">
        <Literal Editable="true">
      <Code Language="csharp" Kind="method decl"><![CDATA[using System;
using NUnit.Framework;
namespace $SomeNamepace$
    public class $SomeTestClass$
        public void $InitializeTest$()
        public void $SomeTestFunction$()


E-mail | Permalink | Trackback | Post RSSRSS comment feed 0 Responses


Replace Nested Conditions with Guard Clauses

   I am reading “Applying Domain-Driven Design and Patterns with Examples in C# and .NET” by Jimmy Nilsson. I am at the very beginning of the book, and the book already is proved to be very useful for me. I put a post-it page with a small note on it, reminding myself what i should be checking out after I am done with the book. This book has already gotten a lot of post-its :)

One of my notes has this on it: “Replace Nested Conditions with Guard Clauses” (Martin Fowler Refactoring). I search on this phrase, and basically this is what it means I guess:
Let’s say in your code you have some if-else clauses, usually what if-else clause says, each possibility (if being true, or if being false) has almost the same weight, even whatever you are testing in one branch  is a rare condition.

Below is a calculator class, that can  divide numbers:

public class Calculator
    public int Number1;
    public int Number2;
    public Calculator(int Number1, int Number2)
        this.Number1 = Number1;
        this.Number2 = Number2;
    public Calculator():this(0,0){}
    public double Divide()
             throw ArgumentException();
         else if(Number1==0)
              return 0;
            return (double)Number1/Number2*1.0;

This is a simple class, and divide function, first checks the numbers, and throws exception or returns 0 or returns division. There is 1 if clauses with 2 else clauses. We first check if Number2 is zero or not, as any number divided by zero will throw runtime error, this  check is an unusual condition check, as the application is not expecting a zero, and shouldn't get one. This unusual conditional  should be not followed with an else clause, but return back the caller. This is called a guard clause, so if we refactor the divide function we will get this:

if (Number2==0)
    throw new ArgumentException();
    return 0;
return (double)Number1/Number2*1.0;
This new code is clearer, easier to understand and maintain :)


E-mail | Permalink | Trackback | Post RSSRSS comment feed 0 Responses


Strategy Design Pattern

Strategy design pattern is a behavioral type of design pattern that allows to change the algorithm (strategy) to your solution dynamically. Here is a uml diagram of the pattern (Wikipedia Image)


So we have 3 main actors in this design pattern.

  • Actor #1: The Strategy: Usually an interface or abstract class  that has the signature for the function we want to change dynamically.
  • Actor #2: ConcreteStategy: The classes that implement the function that is introduced by Actor #1
  • Actor #3: Context: The client that uses actor #1 to call the functions at actor #2

Let’s come up with a few scenarios where we can implement this pattern.

Assume your application has a Notification features, depending on some configuration, this notification could send an email, page somebody, call somebody, log it to the database, log it to the event log etc…

If you don’t separate these different functions from the context, than you will have a huge switch case. Instead you can have an interface INotifyUser with a single SendMessage functionality such as:

   1:  public INotifyUser
   2:  {
   3:      public void Notify(string NotificationMessage)
   4:  }

This is our actor #2, the strategy. Our next actor could be the concrete strategies, such as the classes that implement this interface.

   1:  public class SaveToDatabase: INotifyUser
   2:  {
   3:      public void Notify(string NotificationMessage)
   4:      {
   5:           // Write to database code comes in here
   6:       }
   7:  }
   9:  public class EmailToUser
  10:  {
  11:      public void Notify(string NotificationMessage)
  12:      {
  13:           //Email to user code comes in here
  14:       }
  15:  }
  17:  public class SMSToUser:INotifyUser
  18:  {
  19:      public void Notify(string NotificationMessage)
  20:      {
  21:           //SMS code comes in here
  22:       }
  23:  }

After we have our strategy, and the concrete classes, all we need is a context that will use the interface to swap the algorithm dynamically. If you are C# developer, you can see a similarity with this pattern and delegates, lambda expressions too.

Our context could be SystemFailure class which has dependency on the interface and call the Notify function. I took the example from Dimecasts.net and modified it so that it fits into my solution.

   1:  public enum SystemNotifier
   2:  {
   3:    SaveToDatabase,
   4:    EmailToUser,
   5:    SMSToUser
   6:  };
   8:  public class SystemFailureLog
   9:  {
  10:    var _Notifiers = new Dictionary<SystemNotifier,INotifyUser>();
  12:     private void CreateNotifiers(){
  13:       _Notifiers.Add(SystemNotifier.SaveToDatabase,new SaveToDatabase());
  14:       _Notifiers.Add(System.Notifier.EmailToUser,new EmailToUser());
  15:       _Notifiers.Add(System.Notifier.SMSToUser,new SMSToUser());
  17:    public SystemFailureLog(){
  18:      CreateNotifiers();
  19:     }
  21:     public void NotifySystemFailure(SystemNotifier strategy,string message){
  22:        _Notifiers[strategy].Notify(message);
  23:     }
  24:  }

As you can see, the context, has a dictionary that holds different strategies, and by passing an enum value, you can dynamically change what functionality you will be using.

How can we use this? Imaging, you have a system monitoring tool, and the first time system fails, it uses SystemFailireLog and calls save to database function, the second time system fails, email to user, and maybe third one is sms to user.

public class SystemWatchDog
  public static int FailureCount = 0;
  private SystemFailureLog _FailureLogger = new SystemFailureLog();

  public void ReactToSystemFailure()
     FailureCount = FailureCount++;
                String.Format("System failure, restarting at {0}",DateTime.Now);
     else if (FailureCount ==2)
                String.Format("System failure, restarting at {0}",DateTime.Now);
                String.Format("System failure, restarting at {0}",DateTime.Now);
Have Fun :)


E-mail | Permalink | Trackback | Post RSSRSS comment feed 0 Responses


Oracle Developer’s Day

      Yesterday, I was at the Oracle Developer’s Day workshop in Anaheim. I am not an Oracle developer, but I wanted to see the other side :), and registered for the event. The event was at Crown Plaza Anaheim. I don't like to complain for the events that are totally free, as the vendors usually spend lots of money and effort to organize these events, however there a few things I need to say :). There was a registration form for this event, and laptop was required too so everybody had to bring their laptops. By just looking at the number of registration forms filled in, Oracle could know how many people were coming, and supplied enough power extensions for the room, as some people couldn’t plug in their laptops. The internet was dead slow, I tried to download a file from the internet the average speed was 5kb/sec.

Another important feature for me is the room temperature as it is not easy to sit in a room that is too hot or too cold and try to listen the new stuff. However yesterday the room temperature was perfect. The lunch was good, unlimited coffee and drinks were nice.

So the presenter? It was very obvious that the presenter was very knowledgably and he knows what he is talking about. You can’t imagine how many workshops I attended and the presenter did not know about the presentation. However our presenter had a problem managing the crowd yesterday. He didn't give the break on time which made a lot of people uncomfortable as there were leaving the room to get coffee, visit restroom and mumbling. He was also late for the lunch break. These things may sound simple things for you, and I may sound like I am whining however when you present to 100+ people, these small things multiple by 100+.

So Oracle announced the JDeveloper tool, and I don't have any knowledge with their trend, but I liked the tool, with a few clicks you can do a lot of things such as paneling, database cruds, drawing charts. There was the MVC from Oracle too. For more technical review of this workshop, I am sure you can google and find lot’s of reviews, this was my guest from the other side of review :)


E-mail | Permalink | Trackback | Post RSSRSS comment feed 0 Responses