Tag: design

API: Top-Down? Bottom-Up? Somewhere in the Middle?

A Quick Brain-Dump on API Desgin

I’ll keep this one pretty brief as I haven’t totally nailed down my thoughts on this. I still thought it was worth a quick little post:

When you’re creating a brand new API to expose some functionality of a system, should you design it with a strong focus on how the internals work? Should you ignore how internals work and make it as easy to consume as possible? Or is there an obvious balance?

I find myself trying to answer this question without ever explicitly asking it. Any time I’m looking to extend or connect systems, this is likely to come up.

Most Recently…

Most recently I started trying to look at creating an API over AMQP to connect my game back-end to a Unity 3D front-end. I had been developing the back-end for a little while now, so I had a pretty good idea for how things needed to work from that perspective. The front-end? Not so much really. I knew some basic actions that I was considering, so I tried coding up an early API for them.

A lot of my focus was around how I was going to implement the code on the back-end to make this API work. It resulted in some of the API calls looking a little bit gross. But the idea was that if I settled on an API that would make the back-end easy to implement, I could get it up and running faster.

After a little while, I feel like my API isn’t getting any cleaner from a consumer perspective, and funny enough, it’s not actually as easy to implement as I was hoping on the back-end. Which had me reflect on a work example…

Once Upon a Time at Work…

Well, it was only a couple of months ago, really. I was working with a colleague on integrating a new system into an existing code base. We decided we wanted to approach the API problem from a consumer perspective. We said “let’s make this as easy to call and use as possible so that people ACTUALLY want to use it”.

We set out with this mission, and created a pretty simplistic API. The challenge? There was a lot of heavy lifting and a bit of voodoo going on behind the scenes. But you know what? We hid the magic in one spot of the code (instead of having ugly stuff scattered all over the code base) and it ended up being a very usable API.

So…

So does this consumer-first, top-down approach to API design always work? I’m not sure. Some similarities/differences in the scenarios:

  • In my current situation, I have a back-end implemented and very minimal code implemented on the caller side. In the work example, we had nothing implemented on the back-end, and a ton of code implemented where the caller side would be.
  • In both examples, at least one of the caller side or back-end side was reasonably well understood. For my game, the back-end was pretty well understood. For work, the caller side was pretty well understood and we had experience with what we’d call a “failed’ back-end implementation (that we were actually setting out to redesign).
  • The work example was a relatively small subset for an API, but the game example was about to be a very specific implementation that I’d need to adapt into a pattern for all messaging in my AMQP system

So there’s a few things to consider there. I think I’m at the point in my game where I’d like to revisit how I’m forming this API and try it from a client-first perspective. Now that I know some of the catches, maybe I’ll shed some new light!

How do you approach API design?


What Makes Good Code? – Should Every Class Have An Interface? Pt 1

What Makes Good Code? - Should Every Class Have An Interface?

What’s An Interface?

I mentioned in the first post of this series that I’ll likely be referring to C# in most of these posts. I think the concept of an interface in C# extends to other languages–sometimes by a different name–so the discussion here may still be applicable. Some examples in C++, Javaand Python to get you going for comparisons.

From MSDN:

An interface contains definitions for a group of related functionalities that a class or a struct can implement.
By using interfaces, you can, for example, include behavior from multiple sources in a class. That capability is important in C# because the language doesn’t support multiple inheritance of classes. In addition, you must use an interface if you want to simulate inheritance for structs, because they can’t actually inherit from another struct or class.

It’s also important to note that an interface decouples the definition of something from its implementation. Decoupled code is, in general, something that programmers are always after. If we refer back to the points I defined for what makes good code (again, in my opinion), we can see how interfaces should help with that.

  • Extensibility: Referring to interfaces in code instead of concrete classes allows a developer to swap out the implementation easier (i.e. extend support for different data providers in your data layer). They provide a specification to be met should a developer want to extend the code base with new concrete implementations.
  • Maintainability: Interfaces make refactoring an easier job (when the interface signature doesn’t have to change). A developer can get the flexibility of modifying the implementation that already exists or creating a new one provided that it meets the interface.
  • Testability: Referring to interfaces in code instead of concrete classes allows mocking frameworks to leverage mocked objects so that true unit tests are easier to write.
  • Readability: I’m neutral on this. I don’t think interfaces are overly helpful for making code more readable, but I don’t think they inherently make code harder to read.

I’m only trying to focus on some of the pro’s here, and we’ll use this sub-series to explore if these hold true across the board. So… should every class have a backing interface?

An Example

Let’s walk through a little example. In this example, we’ll look at an object that “does stuff”, but it requires something that can do a string lookup to “do stuff” with. We’ll look at how using an interface can make this type of code extensible!

First, here is our interface that we’ll use for looking up strings:

public interface IStringLookup
{
    string GetString(string name);
}

And here is our first implementation of something that can lookup strings for us. It’ll just lookup an XML node and pull a value from it. (How it actually does this stuff isn’t really important for the example, which is why I’m glossing over it):

public sealed class XmlStringLookup : IStringLookup
{
    private readonly XmlDocument _xmlDocument;

    public XmlStringLookup(XmlDocument xmlDocument)
    {
        _xmlDocument = xmlDocument;
    }

    public string GetString(string name)
    {
        return _xmlDocument
            .GetElementsByTagName(name)
            .Cast<XmlElement>()
            .First()
            .Value;
    }
}

This will be used to plug into the rest of the code:

private static int Main(string[] args)
{
    var obj = CreateObj();
    var stringLookup = CreateStringLookup();
    
    obj.DoStuff(stringLookup);
 
    return 0;
}
 
private static IMyObject CreateObj()
{
    return new MyObject();
}
 
private static IStringLookup CreateStringLookup()
{
    return new XmlStringLookup(new XmlDocument());
}
 
public interface IMyObject
{
    void DoStuff(IStringLookup stringLookup);
}
 
public class MyObject : IMyObject
{
    public void DoStuff(IStringLookup stringLookup)
    {
        var theFancyString = stringLookup.GetString("FancyString");
        
        // TODO: do stuff with this string
    }
}

In the code snippet above, you’ll see our Main() method creating an instance of “MyObject” which is the thing that’s going to “DoStuff” with our XML string lookup. The important thing to note is that the DoStuff method takes in the interface IStringLookup that our XML class implements.

Now, XML string lookups are great, but let’s show why interfaces make this code extensible. Let’s swap out an XML lookup for an overly simplified CSV string lookup! Here’s the implementation:

public sealed class CsvStringLookup : IStringLookup
{
    private readonly StreamReader _reader;
 
