INTRODUCTION: Singleton is the design pattern that is the easiest to abuse and hardest to nail down. You must correctly ascertain when they are appropriate and to what scope. But first, what is a Singleton? Singletons are classes that should only be instantiated once per application. These classes typically represent a set of functionality that is global to the application, yet deserves to be encapsulated into a single set of functionality.

The Singleton should expose itself as a static property from the class definition, making available public instance methods only from the referenced static property. Singletons should have a single purpose. Some examples are a Window manager for an Application, or a Report generator. I’ve even used a Singleton to manage the state of a WinForms ribbon. The main thing to remember is that the Singleton only gets instantiated at a global scope and should have a narrow focus.

For an example, let’s make a Singleton that performs acts as a state manager for a fictional application. This application will represent a wizard that must move between three steps.

EXAMPLE:

public class AppSingleton
{
  // Private static reference to the long instance of this
  // Singleton.  
  private static readonly AppSingleton _instance = new AppSingleton();

  // Current state of the application.
  private State _state = State.Start;

  public State State => _state;

  // Private constructor ensures that only the Singleton
  // can create new instances.
  private AppSingleton() { }

  public AppSingleton Instance => _instance;

  // Instance method to change the state of the application,
  // returns the resulting app state.
  public State MoveNext()
  { 
    switch(_state)
    {
      case State.Start:
        _state = Middle;
        break;

      case State.Middle:
        _state = Finish;
        break;

      case State.Finish:
        _state = Completed;
        break;
    }
    return _state;
  }

  // Instance method to change the state of the application,
  // returns the resulting app state;
  public State MovePrevious()
  {
    switch(_state)
    {
      case State.Middle:
        _state = First;
        break;

      case State.Finish:
        _state = Middle;
        break;
    }
  }

  // Here we can tell the singleton to perform some work.
  // You do not need this method signature, you can have
  // as many "worker" methods as is necessary.  This is 
  // just an example!
  public void DoSomething(params object[] args)
  {
    // DO some work!
  }
}

public enum State
{
  Start, Middle, Finish, Completed
}

public class Program
{
  public static void Main(string[] args)
  {
    AppSingleton.Instance.DoSomething(1);
    var state = AppSingleton.Instance.MoveNext();

    if(state != State.Start) 
    {
      // We moved state!  Do something else!
      AppSingleton.Instance.DoSomething(2);

      // Let's go back and try again!
      state = AppSingleton.Instance.MovePrevious();

      // Etc.
    }
    else
    {
      // Uh-oh, the singleton says it cannot move.
    }
  }
}

Here our application state is managed by the AppSingleton. The main program simply attempts to manipulate that state by providing data to the Singleton to process. In a real app, there would be user interaction that would drive the wizard forwards and backwards.

CONCLUSION: Singletons are a very powerful arrow in your C# quiver. Single-user applications are great usages for them. If you are not sure if you should use a singleton, ask yourself these questions:

  • Does the Singleton represent a single state within the application?
  • Does the Singleton have logic that should be encapsulated?
  • Do you need to control the object lifecycle for the Singleton?

If your answer is yes to these questions, a Singleton is right for you!

INTRODUCTION: I may be about to start a holy war, but this is actually a topic I’ve had to very recently deal with at work. For years I’ve standardized the theming of websites on jQueryUI and ThemeRoller. It was simply the thing to do. All the cool kids did it. It was kinda easy and if you followed the rules you’d (pretty much) avoid trouble. ThemeRoller is easy to use, there’s tons of great pre-built themes, and it got the job one. Then came Bootstrap, and it set the web on its ear. Bootstrap is more than just a theming mechanism, it’s a complete way of designing your website from both a layout and a stylistic perspective.

For years we were told the web would magically make it easy to write consistent applications that would work anytime, anywhere. For years we fought with browser incompatibilities, indecisiveness on visual standards, and a general lack of any kind of standardization on how the UI of a web application should act. Twitter decided enough is enough and dropped a big bomb on the whole net. If you want a consistent UI experience, you need a consistent tool and the appropriate conventions to go with it.

