Tag: code

Python, Visual Studio, and C#… So. Sweet.

Python, Visual Studio, and C#

Python & C# – Background

Let’s clear the air. Using Python and C# together isn’t anything new. If you’ve used one of these languages and at least heard of the other, then you’ve probably heard of IronPython. IronPython lets you use both C# and Python together. Pretty legit. If you haven’t tried it out yet, hopefully your brain is starting to whir and fizzle thinking about the possibilities.

My development experiences is primarily in C# and before that it was VB .NET (So I’m pretty attached to the whole .NET framework… We’re basically best friends at this point). However, pretty early in my career (my first co-op at Engenuity Corporation, really) I was introduced to Python. I had never really used a dynamic or implicitly typed language, so it was quite an adventure and learning experience.

Unfortunately, aside from my time at EngCorp, I hadn’t really had a use to continue on with Python development. Lately, I’ve had a spark of curiosity. I’m comfortable with C#, sure, but is that enough? There’s lots of great programming languages out there! It’s hard for me to break out of my comfort zone though. I’m used to C# and the awesomeness of Visual Studio, so how could I ever break free from these two things?

Well… I don’t have to yet.

Python Tools for Visual Studio

This was a nice little treasure to stumble upon:

But I didn’t really know what it was all about. I had heard of IronPython, and I knew I could use Python with C# together, so what exactly is “Python Tools“?

After I watched the video that the Visual Studio team tweeted out, I was captivated. Did this mean I could revisit python without having to leave the comfort of my favourite IDE? You bet. First thing I did after watching this video (and yes, I somehow managed to hold back the excitement and wait until the video was done) was fire up Visual Studio. I run with Visual Studio 2012 (the dark theme too) so in my screenshots that’s what you’ll be seeing. Once Visual Studio has loaded:

  • Go to the “Tools” menu at the top of the IDE.
  • Select the “Extensions and Updates…” menu item.
  • You should see the “Extensions and Updates” dialog window now.

You’re going to want to search for “Python Tools” after you’ve selected the “Online” option on the left side of the dialog. It should look something like this:

Python Tools - Visual Studio Extensions and Updates

Installing Python Tools for Visual Studio is pretty easy. Make sure you’re searching online and search for “Python Tools”.

After you’ve followed all of the installation instructions, it’s time to make sure the installation worked. Simple enough!

  • Go to the “File” menu at the top of the IDE.
  • Go to the “New” menu item.
  • Select the “Project…” menu item.
  • You should now see the “New Project” dialog

To ensure Python is now available, try seeing if you have Python project templates available:

Verify Python in Visual Studio

To verify that Python is now available in Visual Studio, check under the installed templates. It should be under “Other Languages”.

Hopefully it’s there. If not, or if you have any other install questions, I highly recommend you refer to the official site and follow along there. This is what got me up and running with my current machine, but if your setup is slightly different you should definitely follow their instructions. That’s it! You have Python Tools! But what else would make your C#, Python, and Visual Studio experience EVEN BETTER? The answer to that question is of course IronPython. Head on over to this page and get yourself setup with the latest cut of IronPython. Once that’s setup, you should have all the fancy tools you need!

Print to Console – Your First C#/Python Application

I’m sure you feel the excitement building. I’ll start by saying the code is all available online, so even though I’ll have snippets and pictures here, you can download all of the source and follow along that way if you want. Otherwise, I’ll do my best to walk you through how I set things up! This application is going to be pretty simple. It’s a tiny bit bigger than a “Hello World” application, with the difference being that you tell Python what you want to print to the console. Easy-peasy, right?

First up, let’s make a new C# console project.

  • From Visual Studio, go to the “File” menu at the top of the IDE.
  • Select the “New” menu item.
  • Select the “Project” menu item.
  • You should see the “New Project” dialog.
  • Select the “Visual C#” template on the left of the dialog.
  • Select “Console Application”.
  • In the framework dropdown at the top of the dialog, select .NET 4.5
  • Fill in the details for where you want to save your project.
  • Press “OK”! And we’re off!