    public CsvStringLookup(StreamReader reader)
    {
        _reader = reader;
    }
 
    public string GetString(string name)
    {
        string line;
        while ((line = _reader.ReadLine()) != null)
        {
            var split = line.Split(',');
            if (split[0] != name)
            {
                continue;
            }
 
            return split[1];
        }
 
        throw new InvalidOperationException("Not found.");
    }
}

Now to leverage this class, we only need to modify ONE line of code from the original posting! Just modify CreateStringLookup() to be:

private static IStringLookup CreateStringLookup()
{
    return new CsvStringLookup(new StreamReader(File.OpenRead(@"pathtosomefile.txt")));
}

And voila! We’ve been able to extend our code to use a COMPLETELY different implementation of a string lookup with relatively no code change. You could make the argument that if you needed to modify the implementation for a buggy class that as long as you were adhering to the interface, you wouldn’t need to modify much surrounding code (just like this example). This would be a point towards improved maintainability in code.

“But wait!” you shout, “I could have done the EXACT same thing with an abstract class instead of the IStringLookup interface you big dummy! Interfaces are garbage!”

And you wouldn’t be wrong about the abstract class part! It’s totally true that IStringLookup could instead have been an abstract class like StringLookupBase (or something…) and the benefits would still apply! That’s a really interesting point, so let’s keep that in mind as we continue on through out this whole series. The little lesson here? It’s not the interface that gives us this bonus, it’s the API boundary and level of abstraction we introduced (something that does string lookups). Both an interface and abstract class happen to help us a lot here.

Continue to Part 2


Should My Method Do This? Should My Class?

Whose Job Is It?

I wanted to share my experience that I had working on a recent project. If you’ve been programming for a while, you’ve definitely heard of the single responsibility principle. If you’re new to programming, maybe this is news. The principle states:

That every class should have responsibility over a single part of the functionality provided by the software, and that responsibility should be entirely encapsulated by the class

You could extend this concept to apply to not only classes, but methods as well. Should you have that one method that is entirely responsible for creating a database connection, connecting to a web service, downloading data, updating the database, uploading some data, and then doing some user interface rendering? What would you even call that?!

The idea is really this: break down your code into separate pieces of functionality.

Easier Said Than Done… Or Is It?

The idea seems easy, right? Then why is it that people keep writing code that doesn’t follow this guideline? I’m guessing it’s because even though it’s an easy rule, it’s even easier to just… code what works.

The recent experience I wanted to share was my work on a project that has a pretty short time frame to prove it was feasible. It was starting something from scratch, so I had all the flexibility in the world to design code however I wanted to. I really made an effort to keep asking myself this one question: Whose job is it?

Every time I asked that question and found that it was not my current method’s responsibility, I would ask “Is this class really responsible for that”? I’d either go make myself a new method in my class or I’d just go immediately make a new class with a single method on it. It seemed like a bit of extra overhead each time I had to do it, but was it worth it in the end?

Absolutely. After the project had proven itself and development continued on, I was easily able to refactor code (where necessary) and mock out functionality in my coded tests. Instead of trying to write test setup code that required a whack of classes I needed to initialize, I could mock out a couple of interfaces and test with ease. It was also really obvious which pieces were responsible for what functionality.

Final Thoughts

If you want to get better at following the single responsibility principle, I think it starts with one question: Whose job is it? Try it out!


ProjectXyz: Enforcing Interfaces (Part 2)

Enforcing Interfaces

This is my second installment of the series related to my small side project that I started. I mentioned in the first post that one of the things I wanted to try out with this project is coding by interfaces. There’s an article over at CodeProject that I once read (I’m struggling to dig it up now, arrrrrghh) that really gave me a different perspective about using interfaces when I program. Ever since then I’ve been a changed man. Seriously.

The main message behind the article was along the lines of: Have your classes implement your interface, and to be certain nobody is going to come by and muck around with your class’s API, make sure they can’t knowingly make an instance of the class. One of the easiest ways to do this (and bear with me here, I’m not claiming this is right or wrong) is to have a hidden (private or protected) constructor on your class and static methods that let you create new instances of your class. However, the trick here is your static method will return the interface your class implements.

An example of this might look like the following:


public interface IMyInterface
{
    void Xyz();
}

public sealed class MyImplementation : IMyInterface
{
    // we hid the constructor from the outside!
    private MyImplementation()
    {
    }

    public static IMyInterface Create()
    {
        return new MyImplementation();
    }

    public void Xyz()
    {
        // do some awesome things here
    }
}

Interesting Benefits

I was pretty intrigued by this article on enforcing interfaces for a few reasons and if you can stick around long enough to read this whole post, I’ll hit the cons/considerations I’ve encountered from actually implementing things this way. These are obviously my opinion, and you can feel free to agree or disagree with me as much as you like.

  • (In theory) it keeps people from coming along and tacking on random methods to my classes. If I have an object hierarchy that I’m creating, having different child classes magically have random public APIs changing independently seems kind of scary. People have a harder time finding ways to abuse this because they aren’t concerned with the concrete implementation, just the interface.
  • Along with the first point, enforcing interfaces makes people think about what they’re doing when they need to change the public API. Now you need to go change the interface. Now you might be affecting X number of implementations. Are you sure?
  • Sets people up nicely to play with IoC and dependency injection. You’re already always working with interfaces because of this, now rolling out something like Moq or Autofac should be easier for you.
  • Methods can be leveraged to do parameter checks BEFORE entering a constructor. Creating IDisposable implementations can be fun when your constructor fails but and your disposable clean up code was expecting things to be initialized (not a terribly strong argument, but I’ve had cases where this makes life easier for me when working with streams).

Enforcing Interfaces in ProjectXyz

I’ve only implemented a small portion of the back-end of ProjectXyz (from what I imagine the scope to be) but it’s enough where I have a couple of layers, some different class/interface hierarchies that interact with each other, and some tests to exercise the API. The following should help explain the current major hierarchies a bit better:

  • Stats are simple structures representing an ID and a value
  • Enchantments are simple structures representing some information about modifying particular stats (slightly more complex than stats)
  • Items are more complex structures that can contain enchantments
  •  Actors are complex structures that:
    • Have collections of stats
    • Have collections of enchantments
    • Have collections of items

Okay, so that’s the high level. There’s obviously a bit more going on with the multi-layered architecture I’m trying out here too (since the hierarchies are repeated in a similar fashion in both layers). However, this is a small but reasonable amount of code to be trying this pattern on.

I have a good handful of classes and associated interfaces that back them. I’ve designed my classes to take in references to interfaces (which, are of course backed by my other classes) and my classes are largely decoupled from implementations of other classes.

