Tag: design

How Do You Structure Your Singletons?

Background

I’ll skip over the discussion about why many people hate singletons (that’s a whole separate can of worms, but worth mentioning) because in the end, it’s not going to get rid of them. A singleton is a design pattern that ensures only one instance of the singleton object can ever be constructed. Often, singletons are made to be “globally accessible” in an application (although, I’m still not confident that this is actually part of the definition of a singleton). There are a handful of different ways to implement singletons… so what are they?

 

The Not-Thread-Safe-Singleton

With singletons, the main goal is to ensure that only one instance can be created. Below is a snippet of singleton code that works, but is not guaranteed in a multi-threaded environment:

    internal class NotThreadSafeSingleton
    {
        private static NotThreadSafeSingleton _instance;

        /// 
        /// Prevents a default instance from being created.
        /// 
        private NotThreadSafeSingleton()
        {
        }

        /// 
        /// Gets the singleton instance (not thread safe).
        /// 
        internal static NotThreadSafeSingleton Instance
        {
            get
            {
                if (_instance == null)
                {
                    _instance = new NotThreadSafeSingleton();
                }

                return _instance;
            }
        }
    }

The key take away point here is that if this singleton class is accessed across multiple threads, it is possible that two threads perform the null check and begin the constructor at the same time. Because this block of code is not protected with a lock a race condition occurs.

 

The Thread-Safe Singleton

If the key problem with the first example was that it is not safe across threads due to lack of locking… Then it should be pretty obvious that we just need to lock!

    internal class ThreadSafeSingleton
    {
        private static readonly object _instanceLock = new object();
        private static ThreadSafeSingleton _instance;

        /// 
        /// Prevents a default instance of the class from being created.
        /// 
        private ThreadSafeSingleton()
        {
        }

        /// 
        /// Gets the singleton instance (thread safe).
        /// 
        internal static ThreadSafeSingleton Instance
        {
            get
            {
                if (_instance == null)
                {
                    lock (_instanceLock)
                    {
                        if (_instance == null)
                        {
                            _instance = new ThreadSafeSingleton();
                        }
                    }
                }

                return _instance;
            }
        }
    }

That looks sort of weird though, doesn’t it? The double-check serves two purposes: a required check for thread safety and a performance optimization! The check inside of the lock actually guarantees that a single instance is created across threads. However, the check outside is an optimization because after the first instance is created, there’s overhead to acquiring the lock just to check if the instance exists.

For what it’s worth, this is actually my preferred method of coding singletons. I’ve been coding them like this for a while in C#, and I find they work nicely. However, I stumbled upon a posting by John Skeet (essentially, a programming god) who’s done a much better job at documenting singleton patterns than I have. In his analysis, he actually notes some drawbacks to this pattern. Firstly, he mentions it doesn’t work in Java, which is a great point. I primarily code in C#, but this is still important to acknowledge. Secondly, he calls upon ECMA CLI memory specifications that state it’s not guaranteed to actually be thread safe without memory barriers. This was slightly out of my comfort zone, so I admit I still have yet to look into this. Finally, I do agree that the pattern is easy to get wrong for more junior developers and as for performance, I’ve never considered it an issue at all. (Hopefully by now you’ve come back from his write-up to finish mine!)

 

Generic Singleton: A Quick Hand At It…

One of the big drawbacks I saw with the thread safe singleton implementation that I favour is the amount of boilerplate code. Every time I want a new singleton class, I have to code basically everything you see in the previous section. It’s redundant and I don’t want to do it. I can hear the singleton-haters saying “so STOP making them!” but as I said, that’s a discussion for a later post.

I decided I’d have a quick attempt at making a generic singleton! Check out my implementation below (and be warned that I flipped some condition checks in order to try and reduce the width of the text to fit nicely here…):

    internal class Singleton<T> where T : class
    {
        private static readonly object _instanceLock = new object();
        private static T _instance;

        /// 
        /// Prevents a default instance of the class from being created.
        /// 
        private Singleton()
        {
        }

        /// 
        /// Gets the singleton instance (thread safe).
        /// 
        internal static T Instance
        {
            get
            {
                if (_instance != null)
                {
                    return _instance;
                }

                lock (_instanceLock)
                {
                    if (_instance != null)
                    {
                        return _instance;
                    }

                    const string SINGLETON_EXCEPTION_MSG =
                            "A single private parameterless constructor is required.";

                    var constructors = typeof(T).GetConstructors(
                        BindingFlags.Public |
                        BindingFlags.CreateInstance |
                        BindingFlags.Instance);

                    if (constructors.Length > 0)
                    {
                        throw new Exception(SINGLETON_EXCEPTION_MSG);
                    }

                    constructors = typeof(T).GetConstructors(
                        BindingFlags.NonPublic |
                        BindingFlags.CreateInstance |
                        BindingFlags.Instance);

                    if (constructors.Length != 1 ||
                        constructors[0].GetParameters().Length > 0 ||
                        !constructors[0].IsPrivate)
                    {
                        throw new Exception(SINGLETON_EXCEPTION_MSG);
                    }

                    _instance = (T)constructors[0].Invoke(null);
                    return _instance;
                }
            }
        }
    }