Now that you have a console application you’re going to want to add in all the dependencies we need. If you look at the project in your solution explorer, you’re going to want to add the following dependencies:

IronPython Dependencies in Visual Studio

Add the IronPython and Microsoft.Scripting dependencies through the solution explorer in Visual Studio.

If you’re having trouble getting the dependencies set up, remember you can always download the source projects I’ve put together. Now that you have all the necessary dependencies, here’s the source for our little application:

using System;
using System.Collections.Generic;
using System.Text;
using System.Diagnostics;

using IronPython.Hosting;

namespace PrintToConsole
{
    internal class Program
    {
        private static void Main()
        {
            Console.WriteLine("What would you like to print from python?");
            var input = Console.ReadLine();

            var py = Python.CreateEngine();
            try
            {
                py.Execute("print('From Python: " + input + "')");
            }
            catch (Exception ex)
            {
                Console.WriteLine("Oops! We couldn't print your message because of an exception: " + ex.Message);
            }

            Console.WriteLine("Press enter to exit...");
            Console.ReadLine();
        }
    }
}

Let’s walk through what this code is doing:

  • First we’re getting input from the user. This is some pretty basic C# stuff, but we’re simply printing a message to the console and taking in the text the user enters before they press enter.
  • Next, we create a Python engine instance. This is the class that’s going to be responsible for executing python for us!
  • The code that exists within the try block tells our engine instance to execute some python code.
    • The print() method that you see being passed to the engine is the syntax since Python 3.0.
    • The parameter that we’re passing into the print() method is a python string… but we’re sticking our user input inside of it as well!
    • It’s also important to note that we’re building up a C# string that contains all of the Python code that will be executed and passing that to the engine.
  • I have a catch block here to catch any unexpected problems. Can you think of any?
    • What happens if your user input some text with a single quote?
  • The last part of the application just asks the user to press enter when they are all done.

Simple! There’s your first C# + Python application! You can see the source for the whole thing over here.

Run External Script

So this is great: you can now run some python code from within C#. Totally awesome. But what about all those python scripts you have written up already? Do you need to start copying and pasting them into C# code files and start to try and format them nicely? The answer is no, thankfully! Let’s start by following the exact same steps as outlined in the first example. You should be able to set up a new .NET 4.5 C# console project and add in all the same dependencies. Once you have that put together, you can use the following source code:

using System;
using System.Collections.Generic;
using System.Text;

using IronPython.Hosting;

namespace RunExternalScript
{
    internal class Program
    {
        private static void Main(string[] args)
        {
            Console.WriteLine("Press enter to execute the python script!");
            Console.ReadLine();

            var py = Python.CreateEngine();
            try
            {
                py.ExecuteFile("script.py");
            }
            catch (Exception ex)
            {
                Console.WriteLine("Oops! We couldn't execute the script because of an exception: " + ex.Message);
            }

            Console.WriteLine("Press enter to exit...");
            Console.ReadLine();
        }
    }
}

This script looks similar, right? Before I explain what it does, let’s add in the Python script that you’ll be executing from this console application.

  • Right click on your project in the solution explorer.
  • Select the “Add” menu item from the context menu.
  • Select the “New Item…” menu item.
  • You should see the “Add New Item” dialog.
  • You’ll want to add a new text file called “script.py”.

It should look a little something like this:

Add new Python script in Visual Studio

In the “Add New Item” dialog, select “Text File” and rename it to “script.py”.

The next really important step is to ensure that this script gets copied to the output directory. To do this, select your newly added script file in the solution explorer and change the “Copy to Output Directory” setting to “Copy Always”. Now when you build your project, you should see your script.py file get copied to the build directory. Woo! You can put any python code you want inside of the script file, but I started with something simple:

print('Look at this python code go!')

