Author Archives: Russell

Pattern of the Week: Strategy

This is the third in a series of “Pattern of the Week” posts. I’m primarily sticking with the Gang of Four patterns, but I may branch off occasionally. Thanks for reading.

Type: Behavioral
Difficulty: Beginner

This week’s pattern is the Strategy pattern. This pattern can be used when you have a set of similar algorithms. The easiest way to explain it is with an example, so let’s look at the following class:

Here we have a class that represents a Warrior. There is a primary weapon that is passed into the constructor. The warrior has a method called Attack, which uses that weapon. Let’s look at the IWeapon interface.

This interface has just one method, Use(). When the Warrior needs to attack, he needs to be able to use his weapon. Seems pretty straightforward, right? No matter what kind of weapon that the warrior has, he needs to use that weapon in order to attack. The only difference between each type of weapon is how the warrior uses it. This is the essence of the Strategy pattern. It allows the ability to change the how without changing the what. Let’s take a look at the implementations of the IWeapon interface.

For example’s sake, I didn’t elaborate on how the warrior would use each weapon, but obviously there are huge differences. One slashes with a sword, fires a shotgun, and throws a grenade. However, how the warrior approaches using a weapon is the same: he thinks, “I need to use my weapon”, and then he does whatever it takes to do that.

So, how do we use this? It’s pretty simple. If we want a Warrior who uses a Sword, we do this:

We would do the same thing for all of the other weapon types too.

This pattern may look very familiar to those of us who use Dependency Injection, or more specifically, Constructor Injection. Constructor Injection is probably the most widely used example of the Strategy pattern, but there are other things you can use it for as well. An example that comes to mind is that you could implement data access as a strategy pattern, then pass in the proper implementation based on the database server type that you are using.

That’s all! Visit next week for an explanation of the Template Method pattern.

View Sample Code

Pattern of the Week: Decorator

This is the second in a (hopefully) long series of “Pattern of the Week” posts. I’m primarily sticking with the Gang of Four patterns, but I may branch off occasionally. Thanks for reading.

Type: Structural
Difficulty: Beginner

This week’s “Pattern of the Week” is the Decorator pattern. To explain this pattern, I’m going to start with an explanation of the Open/Closed Principle. The Open/Closed Principle is one of the five “SOLID” principles outlined by Robert C. Martin in his works. The principle states that a class should be open for extension, but closed for modification. What does this mean? It’s actually pretty simple. We shouldn’t change the behavior of a class after it has been defined, and we should be able to extend the class by various means to add functionality. One of the ways to extend a class without modifying it is the Decorator pattern. Without further ado, here’s a class:

Well, that’s a pretty simple class. It implements the following interface:

Nothing revolutionary there. We’ve represented a pretty basic person. So, let’s say we want to print out the information on the console. Here’s one way to do it:

Since this only deals with the Person class, maybe we should add it to the Person class, as a Print method. But wait, wouldn’t that be modifying the class to extend it? Yes. So, we shouldn’t do that. Worse, it would also be violating another SOLID principle: The Single Responsibility Principle. This class would have the responsibility to keep Person information, as well as the responsibility to print it out to the console. Well, we don’t want to break two SOLID principles, so let’s try something using the Decorator pattern instead. We’ll create the following class:

Now, there are a couple of important notes about the PrintablePerson class. First of all, you’ll notice that it implements the same interface as the Person class. It also adds a method called Print. Finally, it takes any implementation of IPerson in the constructor, then hands off all calls to IPerson properties and methods to that class. So, how does this help us?

Well, we can now add printing functionality to any IPerson implementation, without changing the class itself. This new class also has only one responsibility: printing. That covers both the Single Responsibility Principle and the Open/Closed Principle. So, let’s look at this in action:

By decorating the Person class in the above code, we were able to extend the class, without actually modifying the original class. This is incredibly powerful. By using this technique, you can keep your classes simple, and make sure that they only have one responsibility. You can also avoid changing the code in a class that you know is working, so you don’t have to worry as much about introducing bugs. (You should still test though!)

You may be asking yourself, “that’s good and all, but when do I use it?” Well, there are countless ways to use the pattern. Microsoft actually uses the pattern fairly heavily in the .NET Framework, mainly with the System.IO classes. You could use it to add logging to a class that doesn’t have it built in. You could use it to handle exceptions from a class that doesn’t handle them. Again, the possibilities are nearly endless.

That’s all! Visit next week for an explanation of the Strategy pattern.

View Sample Code

Pattern of the Week: Singleton

This is the first in a (hopefully) long series of “Pattern of the Week” posts. I’m primarily sticking with the Gang of Four patterns, but I may branch off occasionally. Thanks for reading.

Type: Creational
Difficulty: Beginner

Singleton. It is probably the least complicated of all design patterns, yet it can be confusing for beginners. In this post, I will attempt to explain exactly how to create a Singleton, talk about common implementation problems, and provide some sample code so you can see it in action.

The basic idea of a Singleton is simple. I only want one of some object. Well, that’s easy, right? Don’t create more than one. Looks like my work here is done. Well, what if I want to ensure that there is only one instance of a certain class ever created while my application is running? That’s where Singleton comes in. Singleton basically protects you from creating more than one of something. It also only creates the instance the first time you use it, i.e., lazy initialization. Here’s a basic implementation:

The above code is pretty much the simplest way to create a Singleton. It also isn’t thread-safe, and it isn’t very useful (no properties, members, etc.). Before we go on to that, let’s explain what we’re looking at. First, you’ll notice that the class has a private constructor. This is due to the fact that we don’t want people to just do this:

You’ll also notice a private, static variable on the class called _instance. This variable is what actually holds the Singleton instance. Finally, you’ll notice the Instance property. This is where all the work is done. The getter first checks to see if there is already an instance, and if there isn’t, it creates one. Then, it simply returns the instance. This ensures that there is only one.

Now, this is great, right? Not really. What if your application is multi-threaded? Meaning, two threads accessing the Instance property at the same time? Well, thread 1 will hit the if statement, and say, “I need to create an instance.” Maybe thread 2 will hit that same if statement before the instance is created, and it’ll say, “I need to create an instance.” So, it’s actually possible to end up with two threads with two different instances of Singleton. Fixing this is simple though. See the below corrected code:

I’ve added a static lock object that will prevent more than one thread from going through the instantiate + return code. This means that if the threads reach the code at around the same time, the later one will have to wait. So, looks like we’ve solved all the problems with Singleton. Wait, what if I create a derived class? You can’t create a derived class outside of the Singleton class, since the constructor is private, but what if you create one inside of Singleton?

Then, somewhere in your code, say:

Guess what? You’ve just created two instances of a Singleton class! How do we fix it? Simple. Add the sealed modifier on to the Singleton class. Sealed classes cannot be derived. Here’s our final code:

To make this useful, you would simply add properties to the Singleton class, then access them like this:

That’s all! Visit next week for an explanation of the Decorator pattern.

View Sample Code

SimpleLookups 1.5.1, Blog Status

Today, I’m releasing SimpleLookups 1.5.1.

This version is a major rewrite of a lot of the core stuff, so it contains no API changes. Basically, if you used it before, it should still work great for you today. The only new thing is that you can now configure it through the app.config/web.config files. The download package contains an example of how to do that, and I’ll be updating the documentation so that it’s even more clear.

You may ask yourself, what happened to 1.5? Well, as of today, SimpleLookups is now available in NuGet. The version had to be revved due to me accidentally pushing an early version of 1.5 during a test, and NuGet not having a way to replace the earlier version (unless the version number is higher). I’m planning to release the next major revision soon anyway, so it’s not a big deal.

Besides the SimpleLookups release, I’m planning to use this site as more of a how-to blog instead of just a release log. I’ve done a couple posts, but I really want to start getting into writing about what I’m learning. The next blog post will be educational, and not a release announcement. Pending bugs of course.

Anyway, keep learning and have a great day. -R

SimpleLookups 1.2 Released

Today, I released SimpleLookups v1.2. This version includes the following changes:

New Features:
– Get a list of lookup values based on a code or a list of codes.
– Remove a list of lookup values based on a code or a list of codes.

Changed Features:
– The methods “GetActive” and “GetAll” are deprecated and are replaced by a single method called “Get”. An activeOnly flag is passed in to the method.

The next release will be v1.5, and it will contain code structure changes and some other changes, namely the ability to configure SimpleLookups through app.config/web.config files.

As typical, a few links for the lazy:
Getting Started with SimpleLookups

Download SimpleLookups 1.2
View Source Code (BitBucket)
View Complete SimpleLookups v1.2 API Documentation

SimpleLookups 1.1 Released

Today, I released SimpleLookups v1.1, which is a small change to the library that is taking the world by storm. (Disclaimer: May not be as popular as advertised.)

This version includes a couple of small API changes, as well as a couple new methods.

New Features:
– Get a list of lookup values based on a list of ids.
– Remove a list of lookup values based on a list of ids.

Changed Features:
– The method “GetById” is now called “Get”.
– The API will now return IList instead of List.

A few links for the lazy:
Getting Started with SimpleLookups

Download SimpleLookups 1.1
View Source Code (BitBucket)
View Complete SimpleLookups v1.1 API Documentation

SimpleLookups 1.0 Released

Today, I released SimpleLookups v1.0, which is a project that I’ve been wanting to release for a long time. This is a small .NET 2.0+ library that is designed to make “lookup” values easy to retrieve from a SQL Server database.

Edit: The tutorial is now here: Tutorial

Download SimpleLookups 1.0
View Source Code (BitBucket)
View Complete SimpleLookups v1.0 API Documentation

SQL Server: Divide Date Range into Months

I wrote a script the other day that is utterly useless to me, but it might be helpful for someone else, so I thought I’d write a quick post about it.

Suppose you have some date range, let’s say “1/20/2013 – 4/29/2014”. Now, suppose you want this range to be broken up into one month sections, with a start and end date for each month. Suppose, for some reason, you want to use a recursive common table expression (CTE). You can just do this:

This would produce the following results:


I think that this is actually pretty cool, but I can’t really come up with a reason to use something like this, outside of maybe a financial application. Anyway, I hope someone gets some use out of it.

Points Calculator 1.1 Released

I just released Points Calculator v1.1 on the “Things I Work On” page. It uses a well-known points-based weight loss formula to calculate how many “points” a particular food is worth. I used to use it in college, and I haven’t really messed with it since then, but I figured I would put it up here in case anyone can use it. It’s also open source if you want to check out how it was made. No real magic there though, just a simple button event and an equation. Anyway, enjoy.