Doesn’t look to shabby, right? You simply need to create a class with *only* a private constructor and everywhere you want access to the singleton, you say Singleton.Instance. It’s that easy.

Unfortunately, this isn’t as good as I initially hoped. Can you think of an example where this approach breaks down? My hint to you is everything you need to break it is posted right here. Unfortunate really because I thought I was onto something good there! ūüôā In reality, it may not be a bad foundation for your singleton implementations if you don’t like the boiler plate code I listed above.

 

Summary

There are many ways to write singletons, and some are clearly more robust than others. I’ve only shown you a couple here, but John Skeet’s post has a handful more which he prefers. It’s hard to argue with what he’s written (although, I’m not actually fond of his fourth implementation which he likes) because he’s done a great analysis on them. In the end, it’s important to know what a singleton actually is, when you might want to use it, and what the differences actually mean in various implementations.


Why Events? Flexibility.

Background

There are many different approaches to developing software, but in my opinion, the opposite ends of the spectrum end up being:

  • Knowing how the whole system looks, feels, and operates before coding a single line.
  • Having an idea of what the user wants and coding to make it happen.

Although I’m generalizing a lot here, it’s sort of like the battle between Waterfall and Agile. Okay, great. So what am I rambling on about here?

Well, in the first case, you know all the ins and outs of the system. You can structure your system so that almost no matter how complex it is, you can ensure that method A is always run immediately after method B which is etc… The design is completely controlled. You have a spec for how all the components work together. The problem? Well, most of this will be reserved for another write-up, but in our case there’s no flexibility. If that spec changes after your complicated system is already in place, how much code do you have to go change?

 

Enter: Events

Okay, so I hinted at why something like¬†Waterfall¬†might cause some headaches, but you don’t need to develop your software in an agile fashion to have flexibility. Events can help you with that!

If you’re not already familiar with what an event is, it’s simply a delegate that one would call when some particular criteria is met. In C#, which is what I’ll be assuming for this write-up, you add event handlers¬†to an event so that when the event is invoked, the event handlers get called (and they get called in the order that they were “hooked” onto the event). Splendid.

So what’s great about events? How are they going to fix your brittle code? Well, if you approach software design in terms of components in a system and how they interact, it’s really beneficial to think about how certain things react to each other. If you’re planning your whole system out ahead of time, you could just always call method A, then method B, and then method C in order every time you want something in particular to happen. But is that flexible? What happens when method B now calls an additional method, let’s say method D, due to some architectural changes that had to be made. Well… That’s all fine and dandy unless you have scenarios where you don’t want to run D in your A,B,C method calls you have everywhere.

So, what if you had thought about it this way:

  • I want B to run once A is run.
  • I need an event for A
  • I need to call method B in my event handler for event A
  • I want C to be run once B is run.
  • I need an event for B
  • I need to call method C in my event handler for event B
And then someone comes along and throws method D into the mix. Well, you know that there is at least one particular case where you want D to be run after B is run… So make another event handler! Your listing now changes to:
  • I want B to run once A is run.
  • I need an event for A
  • I need to call method B in my event handler for event A
  • I want C to be run once B is run.
  • I need an event for B
  • I need to call method C in my event handler for event B
  • I want D to be run when condition X is met after B is run
  • I need an event for B (which I already have!)
  • I need to call method C in my event handler for event B
    • I can add a whole second event handler for event B (so I get C then D called)
    • OR I can modify the existing event handler that calls method C to conditionally call method D when necessary

And now how do you check the condition? Pass in some fancy event args with your state.

 

Summary

Events can help you keep your code flexible when your structure is changing because they provide hooks into the code when certain conditions are met. You don’t need to rely on a firmed-up design for how methods are required to be called in some particular order. If your design changes because you want something to execute under different conditions, just hook up to the event that meets those conditions instead and re-write minimal code.