Okay, so back to the C# code now. This example looks much like the first example.

  • Wait for the user to press enter before executing the Python script. Just to make sure they’re ready!
  • Create our engine instance, just like in the first example.
  • In the try block, we tell the engine to execute our script file. Because we had the file copy to the output directory, we can just use a relative path to the file here.
  • Again, we’ve wrapped the whole thing inside of a try/catch to ensure any mistakes you have in your python script get caught.
    • Try putting some erroneous Python code in the script file and running. What happens?
  • Finally, make sure the user is content with the output and wait for them to press Enter before exiting.

Look how easy that was! Now you can choose to execute Python code generated in C# OR execute external Python scripts!

Summary

It’s awesome to see that you expressed an interest in trying to marry these two languages together inside of a powerful IDE. We’re only breaking through the surface here, and admittedly I’m still quite new to integrating Python and C# together. I need to re-familiarize myself with Python, but I can already see there is a ton of potential for writing some really cool applications this way.

In the near future, I’ll be discussing how the dynamic keyword in C# can actually allow you to create classes in Python and use them right inside of C#… Dynamically!

Both of these pages were helpful in getting me up and running with C# and Python together:

Source code for these projects is available at the following locations:


Events: Demystifying Common Memory Leaks

Events: Demystifying Common Memory Leaks

Background

If you’ve poked through my previous postings, you’ll probably notice that I love using events when I program. If I can find a reason to use an event, I probably will. I think they’re a great tool that can really help you with designing your architectures, but there are certainly some common problems people run into when they use events. The one I want to address today has to do with memory leaks. That’s right. I said it. Memory leaks in your .NET application. Just because it’s a managed language doesn’t mean your code can’t be leaking memory! And now that I’ve got your attention, let’s see how events might be causing some leakage in your application.

(There is source that you can download and run. Check the summary section at the end!)

Instance-Scope Event Handlers

One of the most common ways to set up an EventHandler in C# is by having them defined for the entire scope of the instance. Consider for a moment the form designer in Visual Studio. When you double click on controls you get some handler created for the default event on that control. See how the EventHandler was declared though? You get a method declared that has a sender and some type of EventArgs. Pretty standard stuff here and there’s nothing ground-breaking about it. So what’s the problem with this method?

Well, there’s nothing wrong with it as long as you know how to clean up after yourself. Consider the following two classes:


private class ObjectWithEvent
{
    ~ObjectWithEvent()
    {
        Console.WriteLine(this + " is being finalized.");
    }

    public event EventHandler<EventArgs> Event;

    public void UnhookAll()
    {
        Event = null;
    }
}

private class ObjectThatHooksEvent
{
    public ObjectThatHooksEvent(ObjectWithEvent objectWithEvent)
    {
        objectWithEvent.Event += ObjectWithEvent_Event;
    }

    ~ObjectThatHooksEvent()
    {
        Console.WriteLine(this + " is being finalized.");
    }

    private void ObjectWithEvent_Event(object sender, EventArgs e)
    {
        // some fancy event
    }
}

The first class has an event that our second class can hook onto. You’ll notice in the second class that I’ve defined an instance-scope handler that we can hook up. This is the exact same syntax for declaring an event handler that you’d get from the form designer if you’re doing GUI programming.

The danger with this setup is that until you unhook the event, the object that hooks onto the event will not be freed. “Well, no problem!” is what you might be thinking. You know how to solve that. You can just unhook the event in the second class’s finalizer/deconstructor.

…Except that won’t work. The finalizer will not get called on the instance of the second class until the event has been unhooked! It’s a bit of a chicken-or-the-egg problem, but it makes sense. A finalizer will only be called when the reference is being cleaned up, but the instance can’t be marked for cleaning because something is still using its event handler. See why this can get a bit dangerous?

Anonymous Delegate (No Parent Reference)

So this is an example of hooking events where you won’t get a leak. Why am I showing it? Well, in the next section I’ll make a small tweak to it which will make it behave just like the first scenario I described.