Now that I’ve had some time to play with this pattern, what are my initial thoughts? Well, it’s not pure sunshine and rainbows (which I expected) but there are definitely some cool pros I hadn’t considered and definitely some negative side effects that I hadn’t considered either. Stay tuned

(The previous post in this series is here).


ProjectXyz: Why I Started a Side Project (Part 1)

ProjectXyz

Alright, I’ll admit it… Even for a placeholder name on a side project it’s pretty terrible, right? Well, my apologies. So, if you made it to this post you might be wondering what ProjectXyz is and why I started it up. From a high level, I started working on ProjectXyz so that I could have a hobby programming project to tinker with and I figured I’d blog about my adventures in bringing it all together. I plan on making this a mini-series documenting some of the things I’m learning or experimenting with, so this will serve as the intro to the series.

Before we get too far, here’s the link to the GitHub site: https://github.com/ncosentino/ProjectXyz

Why Have a Side Project?

Here’s the main thing I want to talk about in part 1 of this series: Why should you have a side project?

From my experiences in high school and university, I found that having a side project that I could code in was probably the best way that I could continue to learn. It’s a low stress activity that encourages you to be highly creative. You can involve as many other people as you want, or work on it completely solo so that you can minimize external stress and maximize your own creativity. It’s your project, so you have the freedom to do what you want.

I leveraged various small side projects to learn things like how sockets work or how I’d try and structure a multi-tier application. I was able to work on refactoring large amounts of code and learn how to use source control to my advantage. Was there a design pattern I wanted to learn about implementing? Great! Then I could try and find a way to incorporate it into my projects. The goal was always about trying to implement new things and not about cutting corners to try and deliver something to an end user.

Once I started work full-time, I gave up on my programming side projects. I started up this blog which has been fun and I try to take on as much work for my career as I can because I actually enjoy my job… But I stopped coding my own hobby projects. I’ve found that I’m missing out on two major things as a result of that:

  • The ability to experiment with patterns, technologies, and frameworks
  • The ability to get really creative and try out completely new things

Work has been a great opportunity to learn, but it’s learning out of necessity. Myself or my team will hit blocks and we have to work together to try and overcome them. It doesn’t give me the opportunity to go completely into left field to try something new out. Having a side project gives me a bit of freedom to try and learn all sorts of really neat things.

So… Why ProjectXyz?

Okay, well, if you mean why the name… Then I don’t have a great answer. I wanted to start coding but I didn’t want to waste time thinking about a name. I’ll think of something better later, I promise.

Otherwise, you might be wondering why I decided to build ProjectXyz to be what it is (or, what it will be). ProjectXyz is the back end (i.e. not the pretty graphical part) for a role playing game, and I’ve played around with this kind of thing before. I like playing games like this, and I’ve had a lot of fun trying to create a game like this in the past. As a result, I can really focus on what I’m building and not trying to figure out what to build. I’m not pouring energy into wondering “how do I solve this great big popular problem with this piece of software?”, but instead I can just get as creative as I’d like. It’s not about “What does the customer want?”, but instead, I can ask “What do I want to make?”.

The things I’m looking to try out with ProjectXyz (to start with, at least) are:

  • More LINQ usage
  • Coding by interfaces
  • API design
  • Dependency injection and IoC
  • TDD and coded test designs
  • Moq for mocking my classes
  • … GitHub! To make some publicly visible code.

As I work through ProjectXyz, I’ll write more posts on the various things I’m learning as I go! Check out the GitHub page and drop some comments!

https://github.com/ncosentino/ProjectXyz
(The second post in this series is here)


Refactoring For Interfaces: An Adventure From The Trenches

puzzle

Refactoring: Some Background

If you’re a seasoned programmer you know all about refactoring. If you’re relatively new to programming, you probably have heard of refactoring but don’t have that much experience actually doing it. After all, it’s easier to just rewrite things from scratch instead of trying to make a huge design change part way through, right? In any mature software project, it’s often the case where you’ll get to a point where your code base in its current state cannot properly sustain large changes going forward. It’s not really anyone’s fault–it’s totally natural. It’s impossible to plan absolutely everything that comes up, so it’s probable that at some point at least part of your software project will face refactoring.

In my real life example, I was tasked with refactoring a software project that has a single owner. I’m close with the owner and they’re a very technical person, but they’re also not a programmer. Because I’m not physically near the owner (and I have a full-time job, among other things I’m doing) it’s often difficult to debug any problems that come up. The owner can’t simply open an editor and get down to the code to fix things up.

So there was an obvious solution which I avoided in the first place… Unit tests. Duh. I need unit tests. So that’s an easy solution right? I’ll bust out my favourite testing framework (I’m a fan of xUnit) and start getting some solid code coverage. Well… in an ideal world, like every programming article is ever written, this would have been the case. But that wasn’t the case. My software project does a lot of direct HTTP/FTP requests and interacts with particular hardware on the machine. How awesome is writing a unit test that contacts an HTTP server? Not very awesome.

What was I to do? I need to be able to write unit tests so that I can validate my software before putting it in my customer’s hands, but I can’t test it with unit tests because I don’t have the hardware!

Refactoring for Interfaces

Okay, so the first step in my master plan is to refactor for interfaces. What do I mean by that? Well, I have a lot of code that will call out and make HTTP requests and it has a specific dependency on System.Net.WebRequest. The same thing holds true for my FTP requests I want to make. Because I have that dependency within my classes, it means I have no choice but to call out to the network and go do these things.

I could design it a different way though. What if I abstracted the web requests away so that I didn’t actually have to call that class directly? What if I could have a reference to some instance that met some API that would just do that stuff for me? I mean, my class knows all about it’s on particular job, but it truthfully doesn’t know the first thing about calling out to the Internet to go post some HTTP requests. This means if someone else is responsible for providing me with a mechanism for giving me the ability to post HTTP requests, this other entity could also fool me and not actually send out HTTP requests at all! That sounds like exactly what my test framework would want to do.

My first step was to look at the properties and methods I was using on the WebRequest class. What was shared between the HTTP and FTP requests that I was creating? The few things I had to consider were:

  • Some sort of Send() method to actually send the request
  • A URI to identify where the request is being sent
  • A timeout property

I then created an interface for a web request that had these properties/methods accessible and created some wrapper classes that implemented this interface but encapsulated the functionality of the underlying web requests. The next step was creating a class and interface for a “factory” that could create these requests. This is because my code that needs to make HTTP/FTP requests only knows it needs to make those requests–It doesn’t have any knowledge on how to actually create one.

