2009-05-28

Patterns and Practices - Factory

The Factory (method) Pattern, deals with the problem of creating objects. This is particularly useful when the consumer of the Factory method doesn't care the exact object that's returned, but really only cares that it's of a certain type.

Implementations of the Factory Pattern are often done using interfaces, but it's also not uncommon for them to be done using Abstract (or parent) classes [which may start to broach on the concept of the Abstract Factory Pattern], as well. If you're not familiar with either of these concepts in the .NET world, it's worth your time to do some research--before you continue reading.

The following examples (again, in C#) are just one possible implementation, but they should  help you to understand what to expect when someone discusses the factory patterns.

The following is one of the most basic examples of the factory pattern:

  public interface ICar
  {
    public int CalculateMaxSpeed();
  }

  public class Corvette : ICar
  {
    public Corvette() {}
    public int CalculateMaxSpeed()
    {
      // Of course, you could calculate, coefficients of friction, aerodynamics,
      // torque, gear ratios, blah blah blah. Or just return 180.
      return 180;
    }
  }

  public class StationWagon : ICar
  {
    public StationWagon() {}
    public int CalculateMaxSpeed()
    {
      // Of course, you could calculate, coefficients of friction, aerodynamics,
      // torque, gear ratios, blah blah blah. Or just return 65.
      return 65;
    }
  }

  public class CarFactory
  {
    public static ICar GetCarFactoryMethod(bool DoesCustomerWantSportsCar)
    {
      if (DoesCustomerWantSportsCar)
      {
        return new Corvette();
      }
      else
      {
        return new StationWagon();
      }
    }
  }

Now, to explain what's going on above. First off--we've defined an Interface, ICar. ICar has one method, CalculateMaxSpeed. You'll then notice that there are two implementations for this interface--Corvette and StationWagon. You'll also notice that Corvette and StationWagon have two very different results for CalculateMaxSpeed. Now, if you're writing code to consume this, you'll use CarFactory.GetCarFactoryMethod(bool) to return a car.

Think of it this way--you're a Customer who's shopping for a new Car. You know that you want a sports car, but you don't really care about anything past that. So you go to the CarFactory and ask for a car. It asks you DoesCustomerWantSportsCar, and you reply yes! And viola. CarFactory gives you a Corvette.

To consume this, you'll write code that looks something like this:

public int GetCarsMaxSpeed()
{
  ICar car = CarFactory.GetCarFactoryMethod(checkboxWantSportsCar.Checked);
  return car.CalculateMaxSpeed();
}

Bam. Your CarFactory has returned to you the car that you desire. Of course, you could add in configuration file scanning logic. Perhaps you want to use to facilitate your connections to your database. There's a lot of very intriguing things that you can do with this pattern, so use your imagination!

Oh, also note that some variations of the Factory pattern are more strict--requiring constructors to be private and using having a class implement it's own tightly contained factory method... such as follows:

  public interface ICar
  {
    public int CalculateMaxSpeed();
  }

  public class Corvette : ICar
  {
    private Corvette() {}
    public static ICar GetFastCar(int SomeCriteria)
    {
      // This static method is also a Factory method.
      return new Corvette();
    }
    public int CalculateMaxSpeed()
    {
      // Of course, you could calculate, coefficients of friction, aerodynamics,
      // torque, gear ratios, blah blah blah. Or just return 180.
      return 180;
    }
  }

  public class CarFactory
  {
    public static ICar GetCarFactoryMethod(bool DoesCustomerWantSportsCar)
    {
      if (DoesCustomerWantSportsCar)
      {
        return new Corvette.GetCar();
      }
    }
  }

Practical reasons to use it...

  • You have a multiple different-but-similarly-structured objects that you need to consume at runtime, and they're use may vary at runtime.
  • You want to use some KPI (Key Performance Indicator) to determine which object you want to work with depending on the state of your application.
  • You want to control how your objects are instantiated--as described in the Corvette.GetFastCar above. This also leads to very descriptive instantiations, rather than complex overloads of constructors.

Places where I've used it...

  • An application that used both online / offline data storage. Depending on the availability of an internet connection, it may try to write to a local XML Structure--or to a SQL Server database.

What to be worried about...

  • Are you pushing too much into a factory? Do you really need to determine at runtime what object type you need? Or can you do that during development?
  • There is a minor performance hit by using a separate subroutine instantiate your object and pass it to you. High performance apps may care.
  • Adds complexity to your code and may make debugging more difficult.

More Patterns coming soon. Zoidberg away!

2009-05-27

Safari (Mac) Keyboard Shortcuts

Alright... couple of important keyboard shortcuts for Mac users.

F6 on Windows jumps to the browser's address bar. Command+L is the Mac (Safari) equivalent.

And to hop directly to the Search Box, Option+Command+F

Zoidberg Away!

Patterns and Practices - Singleton

One of my biggest shortcomings as a developer is not being able to identify the different Design Patterns out there. Sure, I've been writing code for years that have applied these same types of behaviours and methodologies, but I've never been able to say "See this code: Singleton... that one: Factory".

Well, I've got news for you. Patterns are not only a way to write code, but more importantly, they are a way to communicate it. Hire a new developer? Need to get him trained? He's working with your CRM's Business Layer? Tell him that it's instantiated by the Factory Pattern and he'll have an idea of what's up. Sure, you're implementation maybe slightly different--but he'll know. Patterns are, very simply, a way for developers to communicate what they're doing.

The first Pattern I'm going to talk about is the Singleton. Wikipedia has a pretty good definition... The Singleton is a design pattern to limit instantiation of a class to one object. Let's define a couple of OOP terms...

  • Class: in computer programming, a representation of a defined structure for a type of data. May contain Properties, Fields, and Behaviours/Methods. An abstract representation of a data type.
  • Object: in computer programming, an instance of a Class--most likely having Properties and Fields populated, and possibly having Behaviours/Methods. A concrete, tangible Instantiation of a Class.

So, the goal of the Singleton pattern is to limit the number of (object) instances of an Class to one and only one. During run time, there will ever be only one concurrent instance. (Note, it maybe possible to have your Singleton cleaned up during runtime--I won't be talking about that here).

The following is an implementation of the Singleton in C#.

public sealed class Banana
{
static Banana instance = null;

// Constructor
Banana() { }

// Call this property to consume
public static Banana Instance
{
get
{
if (instance == null)
{
instance = new Banana();
}
return Instance;
}
}
}

There is a problem with the Singleton Banana, in the above example. While it will technically work, it's not thread-safe. It's theoretically possible for this call to be made concurrently and two instantiations of the local variable instance to occur. If you know your application is never going to exploit this, you'll be fine. But if not, you may very well run into a temporal paradox that will ultimately lead to the destruction of the universe as we know it. You may wish to use something like this instead.

public sealed class Banana
{
static Banana instance = null;
static readonly object lockObject = new object();

// Constructor
Banana() { }

// Call this property to consume
public static Banana Instance
{
get
{
if (instance == null)
{

// use your lock object to isolate the object / thread.
lock (lockObject)
{

// check to make sure it's still null. It's possible that two
// threads got into the same lock code simultaneously
if (instance == null)
{
instance = new Banana();
}
}
}
return Instance;
}
}
}

Practical reasons to use it...

  • You have a piece of data that is pretty stagnant that needs to be read frequently (but seldom written to). Placing that data in memory would have certain advantages (in-memory index scans, for example) and/or a data-store lookup would be costly for this type of data.

Places where I've used it...

  • Querying Active Directory for a list of users in a group that's repeatedly shown to my users, but never written.
  • Keeping common information such as States or Departments in memory and available--thus reducing database lookups.
  • When working with data in a stateless environment (and I'm too lazy to implement a state management system).

What to be worried about...

  • Memory consumption. Since the Singleton exists throughout the scope of your application (after it's been instantiated, of course), it will use up X amount of space in memory indefinitely.
  • What if your data source changes? A Singleton may need to be refreshed. In that case, I've used a "DateQueried" property that you use to check against and, if expired, refresh your data.

More Patterns coming soon. Zoidberg away!

2009-05-12

Telerik ASP.NET RadGrid Quirkiness

Greetings all! I've been working with Telerik's fine suite of controls lately, and unfortunately, spent almost two hours spinning my wheels this morning over this one. Apparently, if you're using a RadGrid with the following conditions, except troubles...

  • Using Telerik Script Manager Control
  • Using Telerik RadGrid control
  • Using Telerik AJAX Panel
  • Configured Data table (Master or Detail table) EditMode="Popup"
  • ASP.NET Validator Controls in your edit columns--either applied server side in your grid's ItemCreated event or in a EditItemTemplate

You get a JavaScript error when the "Edit" button is clicked, and your Popup form doesn't display.

In my scenario, everything's wrapped in an AJAX Panel, so there's "no postback". Since this is the case, I've disabled Client Side Validation for my Validator Controls--and things started working again. Warning for you though, disabling Client Side Validation on your Validator will be an inconsistent behaviour compared to some of your other uses--may be less than desirable. Hurrah. Any ideas? I suspect a bug with the ScriptManager / RadGrid combo. Hard to say, though.

Zoidberg Away!

2009-05-06

C# - Fun with .NET Generics, Lists.

If you've not yet experienced .NET Generics (part of the System.Collections namespace), you don't know what you're missing. This namespace is among the most valuable code within the .NET Framework (2.0+), and it's worth getting acquainted with. If you're stilling using arrays or ArrayLists, it's time to move on.

Getting started

It's time to familiarize yourself with List. List--an implementation of IList--is one of the most valuable additions to the .NET Framework. Use it in place of arrays or arraylists, when you can. Here's how to use it.

// Instantiate
List<int> Ids = new List<int>();

// Fill it with data
ids.Add(1);
ids.Add(7);
ids.Add(8);

// Iterate through it
foreach (int id in ids)
{
  Console.WriteLine(id);
}
// Output yields:
/*
1
7
8
*/

With the above sample, it gives you a good idea how to consume it. While I've used integers above, you can easily use any object, replacing <int> with <objecttype>. What makes this so amazing?

List<Employee> employees = new List<Employee>();
// Pretend there's code to populate your Employee List here.
foreach (Employee e in employees)
{
  Console.WriteLine(e.FirstName);
}
// Output yields:
/*
Employee1Name
Employee2Name
Employee3Name (etc.)
*/

Intellisense, too. None of that casting crap that goes along with ArrayLists--and you get the flexibility to dynamically add objects to a List, unlike arrays.

You can even create Classes that inherit from Lists. Use the following syntax.

public class EmployeeCollection<T> : List<T> where T : Employee, new()
{
}

Now, as you can imagine, this could have some amazing functions inside it like...

public class EmployeeCollection<T> : List<T> where T : Employee, new()
{
  public override bool Contains(Employee employee)
  {
    foreach (Employee e in this)
    {
      if (e.EmployeeID == employee.EmployeeID)
      {
         return true; 
      }
    }
    return false;
  }
}

You can even add custom Indexers as well.

public class EmployeeCollection<T> : List<T> where T : Employee, new()
{
  public virtual Employee this[Guid employeeID]
  {
    get
    {
      foreach (Employee e in this)
      { 
         if (e.EmployeeID = employeeID)
         {
            return e;
         }
      }
    }
    return null;
  }
}

Which can then be consumed like this...

EmployeeCollection ec = new EmployeeCollection();
// Pretend I've filled this List, too.
Guid employeeID; // pretend this is meaningfully filled.

Console.WriteLine(ec[employeeID].FirstName);
// Output yields:
// Employee5Name

Well. That's a brief introduction to the fun that you can have with the .NET System.Collections namespace. There's a whole lot more here. HashTables, Dictionaries, and Lists of all sorts. I'd recommend that you dig in to learn some more. Alas, Zoidberg Away!

2009-05-05

.NET 3.5 Extension Methods

New to .NET 3.5 are a very powerful new paradigm called Extension Methods. Extension Methods, in a nutshell, are a way to extend the functionality of additional classes--adding new Methods to existing classes for the purpose of augmenting capability. The easiest way to demonstrate this is to show you a great example...

namespace ExtensionMethods
{
  public static class StringExtensionMethods
  {
    public static bool IsNumeric(this string str)
    {
      try
      {
        int i = int.Parse(str);
        return true;
      }
      catch
      {
      }
      return false;
    }
  }
}

C#, as many of you know, lacks the built in VB.NET function, IsNumeric. (By the way, I can name a few things wrong with this particular extension method--so only use this example for the How-To of Extension Methods, not synthesizing IsNumeric) This extension Method extends the type string (the keyword "this" in the method signature is used to define what this method extends). With this newly written function, you can determine if a string is numeric by running code like this:

string s = "someValue";
bool bs = s.IsNumeric();
// bs is false;

string i = "7";
bool bi = i.IsNumeric();
// bi is true;

Now--as you may know, .NET strings do not intrinsically have a method IsNumeric() on them--this is our new Extension Method in action. In Visual Studio, you'll get intellisense if everything's set up right. Here's the rules you need to follow...

  1. All Extension Methods need to be defined in a static class
  2. All Extension Methods need to be defined as a static method.
  3. All Extension Methods need to take at least one parameter defined as follows:
    this (keyword) string (type) parameterName
    Where the type is whatever type that you wish to extend.
  4. The "this" parameter needs to be the first parameter. All other parameters are optional--and must follow "this".

Also I recommend the following points...

  1. Extension Methods adds complexity to your project and more importantly your IDE must parse these--don't go extension method crazy.
  2. Extension Methods should be extensions only. It's not advisable to define them in commonly used NameSpaces such as "System". That could be bad...
  3. If you're writing too many extension methods--maybe it's time to write a custom class that inherits from that data type, No?

A powerful tool, they are--extend the .NET framework they can. Enjoy them you must.

Also, technically, you can use 'em in .NET 2.0--but its a lot more work.
http://msdn.microsoft.com/en-us/magazine/cc163317.aspx#S7

http://msdn.microsoft.com/en-us/library/bb383977.aspx

Zoidberg Away!

SQL Data Services Update - from IndyPass

Tonight's IndyPASS had some great information about the upcoming changes to Sql Data Services. For those who haven't read my other posts about SDS, it's a great emerging technology that moves your database into the cloud. I'd recommend that you really begin to look into this... in the coming years, it'll be tougher and tougher to host many of your app's databases in house.

Below are my basic notes from this week's meeting--they are scribbles, nothing more--but feel free to read 'em. Oh, regular readers, you'll note that this is a significant change in direction. Primarily--the ACE model is no more. True T-SQL and a SQL Server in the cloud. Hurrah?

-------------------------

SDS:

Data Sync

Microsoft has committed to offering a bilateral data sync for SQL Server 2008 to and from Sql Data Services.

Accessible from many languages including Java, Ruby, and PHP. Of course, this includes .NET

TDS is not nearly as efficient as Rest/Http calls--they'll be additional latency added by making calls to the server, however hopefully you'll reap the gains from the clustered data centers that Microsoft'll be offering through it's "SQL Server Fabric".

Provisioning Model...

Account - Each account has a billing relationship with Microsoft and ownership of one or more Virtual Servers.
Server - One or more databases including Virtual Master. Each database limited in size. One or more logins.
Database - One or more Sql Users
Server = server1.data.database.windows.net