Let’s assume we have two classes again. I’ll use the first class from my first example (the object with the event) and this new class here that we’ll use to hook onto the event:

private class HookWithAnonymousDelegate
{
    public HookWithAnonymousDelegate(ObjectWithEvent objectWithEvent)
    {
        objectWithEvent.Event += (sender, args) =>
        {
            // handle your event
            // (this one is special because it doesn't use anything related to the instance)
            Console.WriteLine("Event being called!");
        };
    }

    ~HookWithAnonymousDelegate()
    {
        Console.WriteLine(this + " is being finalized.");
    }
}

Notice the difference from the first example? I’ve hooked up an anonymous method (using a lambda expression) to our event instead of declaring an instance-scope event handler. It’s a small change, and for the most part, I might argue that this is just a stylistic thing. If you don’t ever plan on unhooking the event then it’s not such a big deal to go with anonymous methods, but if your method body grows pretty big the code can definitely get unsightly.

Anyway… sweet! We just hooked up to our event and we don’t have the scary leak situation that we did in the first scenario. How cool is that? Well…

Anonymous Delegate (With Parent Reference)

The second method I described works great… until you go to put it into practice. It’s clearly not an impossible situation, but it’s pretty unlikely that you’ll write event handlers within an object that don’t use any of that object’s state (or even other methods on the object). Again, not impossible but just not the common use case. And since it’s not the common use case, you need to be concerned with the potentially problematic common use case 🙂

Let’s consider two classes (yes, again, two classes). We’ll use the first class I described above in both examples that has an event that we can hook onto, and a second class that looks similar to the class I introduced in the second example:

private class HookWithAnonymousDelegate2
{
    public HookWithAnonymousDelegate2(ObjectWithEvent objectWithEvent)
    {
        objectWithEvent.Event += (sender, args) =>
        {
            // handle your event and use something that's part of this instance
            SomeInnocentLittleMethod();
        };
    }

    ~HookWithAnonymousDelegate2()
    {
        Console.WriteLine(this + " is being finalized.");
    }

    private void SomeInnocentLittleMethod()
    {
        Console.WriteLine("... Not so innocent after all!");
    }
}

See the difference compared to example 2? The event handler in this class calls an instance method. This would be a pretty common thing to do (unless you like to duplicate all of your code and not use methods ever :P) and it doesn’t look like it should cause problems. And really, it won’t if you understand the implications of hooking an event handler up to an event. So once you’re done handling your events, make sure you clean up and remove your handlers!

In my opinion, the really interesting part of this example is that the event handler is only calling an instance method. It’s not even using any variables or properties of the instance. Still, the .NET framework is going to hold onto this second instance until we unhook.

Summary

Well, hopefully I haven’t scared you away from using events. The take-away point here is that you need to be mindful of hooking up your events and when/where you unhook them. Personally, unless you always plan to have two objects exist for the same lifetime, I wouldn’t hook up events in the constructors like I’ve done in my examples. Some closing tips:

  • Try only hooking onto events when you need to. If you don’t need to hook up all your events when initializing something, then don’t!
  • Be mindful of how you’re going to clean up your event hooking. Whenever you add an event handler, try to think of where you’ll be cleaning it up.
  • Hooking events onto singletons or global instances can make this problem a lot worse. Since your singleton will be around for the lifetime of your application, if you forget to unhook from your event then you’ll start accumulating a lot of garbage.

I’ve written up a little sample application that uses the example classes and walks you through the three examples I’ve outlined. All of them involve instantiating the classes, hooking up the events, and then how they behave differently when you try to clean them up. You can grab the source code from:

Hope you enjoyed! Remember to follow Dev Leader:


Simple Way To Structure Threads For Control

Background

I’ve previously discussed the differences between the BackgroundWorker and Thread classes, but I figured it would be useful to touch on some code. I’d like to share the pattern I commonly use when creating threads in C# and discuss some of the highlights.

The Single Thread