Bootstrap is that tool. Bootstrap enforces those conventions. Bootstrap not only assigns the pretty colors, but it tells your layout where to go, how wide to be based on the device, and whether or not certain elements should even be visible based on the device. All without the web developer (notice I did not say graphic/web designer) having to lift a finger. Bootstrap really is the closest thing to a magic bullet that the web has seen since ASP.Net was born.

CONCLUSION: So what do you do about all your old websites? If they ain’t broke…. But if you do have to refactor the UI for whatever reason, you should really look at converting them to Bootstrap. The shelf life of jQueryUI is basically up. Time to learn Bootstrap.

INTRODUCTION: Let’s take a poll… As a developer, what keeps you on your toes, yet mind-numbingly bored at the same time? For me, it’s null reference checking. I know I’m not alone and that it’s such a pervasive problem that Microsoft decided to do something about it. Welcome to the enlightened world of Null Propagation.

Null Propagation is a new feature in C# 6 that allows you to chain together nullable operations into a single chain that short-circuits on the first null reference, without worrying about having to check the whole chain for null references.

This is one of the most impressive solutions to the mess that arises from continuously nested null reference checks. Let’s look at some code.

EXAMPLE 1

string oops = null;
oops = MethodThatMayReturnNull();
if(oops != null)
{
    // Assume an extension method on String.  **
    oops.MethodThatProcessesOopsThatMayReturnNull(someOtherValue);

    if(oops != null)
    {
        // You get the picture...
    }
}

** (see: This Article)

What a mess!

EXAMPLE 2

string oops = MethodThatMayReturnNull()?.MethodThatProcessesOopsThatMayReturnNull(someOtherValue); // Just keep chaining!

Where’s the Null Reference checks? See that ? between methods? It means that the second method will be called only if the first method does NOT return a null value. If it does return a null value, then the call chain is broken and oops contains a null. That’s when you test for null: when it actually means something semantically to the application.

One of the most common usages of Null Propagation is calling events. Turn 4 lines of code into 1!

// Old way
if(eventDeclaration != null)
{
    eventDeclaration(this, EventArgs.Empty);
}

// The Null Propagation Way
eventDeclaration?.Invoke(this, EventArgs.Empty);

CONCLUSION: I love C# 6! This is a game changer. You write better code that is both easier to read, and more reliable (admit it, how many times have you neglected that Null Reference Check because you were certain you’d never have a Null Reference. How’d that work for ya?) Now, with Null Propagation, there’s no excuse for writing code that doesn’t use proper Null Reference checking because your Null Reference checks are only needed for business logic, not boilerplate.

INTRODUCTION: The Gang of Four were pretty smart folks. They gave us a lot of design patterns to use to make better application architectures. One of the patterns they gave us was the Facade, which is generally used to provide common functionality for objects that don’t necessarily have a polymorphic purpose for the object. In C# we use static classes to build facades, which is great. Facade classes allow you to group together similar functionality and because the classes and methods are static, there is an expectation that they should work on any instance of the object(s) being manipulated.

Extension methods take the Facade one step further. Instead of having to reference a Facade class specifically, the extension methods bring the facade methods right to the class(es) they apply to. You might be asking right now, “What is an extension method?” Extension methods are defined as static methods of static classes that receive the context of a single object instance that allows you to present the functionality of the method as an extension of the object.

EXAMPLE

public static class MyExtensionFacade
{
    // Normal facade implementation
    public static void IncrementInt32ByDecimal(out int source, decimal value)
    {
        source += (int)(value + 0.5m);
    }

    // Extension Method
    // Notice the use of the this keyword, it defines the object that the
    // extension method works on.
    public static void IncrementByDecimal(this int source, decimal value)
    {
        IncrementInt32ByDecimal(out source, value);
    }
}

public class Program
{
    public static void Main(string[] args)
    {
        int i = 10;
        decimal d = 15.75m;

        // Call facade method as normal.
        MyExtensionFacade.IncrementInt32ByDecimal(out i, d);

        Console.WriteLine($"i = {i}");

        // Call as extension method
        i.IncrementByDecimal(d);

        Console.WriteLine($"i = {i}");
    }
}

CONCLUSION: As you can see from the example, the extension method is much simpler to call and makes your code cleaner. As a matter of fact, the entire LINQ framework is a series of extension methods. They can be a very valuable and powerful arrow in your quiver of Ninja tricks.