With my interfaces for my requests and my factory that creates them, I was able to move onto the next step.

Create Mocks for the Interfaces

Now that I had my classes leveraging interfaces instead of concrete classes internally, I could mock the inner-workings of my classes. This would provide two major benefits:

  • I could create tests that wouldn’t have to actually go out to the Internet/network.
  • I could create instrumented mocks that would let me test whether certain web requests were being made.

I started off my writing up some unit tests. I tried to get as much code coverage as I could by doing simple tests (i.e. create an object, check default values, call a method and check a result, etc…). Once I had exhausted a lot of the simple stuff, I targeted the other areas that I wasn’t hitting. I mean, how was my coded test supposed to test my method that does an HTTP request and an FTP of a file under the hood? Mocks.

So this is where you probably draw the line between your integration tests or unit tests and get all pedantic about it. But I don’t care how you want to separate it: I need coded tests that cover a section of my class so that I can ensure it behaves as I expect. But if I’m mocking my dependencies, how do I know my class is actually doing what I expect?

Instrument your mocks! This was totally cool for me to play around with for the first time. I had to create dummy FTP/HTTP requests that met the interface my class under test expected. Pretty easy. But I could actually assert what requests my class under test was actually trying to send out! This meant that if my method was supposed to try and hit a certain URL, I could assert that easily by instrumenting my mocked instance to check just that. Was it supposed to FTP a certain set of bytes? No problem. Use my mocked instance to assert those bytes are actually the ones my class under test is trying to send.

Wrap Up

This was just a general post, and I didn’t put up any code to go along with it. Sorry. I really just wanted to cover my experience with refactoring, interfaces, mocking, and code coverage because it was a great learning for me.

To recap on what I said in this post:

  • Identify the parts you want to mock. These are the things your class or method probably isn’t responsible for creating directly. Going out to the network? Accessing the disk? Accessing the environment your test is running under? Creating complex concrete classes because they hook into some other system for you? Great candidates for this.
  • Create interfaces by looking at the API you’re accessing. You know what classes you want to mock, so look how you’re using the API. If you need to access a few properties and methods, then make that part of your interface. If you see commonality between a few similar things, you might be able to create a single interface to handle all of the scenarios.
  • Inject factories that can create instances for you. These factories know how to create the concrete classes that meet your interfaces. In a real situation, they can create the classes you expect. In a test environment, they can create your mocks.
  • Write coded tests with your mocks! The last part is the most fun. You can finally inject some mocked classes into your classes/methods under test and then instrument them to ensure your code under test is accessing them in the way you expect. Run some code coverage tools after to prove you’re doing a good job.

I hope my experiences down this path are able to help you out!


Yield! Reconsidering APIs with Collections