I like to use this design when I have a single thread I need to run and in the context of my object responsible for running the thread, I do mean having a single thread. Of course, you could have your object in control of multiple threads as long as you repeat this design pattern for each of them.

Here’s the interface that I’ll be using for all of the examples:

    internal interface IThreadRunner
    {
        #region Exposed Members

        void Start();

        void Stop();

        #endregion 
    }

Behold!

    internal class SingleThreadRunner : IThreadRunner
    {
        #region Fields

        private readonly object _threadLock;
        private readonly AutoResetEvent _trigger;
        private Thread _theOneThread;

        #endregion

        #region Constructors

        /// 
        /// Prevents a default instance of the class from being created.
        /// 
        private SingleThreadRunner()
        {
            _threadLock = new object();
            _trigger = new AutoResetEvent(false);
        }

        #endregion

        #region Exposed Members

        public static IThreadRunner Create()
        {
            return new SingleThreadRunner();
        }

        public void Start()
        {
            lock (_threadLock)
            {
                // check if already running
                if (_theOneThread != null)
                {
                    return;
                }

                _theOneThread = new Thread(DoWork);
                _theOneThread.Name = "The One Thread";
                _theOneThread.Start(_trigger);
            }
        }

        public void Stop()
        {
            lock (_threadLock)
            {
                // check if not running
                if (_theOneThread == null)
                {
                    return;
                }

                _theOneThread = null;
                _trigger.Set();
            }
        }

        #endregion

        #region Internal Members

        private void DoWork(object parameter)
        {
            var currentThread = Thread.CurrentThread;

            // this was the trigger that we passed in. elesewhere in the 
            // instance, we can use this object to wake up the thread.
            var trigger = (AutoResetEvent)parameter;

            try
            {
                // keep running while we're expected to be running
                while (currentThread == _theOneThread)
                {
                    // DO ALL SORTS OF AWESOME WORK HERE.
                    Console.WriteLine("Awesome work being done.");

                    // put this thread to sleep, but remember it can be woken 
                    // up from other places in this instance.
                    trigger.WaitOne(1000);
                }
            }
            finally
            {
                lock (_threadLock)
                {
                    // if we were still expected to be running, change the 
                    // state to suggest that we're not
                    if (_theOneThread == currentThread)
                    {
                        _theOneThread = null;
                    }
                }
            }
        }

        #endregion
    }

This design was taken from some Java programming I had done in a previous life. Essentially, I have a thread that is responsible for doing some work in a loop. It could be anything… Periodically polling for some data, a work dequeing thread, a random-cursor-moving thread… Anything! The point is, you only want one of these suckers hanging around. How is this accomplished?

Leveraging the instance variable that marks the one expected running thread is key here. Whenever this thread checks if it should still be running, if the current thread doesn’t match what’s assigned to the instance variable then it needs to stop! This means you could potentially spawn off two of these threads, and if you set the instance variable to one of the two, then the other one should kill itself off! Pretty neat.

By using the reset event, we can actually interrupt this thread if it’s sleeping. This is great if we have a thread that periodically wakes up to do some work but we want to stop it and have it stop fast. We simple set our instance variable for the thread to be null and then set this thread’s reset event to ensure it get’s woken up. Presto! It wakes up, checks the condition, and realizes it needs to exit the loop.

Simple.

The Handful of Threads

This design is almost identical to the single thread design above. I use it primarily when I want to have an object responsible for a bunch of threads that are turned on/off under the same conditions. The major difference between the two designs? In the single thread scenario, we check that our current thread is still set to be the one instance. In this design, we need all of our threads to be checking against the same state object which is not going to be a single thread instance.