I’m huge on using events in my architectures, so I’ll try to write up a few more posts on events and why I like them. The flexibility I just described is only one very small part of it, and it certainly requires that you shift your perspective on how components in a system interact.


What Makes a Good API?

Background

My position at work allows me a bit of freedom in how I code and more importantly, influence how others code. I was recently having a conversation with a colleague about what I think makes a good API, from a high level. The context of our discussion was pertaining to developing a C# based API, but this really applies to any object oriented API.

I had two key points that I wanted to address, and while they’re not the only important things, I believe they’re often overlooked. The first thing is how people will¬†use¬†your API, so how they will call methods and use the results. The second point was about how people will¬†implement¬†your API should they want to extend your work and implement their own classes. Here’s what I was trying to drive home:

 

Usage:

As a programmer, when you use an API, you want it to be simple. If you’re using preexisting concrete classes, you want the methods to be easy to call and you want the results of those methods to be useful. How do you achieve this when making an API? Well, my guidelines are:

  • Make your inputs to the method as generic as possible
  • Make your return values as information-packed as possible

Simple right? If your inputs are generic enough, you can pass all sorts of things in. For example, if your function takes in a¬†ReadOnlyCollection, this function wouldn’t necessarily be as easy to use as one that takes only an¬†IEnumerable. If it’s not obvious, it’s because¬†IEnumerable¬†is a far more generic type. With an¬†IEnumerable, I can pass in an array, a list, a queue, a stack, or any collection. I can pass in anything that implements¬†IEnumerable! Conversely, if I require a¬†ReadOnlyCollection, all of my callers who may have these other various types of collections need to do some conversion to make it a¬†ReadOnlyCollection.

To the second point, you want as much information as you can get when calling a function. It’s almost the exact same argument as for parameters, but it works the opposite way. Consider if I have a function that returns an¬†IEnumerable. That means that for anyone that calls my function, all they’ll have access to is something they can enumerate over to get string values. Okay, that’s not too bad… But what if realistically everyone who calls your method really needs a list of strings? What if the common way to use your method is to get the IEnumerable result of your function, create a list out of it, and then add a few more items. Your API has basically created the additional step of requiring callers to create a list out of your return value. So… Why not just return a list? This is a lot more obvious if you look at your concrete implementation and notice that you likely do use something like a list (or some other concrete collection) when doing work inside the function. Why return something that’s harder to use?

 

Implementation:

The flip side to all of this is how other developers will implement the interfaces (or extend the classes) you provide in your API. And guess what? All of the arguments I just made for simplifying the life of the caller are essentially inverted for people implementing interfaces in your API.

If my interface calls for an¬†IEnumerable¬†to be passed in, then the only thing I can do is enumerate over it. Maybe in my own implementation this works fine… but what if someone else implementing your interface would benefit greatly from having a list? What if they can make an awesome optimization by knowing how many items are in the collection or by checking to see the if the 100th item is a particular value? Well, they can only enumerate, so this becomes difficult.

As for return types, before I argued that for the caller, returning as much information as possible is great. Consider this example. If in my API I managed to create a custom collection class that has all sorts of awesome metadata. Just to make up something completely random, let’s pretend I have a class for collections of integers and I have all these fancy properties on it that tell me the Mean/Median/Mode. The caller would say that’s awesome! Sweet! So much information returned to me just by calling this simple function! However, the implementer of your interface is now thinking, “Oh crap… First you restrict my inputs to something super basic and then I have to¬†somehow¬†return that fancy object?! How the heck am I going to do that?!”

 

Summary:

To summarize what I wrote here, I think a good guideline for API’s comes down to:

  • Making inputs generic enough to ease the life of the caller and provide just enough information to the implementer of the method.
  • Make return values as information-packed as possible without placing the burden of creating complex classes (and adding dependencies) to the implementer of the method.

Simple right? If your API is designed such that others will not be extending it (and it’s really only people calling your methods) then you can completely bias your design in favour of the caller!


  • Nick Cosentino

    Nick Cosentino

    I work as a team lead of software engineering at Magnet Forensics (http://www.magnetforensics.com). I'm into powerlifting, bodybuilding, and blogging about leadership/development topics over at http://www.devleader.ca.

    Verified Services

    View Full Profile →

  • Copyright © 1996-2010 Dev Leader. All rights reserved.
    Jarrah theme by Templates Next | Powered by WordPress