Friday, October 14, 2005

Singleton Duplicity in 5 Minutes

Once you've finished laughing at the tongue-in-check title of this post, you can read on for a discussion of the Singleton Pattern. This is not meant to be an all-inclusive resource for Singleton development, but rather to provide a birds-eye view of what the pattern is all about, and one (extremely quick) way to implement it in C#.


Note that the Singleton is a design pattern, which means it is not language specific. I use C# in my code examples simply out of personal preference; however you can implement this pattern using just about any object-oriented language.



What is a Singleton?

In the simplest terms, a Singleton is a class for which there is only a single shared instance. Any code that accesses the class uses the same instance of the object. Consequently, Singletons must provide a global point of access to their instance.



Why use a Singleton?

Think about your computer. There are certain shared resources of which there can only be one. For example, your computer has a single keyboard that is used by all of your applications. You probably (but not necessarily) have only one mouse. From a software standpoint, your Operating System can reasonably have only one process manager.



Sometimes there are programmatic situations that require one and only one of something, too. A great example of this is a logging service. A logging service only needs to exist in memory one time, and that instance can be shared across all functionality that needs to log an event.



Quick and Dirty C# Singleton

Here's an example of an extremely basic Singleton class. In the real world, you'll want to make sure that any Singleton class is thread safe, but the intent here is to simply provide an overview of the basic Singleton framework.


public class Singleton
{
private static Singleton instance;

private Singleton()
{
}

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

public string SayHello()
{
return "Hello World!";
}
}

In the example above, you'll notice that the constructor is private rather than public. This prevents the class from being instanciated. Because the constructor uses the "private" access modifier, it is inaccessible to any code outside of the Singleton class. But, since a private method (and the constructor is simply a method) is accessible from within the same class, code within that class can create an instance of it. In this way, we force all access to the object to go through the GetInstance method, which will return the static (shared) instance.



To use the object above, you might have code that looks something like this:

Singleton mySingleton = Singleton.GetInstance();
string helloMessage = mySingleton.SayHello();
mySingleton = null;

Note that although the reference to the Singleton instance is destroyed when the local object is made null, the instance itself remains, and can be reused by subsequent calls to the GetInstance method. In the first example, note that the instance variable is private, so it is not implicitly accessible to code outside the Singleton class.



Other Considerations

There are multiple ways to implement the Singleton Pattern. The code provided here is merely an example of one implementation method to facilitate discussion of the pattern itself.



If you're planning on implementing the Singleton pattern, do so with care. There are some in the industry who refer to a Singleton as an anti-pattern because it is so often misused. Make sure any objects that interract with singletons are still loosely coupled, and that you're not using a Singleton simply as a global variable.



For more information on Singletons, visit these resources:

Tuesday, October 11, 2005

Sorting Directly in a Data Table

One of the nice things about ADO.NET is that it provides a rich set of functionality for sorting without retrieving new data from the database. Furthermore, with ADO.NET, data binding has moved out of the fringe and is now considered the norm – particularly where Web Applications are concerned.



The standard approach to filtering and sorting data in .NET is to use a DataView. In a nutshell, the DataView acts as a layer between your bound object and the underlying data object. For example, to use a DataView to sort the data in a DataGrid, instead of binding the grid directly to a DataSet (just for the sake of argument), you would declare a DataView and set its source to the DataSet. Then you’d configure the sort options on the DataView, and bind the grid to it. Viola! Instant sorting under the hood without the need to write any code!



What if you have a situation where you need to sort data without binding to it? In that case, using the DataView isn’t a viable option. Well, take heart – the DataTable object provides a mechanism that allows you to sort and filter the data directly on the Data Table.



You can use the Select method of a Data Table to sort and filter the data. The syntax is:



    datatable.Select(filterExp, sortExp, rowstatevalue)



The select method returns an array of rows that meet the filter criteria in the sort order specified. Furthermore, you can control what types of rows are returned. You say you only want the rows that have been added since you populated the Data Table? No problem – just set the RowStateValue parameter to DataViewRowState.Added.



What if you want to sort, but not filter the data? That’s not a problem either. You can pass in null to any parameter you don’t want to use. For example:



    DataRow[] sortedRows = customerTable.Select(null, "LastName");

Monday, October 10, 2005

C# Ternary Operator

Although it is sometimes misused, the ternary operator (also called the conditional operator, although I personally prefer ternary) in C# can be quite a timesaver. For those who don’t’ know, it is roughly equivalent to the IIF function in VB.



The C# language specification contains a really convoluted definition for what essentially amounts to a very simple operation. In my own words, the syntax for using the ternary operator is as follows:



    test-condition ? true part : false part
;



In other words, if “test-condition” evaluations to true, the true part code will execute. Otherwise, the false part code will execute. It’s like an if-then-else bundled into one statement. In fact, the statement above may be rewritten to:




if
(
test-condition)


{

    //true part code here

}

else

{    //false part code here

}



Arguably, a programmer could get carried away with what amounts to a shortcut. One great use of the ternary operator that I’ve found, though, is assigning the value to a variable at the time of declaration based upon a specified condition. For example, reading the contents of a config file, and storing the value in a variable.



Note that when reading from a config file, if the specified key does not exist, the value returned will be null. If you then try to perform a string operation (like testing the value of the string), you’ll end up with a nasty little System.NullReferenceException. To avoid this, I use a technique with the ternary operator that allows me to grab my value, and account for the possibility of null all in one statement. Here’s an example:




//read a setting from the config file,


//and assign it to the mySetting string:

string mySetting = ConfigurationSettings.AppSettings["KeyName"] != null ?
      