Let’s have a peek:

    internal class GroupThreadRunner : IThreadRunner
    {
        #region Fields

        private readonly object _threadLock;
        private readonly Dictionary<Thread, AutoResetEvent> _triggers;

        private bool _running;

        #endregion

        #region Constructors

        /// 
        /// Prevents a default instance of the class from being created.
        /// 
        private GroupThreadRunner()
        {
            _threadLock = new object();
            _triggers = new Dictionary<Thread, AutoResetEvent>();
        }

        #endregion

        #region Exposed Members

        public static IThreadRunner Create()
        {
            return new GroupThreadRunner();
        }

        public void Start()
        {
            lock (_threadLock)
            {
                // check if any are already running
                if (_triggers.Count > 0)
                {
                    return;
                }

                _running = true;

                const int NUMBER_OF_THREADS = 4;
                for (int i = 0; i < NUMBER_OF_THREADS; ++i)
                {
                    var thread = new Thread(DoWork);
                    thread.Name = "Thread " + i;

                    var trigger = new AutoResetEvent(false);
                    _triggers[thread] = trigger;

                    thread.Start(trigger);
                }
            }
        }

        public void Stop()
        {
            lock (_threadLock)
            {
                // check if not running
                if (_triggers.Count <= 0)
                {
                    return;
                }

                _running = false;
                foreach (var trigger in _triggers.Values)
                {
                    trigger.Set();
                }
            }
        }

        #endregion

        #region Internal Members

        private void DoWork(object parameter)
        {
            var currentThread = Thread.CurrentThread;

            // this was the trigger that we passed in. elesewhere in the 
            // instance, we can use this object to wake up the thread.
            var trigger = (AutoResetEvent)parameter;

            try
            {
                // keep running while we're expected to be running
                while (_running)
                {
                    // DO ALL SORTS OF AWESOME WORK HERE.
                    Console.WriteLine("Awesome work being done by " + currentThread.Name);

                    // put this thread to sleep, but remember it can be woken 
                    // up from other places in this instance.
                    trigger.WaitOne(1000);
                }
            }
            finally
            {
                lock (_threadLock)
                {
                    _triggers.Remove(currentThread);

                    // if we were still expected to be running, change the 
                    // state to suggest that we're not
                    if (_running && _triggers.Count <= 0)
                    {
                        _running = false;
                    }
                }
            }
        }

        #endregion
    }

Summary

The above patterns I discussed cover my common usage for threads: Instances that have reoccurring work over long periods of time. Both patterns are very similar and only have slight modifications to make them support one instance or many thread instances running. If you have one unique thread or many threads… there’s a pattern for you!

Check out a full working example of this code over here.


How and Why to Avoid Excessive Nesting

Background

This probably sounds really nit-picky or OCD, but I think it’s an issue worth addressing. Excessive nesting of logic within code can make things nightmarish to read. Even a few of years ago I never thought anything of this. I mean, how much could it really affect someone reading it? He/she must be a complete newb to not be able to read my logic. Fast forward to a co-op placement where this was more closely moderated by my managers, and I began to pay more attention to it…

Why?

Alright, so all that you know so far about my opinion on this is that excessive nesting bothers me. So far, my mission is accomplished. Everything else is just extra. The first issue with excessive nesting is that it actually makes logic hard to follow. If you’re doing code reviews or revisiting your old code, large methods that have lots of nested if statements and loops actually become a tangled mess of logical workflows. You don’t need to believe me yet, but I’m hoping by the end of this you might change your mind.

The next thing, and it’s related, is that it makes refactoring code quite tricky. If you have lot’s of deeply nested if statements, switching up the behaviour of a function even a little bit could have your mind warping with how to tackle all the logical branches. Have fun. Remember that one monolithic function that nobody wanted to go back and refactor? Well, it turns out you need to pass in another parameter now and handle it in all of your separate logical paths. Hold back the tears when you’re trying to recall the logic once you’re 10+ levels deep into nested if statements.

Another key point I’d like to mention is that, in my opinion, the larger the vertical separation between a conditional check and it’s bodies (i.e. the if block and the else block) the more difficult it becomes to read the code. Of course, this may not be a law or an all-the-time thing, but it’s certainly a decent guideline. Think about it though. If you have an enormous block of code for your if statement body, by the time you finish understanding that, you have to go back up to the if statement condition and invert the whole thing to beign to understand what your else block does.