INFO: If you are looking for information specifically related to ASP.Net MVC, then continue your Google Search.  This article is about the MVC Design Pattern and a simple implementation in C#.

OVERVIEW: The MVC (Model-View-Controller) design pattern was introduced by the Gang of Four as a means of describing an application from the perspective of the three layers of the application (Data – Presentation – Logic).  Over the years many different implementations of the MVC pattern have emerged.  I am now about to introduce my personal implementation which has served me well for nearly a decade.

THE MODEL:  Since this is a .Net blog, I will give my example using Microsoft’s Entity Framework.  Whether you prefer to design on the database or in code, the DbContext you create is the perfect repository for your data.  As a matter of fact, the objects created by the DbContext are perfect for your Models, so you don’t have to write any special code!

THE VIEW:  Many MVC implementations lock the view into a specific technology.  I do not.  Instead, I expose Views as Interfaces.  What implements the interface is irrelevant. Here is an example View:

public interface IView
{
    // This is the interface that all views will derive from. This
    // base view will allow us to generalize the controller.
}

public interface ISampleView : IView
{
    // Properties representing your data
    List<Model%gt; ModelData { get; set; }

    // Actions that the controller responds to
    event EventHandler<Model> SaveModelData;
    event EventHandler<Guid> LoadModelDataByGroupUID;

    // Actions that the view responds to
    void BindModelData();
}

Now that we have defined our view, we can implemented it in many different ways. Here’s a simple Web Form that implements the above view.

public class SampleView : Page
{
    public List<Model> ModelData { get; set; }

    public void BindModelData()
    {
        // Assume the ASPX file defines a ListView named ListView1
        // and we want to sort on a specific field before displaying
        // The data.
        ListView1.DataSource = ModelData.OrderBy(x => x.SortField).ToList();
        ListView1.DataBind();
    }
    
    public event EventHandler<Model> SaveModelData;
    public event EventHandler<Guid> LoadModelDataByGroupUID;
}

The view doesn’t have a lot of moving parts (as is correct). The only real work done in the view is shaping the data for presentation. The main work is handled in the Controller.

THE CONTROLLER: Now we’re talking about the main part of the application. This is where the real work is done. Controllers are typically plain old classes that register a view and manage the interaction between the needs of the view and the storage and manipulation of the data. Often the Controller is a stand alone class, but some frameworks provide an abstract class that provides reusable features. I will instead provide a IController interface to provide a simple Initialize method.

public interface IController
{
    Initialize(IView view);
}

Pretty simple, but this ensures that the View implementation has a consistent contract for registering itself with the controller.

Now, let’s take our example and actually load and save the Model from our SampleView.

public class SampleController : IController
{
    private IView _view;
    protected ISampleView SampleView { get { return _view as ISampleView; } }

    public Initialize(IView view)
    {
        _view = view;
        if(SampleView != null)
        {
            SampleView.SaveModelData += SampleViewSaveModelData;
            SampleView.LoadModelDataByGroupUID += SampleViewLoadModelDataByGroupUID;
        }
    }

    protected void SampleViewSaveModelData(object sender, Model data)
    {
        if(SampleView != null)
        {
            using(var context = new SampleDbContext)
            {
                var existing = context.Models.FirstOrDefault(data);
                if(existing != null)
                {
                    // Copy fields from data to existing
                }
                else
                {
                    context.Models.Add(data);
                }

                context.SaveChanges();
            } 
        }
    }

    protected void SampleViewLoadModelDataByGroupUID(object sender, Guid key)
    {
        if(SampleView != null)
        {
            using(var context = new SampleDbContext)
            {
                SampleView.ModelData = context.Models.Where(x => x.GroupUID = key).ToList();
                SampleView.BindModelData();
            }
        }
    }
}

CONCLUSION: The MVC pattern allows for complete abstraction of the data, presentation and manipulation of that data. Here I’ve provided an overly simplistic example of a complete MVC example. I would strongly encourage you to take this example and expand upon it. For example, you can add fields to your View and then incorporate them into the logic of your controller. The sky is the limit!