ConfigurationSettings.AppSettings["KeyName"] : string.Empty;



Another great use is for the ternary operator is when retrieving values from a Data Reader or Data Table. You can use a similar approach to the example above to test for a condition of “== DBNull.Value” before performing any operations on the object that may potentially have a null value.

Tuesday, October 04, 2005

Implementation and Inheritance Primer

* Note: This post is geared toward beginners, and should be relatively easy to understand. (Note 2: forgive the lousey code formatting -- I'll figure something out for that)

Lacking a more in-depth topic, I thought I’d take a few moments today to share a great way to explain the difference between inheritance, and implementation inheritance (that is, implementing or inheriting an Interface).

To put it as a one-liner, inheritance is like saying “is a…”, whereas implementation inheritance is like saying “acts like…”.

Consider the following C# code example. In the example, we have an abstract class named “Dog”. (Recall that an abstract class cannot be instantiated – it may only be inherited)

public abstract class Dog : IDog

{

private string _name;

public Dog()

{

//Standard object constructor

}

public void Bark(int times)

{

//Actual code here to make the dog bark

}

public void Sit()

{

//Actual code here to make the dog sit

}

public string Name

{

get

{

return _name;

}

set

{

_name = value;

}

}

}

The Dog object presumably encapsulates all of the basic required functionality of a dog. We have a Name property and methods for Bark and Sit. Any object that class that inherits Dog will have access to all that functionality.

We also have an Interface, aptly named IDog. (Note to newbies: best practices are that Interface names are always prefixed with the letter I)

public interface IDog

{

void Bark(int times);

void Sit();

string Name{get; set;}

}

In contrast to an abstract class, an interface does not contain any functional source code. Rather, it merely defines the way in which objects that implement it may be interacted with. In our example, any classes that implement the IDog interface must have their own Name property and Bark and Sit methods.

The following are examples of implementing the IDog interface, and inheriting the Dog class:

public class Poodle : Dog

{

public Poodle()

{

//Because this inherited the actual dog object,

//we can make the base class do the bark

base.Bark(3);

}

}

public class Collie : IDog

{

public Collie()

{

//standard constructor, but we don't have

//any functionality available from IDog -

//it simply defines what methods and properties we

//must have

}

public void Bark(int times)

{

//required by IDog interface

throw new NotImplementedException();

}

public void Sit()

{

//required by IDog interface

throw new NotImplementedException();

}

public string Name

{

//required by IDog interface

get

{

throw new NotImplementedException();

}

set

{

throw new NotImplementedException();

}

}

}

Note that in our example, the Dog class itself implements the IDog interface. Strictly speaking, it doesn’t have to. However, if this were real world code, we could use the IDog interface as one way to address the Class Factory pattern as in the following example:

public class DogFactory

{

public DogFactory()

{

}

public IDog GetDog(int height)

{

if (height <>

{

return new Poodle();

}

else

{

return new Collie();

}

}

}

In the real world, this approach is most often seen in functionality that interacts with databases. Taking this approach allows the programmer to write code that will interact with logic that is highly optimized for a specific database platform, while still affording the ability to support multiple platforms. I’ll discuss more about this topic in a future post.

Sunday, October 02, 2005

Finding Your Audience

Arguably, one of the challenges of writing – particularly technical writing – is deciding who your audience will be. Are you writing to a very high level that will help PhD candidates conduct their research, or are you keeping it simple enough to help a newbie or perhaps the casual layperson who doesn’t know a lot about technology?

My intent with this blog is evolving. Originally, I waxed poetically that perhaps I would be able to build something to “take it to the next level”. I’m beginning to see, however, that the best value for this blog may lie in helping out people who are perhaps not so technical.

Years ago I started an MSN group to act as an online study group for college students taking their first VB.NET programming course. The group has since taken on a life of its own (admittedly, I rarely even have to look in on it anymore), but I’m quite pleased that it has helped a tremendous number of people along the way. There just don’t seem to be enough resources to help people who lack a fundamental baseline in programming.

My parents read my blog. There – I said it. Although I doubt Steve Jobs, Bill Gates, or Sergey Brin could boast such personal success, it does create some unique challenges. First, my mom continues to proof-read my work. I can get away with just about any technical error, but damn it, those words had better be spelled correctly, and word choice is up for evaluation (my mom's comments on my latest blog posts relative to my choice of the word “indeed”: You have to now retire your favorite word for at least a month or six. Indeed, it is inappropriate to use "indeed" in every blog. People who read you will think this is your personal crutch that replaces "uhhhh", or "ya know?"). Indeed, I see her logic.

Back to the topic at hand, I still need to decide who my audience is. While this is a work in progress and is apt to change over time, I’ve decided to write to the appropriate level of the topic I’m discussing (e.g. if I’m blogging on multi-threading, I’ll be writing for an audience I assume is somewhat familiar with the terms), but I’ll try to include more links to explain technical terms and concepts.

A few thoughts I have on upcoming blog posts:

Kids Programming Language

Years ago I toyed with the idea of writing my own programming language. The simple problem was that while I had the desire to build a better mousetrap, I had no idea how to make the existing mousetrap any better.

Morrison Schwartz seems to have tackled that issue with Kids Programming Language.

KPL is freeware (that will output .NET code, no less), and from what I’ve reviewed so far, it provides an easy way to render graphics without worrying about all the low-level details. There are several example programs available that do everything from rendering a Mandelbrot set, to complete graphical video games.

If you have kids and you want to get them interested in programming, or even if you don’t have kids but have a taste for nostalgia, I recommend you take a look.