The Offender

Let’s have a look at some real offensive code. Who knows what it does really… Well, nobody does. Why? Because it’s completely contrived to illustrate my point. And that’s that. Behold the horror!

        private void DoStuff()
        {
            foreach (thing in thisList)
            {
                if (condition1)
                {
                    if (condition2)
                    {
                        DoThis(thing);
                    }
                    else
                    {
                        if (condition3)
                        {
                            continue;
                        }
                        else
                        {
                            if (condition4)
                            {
                                continue;
                            }
                            else
                            {
                                if (condition5)
                                {
                                    if (condition6)
                                    {
                                        continue;
                                    }
                                    else
                                    {
                                        if (condition7)
                                        {
                                            continue;
                                        }
                                        else
                                        {
                                            if (condition8)
                                            {
                                                DoThis(thing);
                                            }
                                        }
                                    }
                                }
                            }
                        }
                    }
                }
                else
                {
                    DoThis(thing);
                }
            }
        }

Pretty filthy, right? In all honesty, anyone who has worked in production code is guaranteed to have seen code that nests much much deeper… veering right off the developer’s window (and some of us code with multiple monitors). It’s a scary world out there, and this example doesn’t even begin to illustrate how bad it can get. I mean, this particular example actually fit on my narrow blog window.

 

A Better Way?

Well, fixing this type of thing is nice and easy:

        private void DoStuff()
        {
            foreach (thing in thisList)
            {
                if (!condition1)
                {
                    DoThis(thing);
                    continue;
                }

                if (condition2)
                {
                    DoThis(thing);
                    continue;
                }
                
                if (condition3 || condition4 || !condition5 || condition6 || condition7)
                {
                    continue;
                }
                
                if (condition8)
                {
                    DoThis(thing);
                }
            }
        }

That’s so much prettier. So what’d I do there? A handful of techniques:

  • Invert logical blocks if they can reduce your nesting. For condition1, I had an if/else block where DoThis(thing) resided in the bottom else block… farrrrr farrrr away from the check itself. I simply inverted this check and moved the else block up. Of course, I then had to put a continue statement there to go back up to the next iteration.
  • For condition2, by simply placing a continue right after the method call in the body, I was able to completely eliminate the else block and reduce nesting by a whole level. This works well with if/else blocks with returns too.
  • Next up was a whole pile of combinations for checking when I’m not going to be calling DoThis(thing). That reduced nesting by a bajillion levels, approximately.
  • The final block there for condition8 was still necessary. Of course, it could have be written to be the inverse check (so, if NOT condition8) with a continue inside the block, followed by DoThis(thing) outside of the if block. To me this would have been a bit overkill.

 

Did You Catch That?

Something extremely important to remember when changing logical flows like this is that the order you check your conditions is EXTREMELY important. Notice how in my refactored version the condition checks are still in the same order that they originally appeared? This is on purpose.
Consider if I move condition8 up to the if statement that tests condition1 and say if NOT condition1, OR condition8. Now this is technically not equivalent to the initial implementation. Why? Because the initial implementation says that for one of the logical paths that call DoThis(thing) the following must be met:
  • condition1 = true
  • conditon2 = false
  • conditon3 = false
  • condition4 = false
  • condition5 = true
  • conditon6 = false
  • condition7 = false
  • condition8 = true

Thus, by combining the condition8 check with the condition1 check, how have I guaranteed all those other conditions?  Additionally, how do I know that skipping those condition checks (i.e. pretend they are method calls) has not altered state elsewhere in the class? This optimization actually may not make the code incorrect in certain situations (because it really depends what those conditions are), but it’s important to note that the checks would not be equivalent to the original. It’s just something to pay attention to, but who knows, you may even find that you can optimize some of those checks away depending on your situation!

 

Summary

Don’t excessively nest your code because it makes me cry at night.

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.


  • 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