Yield! Reconsidering APIs with Collections (Image by http://www.sxc.hu/)

Yield: A Little Background

The yield keyword in C# is pretty cool. Being used within an iterator, yield lets a function return an item as well as control of execution to the caller and upon next iteration resume where it left off. Neat, right? MSDN documentation lists these limitations surrounding the use of the yield keyword:

  • Unsafe blocks are not allowed.
  • Parameters to the method, operator, or accessor cannot be ref or out.
  • A yield return statement cannot be located anywhere inside a try-catch block. It can be located in a try block if the try block is followed by a finally block.
  • A yield break statement may be located in a try block or a catch block but not a finally block.

So what does this have to do with API specifications?

A whole lot really, especially if you’re dealing with collections. I personally haven’t been a big user of the yield keyword, but I’ve never really been forced to use it. After playing around with it for a bit, I saw a lot of potential. I’ve written before about what I think makes a good API. In my article, I was making a point to discuss two perspectives:

  • Who needs to implement your interface. You want it to be easy for them to implement.
  • Who needs to call your interface. You want it to be easy for them to use.

In my opinion, the IEnumerable<T> interface was a tricky thing to work with as a return value. You can essentially only iterate an IEnumerable, and at the time of calling a function, maybe that’s not what you want to do. The flip side is that for the person implementing the interface, IEnumerable<T> is a really easy interface to satisfy. However, the yield keyword has opened up some new doors.

In this article, I’d like to go over a couple of different approaches for an API and then explain why the yield keyword might be something you consider next time around. Disclaimer: I’m not claiming anything I’m about to present is the only way or the best way–I’m just sharing some of my own findings and perspective.

Interface For Returning Collections

The first type of API I’d like to look at is for returning collections. Based on my own API guidelines, I’d ideally choose an interface or class to return that provides a lot of information to the caller that is also easy to create for the implementer of my interface. The List<T> class is a great choice:

  • It’s easy to construct
  • It’s built-in to the .NET framework
  • It provides many handy functions (All of the IList<T> functionality as well as things like AddRange(), or functions that support delegates)

My next choice might be to have a return type of IList<T>, which would provide a little less ease of use to the caller, but make it even easier for the implementer of the interface. They could return arrays of type T, since an array implements the IList<T> interface, or their own custom list implementation that doesn’t inherit from the List<T> class. The differences between using IList<T> and List<T> are arguable pretty small.

A third alternative, which I would have avoided in the past, is to return an IEnumerable<T>. My opinion used to be that this made the life of the interface implementer a bit easier compared to returning an IList<T>, but complicated the life of the caller for a couple of reasons:

  • The caller would have to use the results of the function in a foreach loop.
  • The caller would have to add the items to their own collection to be able to do much more with the items.

My naive implementations of being forced to return an IEnumerable<T> were… well… crap. I would have constructed a collection within the function, fill it up, and then return it as an IEnumerable<T>. Then as the caller of my function, I’d have to re-enumerate the results (or add it to another collection):

public static IEnumerable<T> GetItems()
{
  var collection = new List<T>();
  // add all the items to a collection
  return collection;
}

private static void Main()
{
  var myCollection = new List<T>();
  myCollection.AddRange(GetItems());
  // use myCollection...

  // or.....
  foreach (var item in GetItems())
  {
    // use the items
  }
}

Seems like overkill to me with that implementation. However, we’ll examine how using yield can truly transform this into something… better. So to reiterate, a few potential implementations for an API involving collections might be:

  • Return a List<T> class
  • Return an IList<T> (or even an ICollection<T>) interface
  • Return an IEnumerable<T> interface

Constantly Creating Collections

My design decisions, in the past, were really driven by two guidelines:

  • Make it easier for the person implementing/extending the API
  • Make it easy for the person consuming the API

As I quickly illustrated in the first section, this meant that I would have a method where I would create a collection, fill it with items, and then return it. I could generally pick any concrete collection class and return it since I would usually pick a simple collection as the return type. Easy.

One thing that might be noticeable with this approach is that it looks pretty inefficient to keep creating new collections, fill them, and then return them. I’ll illustrate with a simple example. We’ll create a class that has a method on it called GetItems(). As per my reasoning presented earlier, we’ll have this method return a List<T> instance, and to make this example easier to work with, we’ll pass in an IEnumerable<T> instance. For what it’s worth, the input to this function is really just for demonstration purposes here–We’re really focusing on how we’re creating our return value.

public class CreateNewListApi<T>
{
  public List<T> GetItems(IEnumerable<T> input)
  {
    var newCollection = new List<T>();

    foreach (var item in input)
    {
      newCollection.Add(item);
    }

    return newCollection;
  }
}

And now that we have our simple class we can mock up a little test for performance… Just how inefficient is creating new lists every time?

internal class Program
{
  private static void Main(string[] args)
  {
    const int NUM_ITEMS = 100000000;
    var inputItems = new int[NUM_ITEMS];

    Console.WriteLine("API Creating New Collections");
    var api = new CreateNewListApi<int>();

    var watch = Stopwatch.StartNew();
    var results = api.GetItems(inputItems);

    foreach (var item in results)
    {
    }

    Console.WriteLine(watch.Elapsed);
    Console.WriteLine(Process.GetCurrentProcess().PrivateMemorySize64);
    Console.ReadLine();
  }
}

When I run this on my machine, I get an average of about 1.73 seconds. The memory printout I get when running is 1615908864 bytes. So is that slow? Is that a lot of memory usage? I think it’s pretty hard to say conclusively without being able to compare it against anything. So let’s keep this number in mind as we continue to investigate the alternatives.

Side Note: At this point, some readers may be saying “Well, if the input to our function was also a list (or if whatever our function has to work with was otherwise equivalent to our return value) then we wouldn’t have to go populate a new collection every time… We can just return the underlying collection”! And I would say you are absolutely correct. If your function has access to an instance of the same type as the return type, then you could always just return that instance. But what implications does this have? You’re now giving people access to your underlying internals, and they can go modify them as they please. So, if you need to control access to items being added or removed, then it might not make sense for you to expose your internal collections like this.

Yield to Incoming API Alternatives

We’ve seen how my past implementations may have looked, so how might we tweak this? If we tweak our API a bit, we can make our method return an IEnumerable<T> instead. Let’s see what that might look like:

public class YieldingApi<T>
{
  public IEnumerable<T> GetItems(IEnumerable<T> input)
  {
    foreach (var item in input)
    {
      yield return item;
    }
  }
}

So in this API implementation, all we’ll be doing is iterating over some type of collection and then yielding each result. If we run it through the same type of test as out previous API implementation, what kind of results do we end up with?

internal class Program
{
  private static void Main(string[] args)
  {
    const int NUM_ITEMS = 100000000;
    var inputItems = new int[NUM_ITEMS];

    Console.WriteLine("API Yielding");
    var api = new YieldingApi<int>();

    var watch = Stopwatch.StartNew();
    var results = api.GetItems(inputItems);

    foreach (var item in results)
    {
    }

    Console.WriteLine(watch.Elapsed);
    Console.WriteLine(Process.GetCurrentProcess().PrivateMemorySize64);
    Console.ReadLine();
  }
}

When I run this on my machine, I get an average of about 2.80 seconds. The memory printout I get when running is 449409024 bytes. How does this relate back to our first implementation? Well, it’s certainly slower. It takes about 1.62x as long to enumerate using the yield implementation as it did with the first API we created. However, yield also uses less than 1/3 (about 27.8%, actually) of the memory footprint when compared to the first implementation. Pretty cool results!

Site Note: So yield was a bit slower according to our results, but what happens if print the elapsed time before we run that foreach loop? Well, on my machine it averages at about one millisecond. Now that’s fast, right?! The cool thing about using yield with the IEnumerable<T> interface is that the work is deferred. That is, not until the program goes to actually run the enumeration do we get our performance hit. Try it out! Try moving the time printout from after the foreach loop to before the foreach loop. Try sticking breakpoints in on the line that yields. You’ll see what I mean.

Summary

In this article, I’ve explored two different ways of implementing an API (specifically focusing on the return value). We saw a brief performance analysis between the two and I highlighted some differences in both approaches. Let’s recap though:

  • Approach 1: Returning a List<T> and creating the collection ahead of time
    • Appeared to be overall a bit faster then yielding.
    • Consumed much more memory than yielding.
    • Callers can use the results immediately for enumeration, checking count, or as a collection to add more things to
    • The return type of List<T> is a bit more restrictive than an IEnumerable<T> like in the second API implementation
  • Approach 2: Return type of IEnumerable<T> and yielding results
    • Appeared to be overall a bit slower than the List<T> implementation
    • Lazy. We don’t actually execute any enumeration code until the caller actually enumerates
    • Consumed significantly less memory than the first approach using List<T>
    • Callers can enumerate the results immediately, but they need to add the results to a collection class to do much more than enumerate

So next time you’re designing an API for your interfaces and classes, try keeping these things in mind!

EDIT (December 30th, 2013):
As per some comments on Google+ by Dan Nemec, I figured I’d add a bit more here in the summary. IEnumerable<T> on it’s own is certainly not useless, especially if you’re leveraging LINQ or extension methods. My main beef in the past was that the consumer of an API with a IEnumerable<T> return value can only iterate over the results… And that’s just because that’s all that IEnumerable<T> lets you do. Dan made a great point though–If you are leveraging things like extension methods, or LINQ (which introduces tons of handy extension methods for working with IEnumerable<T>) then you get all of that functionality tacked on to IEnumerable<T>.

So if you’re not fortunate enough to be working with LINQ or extension methods (i.e. working with legacy code in old .NET framework versions… and yes I am familiar with the attribute you can add in to allow extension methods provided you have a compiler version high enough to support it), then IEnumerable<T> sometimes just plain sucks. I’d wager the majority of C# developers aren’t in this boat though, so I’d like to thank Dan again for his comments.


API: Don’t Forget About The Non-Public API!

Image courtesy of FreeDigitalPhotos.net

Background

From an object oriented programming perspective, an application programming interface (API) is often referred to as the way other developers can interact with the public members of your class(es) and interface(s). Of course, API can be used to describe how one interacts with a web service (or other types of services), but for this discussion I’m limiting the scope to that of interfaces and classes. Limiting the definition of API to public members (or the equivalent of C#’s “public” in other languages) is omitting one huge part of what it encompasses. The purpose of this post is to clarify, in my opinion, why I think forgetting about the non-public API can lead to bad framework and API designs.

API And The Audience

I’ve written before about what I think makes a good API, and I had some comments on Code Project on the same posting that lead me to this topic: the audience. There’s a lot to consider when you’re writing what many people would consider good, clean code. It’s impossible to please everyone because everyone has some sort of best practice, guideline, or convention that they follow because they believe it’s the best. So, I’m not going to tell you that some way is the best… I just want you to be conscious of your audience so that you can make better decisions.

Okay, okay… So what do I mean by audience? I’m going to generalize your audience (the consumers of your API) into two distinct categories. The first category is the group of developers who will be using references to things that implement your interfaces and your concrete classes. They’ll use the instances of the things you define. For example, let’s consider a something built-in to the .NET framework: the List<T> class. Your first group of API consumers are just going to use instances of this class exactly as provided by the framework. They’ll make new instances of them and pass them around to be used in functions, or make properties that return instances of List<T>, or declare variables of type List<T>, etc… They use it as is, as provided.

The second general group of API consumers are the ones who are going to be extending your interfaces and classes. A great example of this is the EventArgs class. This class is super basic; It doesn’t do anything! Anyone who wants to use the EventArgs class essentially has to make their own class that inherits from EventArgs. Another example of this is the Exception class. Again, this class is built for people to extend it with their own implementations. I suppose both of these examples are pretty primitive because the base classes don’t offer much functionality, but what if your class wanted to let child classes override the default behaviour? I’ll have some more concrete examples of this later on.

Intentions Of The Audience

With these two general types of consumers defined, it’s a bit easier to consider how people may want to use your API differently. The first class of consumer wants to able to easily call your methods that you’ve defined and easily create the objects/interfaces that are core to your API. This means that the input they need to provide should be extremely basic, so using things like built in interfaces, or other classes that you’ve defined that are easy to create. These consumers also want information-rich return values and classes. Why? Because it makes their life easy! If they only need to provide a little bit of information and they get a lot back, they’re able to do a lot more with the data that they have access to. They don’t need to (and they certainly don’t want to) call 10 different things in intricate ways to get a little bit of data back.

The second class of consumer takes the exact opposite perspective. Here’s why. In the first case where the first group of consumers want to pass in only minimal information to methods, the second class of consumer wants lots of information passed in. This class of consumer is required to do some job or return some data, so the more information they are provided the easier it is for them to perform their job. Similarly, they want the return values of methods to be as simplistic as possible. Why? It makes their job easier! If they are responsible for returning some incredibly complex class from a method defined in your interface, and the input to that method is only minimal information, this makes the job of the second class of consumer quite difficult.

The best way to remember these similarities and differences is that the flow of data is opposite depending on what type of API consumer you’re talking about. The first type of consumer wants to provide a little and get a lot, and the second type of consumer wants to get a lot and provide a little. Makes sense right? Everyone wants to do the easy thing.

The take-away here is that depending on who you think your main audience is going to be for your API, it will affect how you structure it. And this is exactly why forgetting about the non-public API can be a huge mistake. Forgetting this part of the API makes the whole thing difficult to extend because your base classes cannot as easily be built on top of. You actually make the lives of the second class of API consumers very difficult if you ignore their needs.

Example: WinForms

If you’ve done desktop application development in C#, you’ve likely used (or at least heard of) WinForms. Some people new to desktop application development might have actually started with Windows Presentation Foundation (WPF), but the same concepts will apply here. In my opinion WinForms is a great example of an API that has both public and non-public components that were designed with both audience types in mind. Let’s start with the first class of API consumers.

If you’ve dabbled in WinForms, you’re likely familiar with the Windows Form Designer offered in Visual Studio. If you are… then congrats! You’re the first class of API consumer that I’ve described. By using the built in classes like Buttons, TextBoxes and Labels, you’re using the out-of-the-box components offered in the framework and consuming the public API offered by these controls. You’ll be using things like the Text property offered on these controls and interacting with them via their events (i.e. hooking onto click events or text changed events). You’ll be using the public API. Nothin’ wrong with that!

//
// MyButton
//
this.MyButton.Location = new System.Drawing.Point(146, 84);
this.MyButton.Name = "MyButton";
this.MyButton.Size = new System.Drawing.Size(75, 23);
this.MyButton.TabIndex = 0;
this.MyButton.Text = "Click Me!";
this.MyButton.UseVisualStyleBackColor = true;
this.MyButton.Click += new System.EventHandler(this.MyButton_Click);

private void MyButton_Click(object sender, EventArgs e)
{
    // do stuff!
}

Now, the creators of WinForms weren’t dummies. They knew that they weren’t going to be able to offer you every possible control you’d ever need. They made the API in WinForms have great support for the non-public members of their base classes! So, what do I mean by that?

Let’s pretend we want to have our own fancy button class. Because our button is fancy, we always want to tell the user just how fancy it is when they click it. Now if the framework you were using had a poorly designed API, you might be forced to code a button from scratch. That would be pretty lame considering the complexity of the built-in controls offered to you already. For this example, you could surely just create one button and hook an event handler onto the click event (using the public API), but what if you wanted to re-use this everywhere throughout your user interface? You’d want your own FancyButton class that has this behaviour built-in so you can easily reuse it. No problem.

private class FancyButton : Button
{
    protected override void OnClick(EventArgs e)
    {
        base.OnClick(e);
        this.Text = "The fancy button was clicked.";
    }
}

The non-public API in WinForms gives you access to built-in behaviour of the base classes. You don’t need to hook onto events to get the job done, you can actually override the OnClick method and prevent the click event from even firing! The focus on the non-public API allows developers to extend the built-in classes without having to design their own from the ground up.

Summary

It takes a lot of practice and experience to be able to write a good API. There’s also plenty of different opinions on what constitutes a well-designed API. In my opinion, you need to give a lot of thought as to how your API will be used. Consider the two general types of API consumers I’ve defined: The consumers that use your API with the public parts of the interfaces and classes you’ve defined, and the consumers that want to extend your defined classes to provide their own related implementations. These two types of consumers will want very different things, and in order to please the second class of consumer, you absolutely cannot forget about the non-public API.

Some food for thought:

  • How can I best guess how developers will use my API?
  • I’m providing base classes with my framework and API. Can people easily extend them through inheritance? Will people want to extend them?
  • What would make my public API easier for other developers to use?
  • What would make my non-public API easier for other developers to build on to my base classes?

Singletons: Why Are They “Bad”?

Background

The very first thing I want to say is that I don’t think singletons are inherently bad–even if it means I am cast away from the rest of the programming world. There’s a time and a place for the singleton. It’s really common for people to get caught up with their perspective on something that they outright refuse to acknowledge the other side of it. I’d also like to point out that if you have a strong opinion on something and you find that other people also have a strongly opposing opinion on the same thing, there’s probably good take away points from either side. In this post though, I’m going to focus on why singletons are “bad”, because for me it means acknowledging one of the two main perspectives–that they are the best thing since cat videos met The Internet or they are the worst thing since Justin Bieber.

Let’s clarify what a singleton is here so we’re all on the same page. Maybe you’re under the impression it’s something slightly different than what I’m about to be talking about, so I’d rather make it clear from the beginning. And for what it’s worth, if this isn’t the exact meaning as set in stone by the singleton gods, then that’s sort of unfortunate… because this is going to be what I’m discussing.  From Design Patterns: Elements of Reusable Object-Oriented Software by the Gang of Four, a singleton must:

Ensure a class has only one instance and provide a global point of access to it.

So, with that incredibly complex definition, let’s get into it.

 

Global Dependencies

There’s approximately 3.2 billion articles on The Internet that will tell you that global variables are the enemy. I mean, I could do some of the work for you, but you could check out this, or this, or this… There’s still billions more. Usually when we have ~99% of people agreeing on something, they probably have a pretty good point, right? You’ll notice after a bit of searching that one *big* problem with singletons is the fact that they are just a different way to dress a global variable. Thus, all of the arguments for why global variables are bad could be used against singletons.

There are a few (quite a few) major problems with having global dependencies:

  • You’ll be putting yourself at risk for dealing with deadlocks if you need to lock your resources
  • Your singleton can become the resource bottleneck in your application
  • It’s hard to know who you’ll affect by modifying the global variable
  • Testing becomes difficult because the tests may depend on the state of the singleton
  • Dependencies aren’t obvious from examining the API

Quite simply, global dependencies can be pretty scary. If you and you’re team are experienced enough, trying to weave in some new features or heavily modify code relying on singletons may not be that challenging for you. Maybe. But testing can get super messy.

When you write unit tests, you want to ensure that each test can be run independently of the others. You need complete control over your state. This can be a big problem if you run two tests in a row that depend on state provided by a singleton. Consider the following set of tests that depend on a singleton in a sample run:

  • Test1 increases the count property on a singleton by 1 as part of the side effect of the test.
  • Test2 also increases the count property of the same singleton instance by 1, just as Test1 did. However, Test2 is explicitly testing this property as part of it’s validation to ensure the value transitioned from 0 to 1.

When you run Test1 all by itself, it behaves as you expect. Great! Now you move onto Test2. Simple. You got it working. You’re all excited so you run them all together. Uh oh… The tests failed! But how? You don’t believe it, so you run them all again. Now they pass! This is a crappy spot to be in. If the test suite executes Test2 before Test1, your tests will work. If the test suite executes them in the opposite order, your tests will fail because the singleton instance will have had its count property increased twice. The global state of the singleton comes back to haunt you.

 

Tight Coupling

Most experienced developers know that you want to decrease coupling and increase cohesion because this, generally speaking, makes for a good API and extensible code base. Now this point is related to the global dependency points I was previously stating, but it deserves to be addressed on it’s own. The global dependency topic was more of a focus on the application at run time. That is, it becomes difficult to know and manage how your application behaves at run time when you share global state across the entire thing. It’s challenging to to start adding new functionality to your application or modify existing components of your application that depend on the global state because the dependencies just keep growing.

Coupling, in my opinion, is more of an issue with compile time. With singletons, you start to design classes that depend on singletons and thus you are relying on a specific implementation (Maybe you could check out dependency injected singletons?). Singletons, generally speaking, are a single instance of a concrete class. You start to code classes and object hierarchies that are then depending on this concrete class, and this can potentially (and I say potentially, because I would never claim it’s “always”) lead you to a dead end. Let’s consider a scenario:

We’re coding an application that uses a singleton for the data access layer of our application. We have a MySQL data model that we’ve coded as a singleton. We expose a few methods to read and write records to the database using some SQL, and things are great. Then, one day, we speak to our customers like we usually do to ensure we’re meeting their expectations. They inform us that we really need to be able to support a document database like MongoDB in addition to MySQL. Hold on. Wait. You mean our code that uses our data layer needs to be agnostic to the database under the hood?! But… But our singleton is only able to deal with MySQL… (I wrote about how to get yourself out of this situation here, although I would not claim it’s the ideal scenario). If we would have been passing around references to something that met a nice and clean model interface spec, we’d likely be able to hide the implementation details and completely avoid this problem.

 

Singletons Disrupt The API

Because I like to design complex systems in code, API and architecture is something I like to focus on. There’s an awesome posting over here by Miško Hevery about this very problem. He does a great job describing the problem with examples, so I’ll only try to summarize some of the main take-away points I got from it.

There’s nothing to stop someone from putting some heavy initialization logic in a singleton. I mean, you shouldn’t (because you can’t guarantee when this is going to happen!) but there’s nothing that prevents it. As such, simply calling a constructor on some class (which you might assume to happen pretty quickly) actually ends up taking seconds. Not a couple milliseconds… But seconds. Oh. I guess you didn’t realize your class was trying to call a singleton instance that was connecting over The Internet to some host on the other side of the planet during its initialization. Surprise. Singletons can mask this kind of stuff because it’s not explicit in the API. It kind of goes back to coupling but I wanted to point out that this kind of stuff can get scary.

This can be completely mitigated by incorporating the dependencies right into the API. There’s no hiding crazy database initialization or downloading data from the internet in a constructor (well… it just reduces the likelihood of you doing it so easily I guess). You use interfaces and construct classes in the order that you need them, and this doesn’t end up being some magical process that happens behind a curtain. If one class depends on another, so be it (it’d be nice if it just depended on the interface…), but pass in the reference that you require. Singletons often end up being the shortcut, but what’s easier for you to code now may not be easier for someone to extend upon and understand in the future.

 

Summary

Singletons. You’ve likely seen them. You’ve likely heard bad things about them. You may have even used one yourself. Shame on you. Like all debatable things though, there’s always going to be another side to it. If you take away anything from reading this, I hope it’s that you question what the other perspective is. Fully understanding something requires you to look at all sides.

 

References

This article was based on information I obtained from the following sources (as well as my own experiences, of course!):


Dependency Injected Singletons… What?

Background

Previously I wrote a bit about singletons. I’m not afraid to say that I think singletons have a time and a place… Okay, I’m afraid to say it, but it’s actually how I feel 🙂 After learning more and more about inversion of control design patterns and programming by interfaces, I started to notice just how inflexible singletons are. When you consider using a singleton, you should be considering both the pros and cons without jumping right into it. Here’s an example of my approach for mixing singletons, programming by interfaces, and a bit of inversion of control.

The Setup

I’m actually surprised you got this far. I’m sure you’re probably just sticking around to see how messed up this could possibly be. I’m actually proud that this little pattern has worked out so well when I’ve used it, so it can’t possibly be that bad.

One major drawback to singletons is that they are often implemented as concrete classes. That is, you ask some class X for it’s instance (via a static property/method) and it provides you it. This doesn’t mix very well with programming by interfaces. So, the first step is to have your singleton return an interface instead of a concrete class. Unfortunately, this on it’s own only provides a few benefits, and it’s really only a minor abstraction layer. You can change your singleton class around all you want, but the only dependencies people are going to see are what’s exposed on the interface. As long as your interface isn’t changing, you’re in a good position. With this change alone, we’ve managed to tackle a bit on programming by interfaces, which makes me just a bit happier.

So, what’s the problem now then? Well, now that I have my singleton returning an interface, the unfortunate truth is it’s always going to be the same class backing that interface. It’s incredibly risky if I start putting some sort of logic in my singleton’s property to get the instance that will return different references that could implement the interface. I mean, once your code is running, you want to make sure you’re always getting the same reference back… or else you’re not using a singleton! The drawback to this is that it completely ruins inversion of control and dependency injection!

 

An Example

Consider that I have a singleton that has information about my application. (If you don’t like my example, then you’ll surely hate using WinForms, because Microsoft does it with their Application class. So, it’s a fair example!) Okay, so if we pretend that we need something just like the Application class in our project, we might create some interface IApplication and create a singleton that returns an instance of an IApplication.

Suppose in one implementation we have, we really want to be using reflection and the assembly information to figure out our application’s information. Our concrete class would implement the IApplication interface but the methods would revolve around using reflection and querying the assembly for what it wants. If we built up a whole framework that used this singleton… We’d be tied to that implementation!

What happens if we go to make another application that wants to use this same framework, but it needs to be able to provide the application information through a configuration file? Well… We’d be pooched! Our singleton that’s used everywhere (and yes, please continue crying about the use of the singleton… Just remember Microsoft’s Application class) and we can’t really do anything about it!

Or can we?

The “Solution”

Okay, so here we are. I’ve demonstrated the problem with a scenario that isn’t too far fetched. How do we fix this crappy situation we’ve got ourselves in by using the dreaded singleton pattern? We use my other best friend: events. Except we use them in a way that makes me cringe. Static events.

Here’s my solution the the above problem:

The Interface:

    public interface IApplication
    {
        string Name { get; }

        string Version { get; }
    }

The Singleton:

    public static class Application
    {
        private static readonly object _instanceLock = new object();
        private static IApplication _instance;

        public static event EventHandler<QueryTypeEventArgs> QueryType;

        public static IApplication Instance
        {
            get
            {
                if (_instance == null)
                {
                    lock (_instanceLock)
                    {
                        if (_instance == null)
                        {
                            _instance = CreateInstance();
                        }
                    }
                }

                return _instance;
            }
        }

        private static IApplication CreateInstance()
        {
            var handler = QueryType;
            if (handler == null)
            {
                throw new InvalidOperationException(
                    "Cannot create an instance because the QueryType event " +
                    "handler was never set.");
            }

            var args = new QueryTypeEventArgs();
            handler.Invoke(null, args);

            if (args.Type == null)
            {
                throw new InvalidOperationException(
                    "Cannot create an instance because the type has not been " +
                    "provided.");
            }

            // NOTE: here's where things get weird. you need to define your own
            // sort of "contract" for what type of constructor you will allow.
            // you might not even use a constructor here... but you need to
            // define what mechanism the provided type must have to provide
            // you with a singleton instance. i'm a fan of providing a type
            // with a private parameterless constructor, so i'll demonstrate
            // with that. your requirements will change what this section of
            // code looks like.
            if (!typeof(IApplication).IsAssignableFrom(args.Type))
            {
                throw new InvalidOperationException(
                    "Cannot create an instance because the provided type does " +
                    "not implement the IApplication interface.");
            }

            const BindingFlags FLAGS = 
                BindingFlags.CreateInstance | 
                BindingFlags.Instance | 
                BindingFlags.NonPublic;

            var constructors = args.Type.GetConstructors(FLAGS);
            if (constructors.Length != 1)
            {
                throw new InvalidOperationException(
                    "Cannot create an instance because a single private " +
                    "parameterless constructor was expected.");
            }

            return (IApplication)constructors[0].Invoke(null);
        }
    }

The Program (With two types to inject!)

    internal class Program
    {
        private static void Main(string[] args)
        {
            Application.QueryType += (sender, e) =>
            {
                e.Type = typeof(ApplicationB);
            };

            Console.WriteLine(string.Format(
                "Application Name: {0}rnVersion: {1}",
                Application.Instance.Name,
                Application.Instance.Version));

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

    internal class ApplicationA : IApplication
    {
        private ApplicationA()
        {
        }

        public string Name
        {
            get
            {
                return "Application A (Pretend this was from the assembly info)";
            }
        }

        public string Version
        {
            get { return "1234"; }
        }
    }

    internal class ApplicationB : IApplication
    {
        private ApplicationB()
        {
        }

        public string Name
        {
            get
            {
                return "Application B (Pretend this was from an XML file)";
            }
        }

        public string Version
        {
            get { return "9876"; }
        }
    }

So, if you were to run the program, what outputs would you expect in either case? What happens when you forget to set your event handler? What happens when you set your event handler and don’t provide a type? What if it’s a bad type?

 

Summary


I’m not claiming this is the best approach to solve this problem, and I’m not even encouraging that everyone go ahead and use it. Some of the pros of this are:

  • Advantages of programming by interfaces! You’re only exposing interface definitions to others.
  • Dependency injection capabilities. Inject your “singleton” into other applications.
  • All the goodies related to singletons
  • Easy to use. Just hook up your type to a event handler when your program initializes.

Some of the cons are:

  • All the things people hate about singletons. All of them.
  • Static events are absolutely hideous.
  • You’re giving some other class control of creating your singleton instance.
  • There is no compile time checking or contracts for how your singleton needs to be created.

And now that you know some of the good and some of the bad, can you leverage a design like this? You can check out a working solution I put together for the code and example I described above over at Google Code. Hope you were able to learn something (either good or bad)!


  • 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