Infovark Underground

  • news
    • infoblog
    • underground
  • product
  • download
  • buy
  • support
  • about
  • refactoring

    • The Curse of the Singleton

      19 Nov 2008 by Dean / No Comments

      It took us six weeks to break the curse of the singleton. Six weeks! By the end of it, we’d rewritten most of our data access layer.

      We began the process of removing singletons innocently enough. I thought I was well prepared for the task. I’d just finished reading The Pragmatic Programmer (my review of The Pragmatic Programmer) and Working Effectively with Legacy Code (my review of Legacy Code). I remember telling Gordon I’d tackle the problem over the weekend…

      What’s a singleton?

      The Singleton Design Pattern is one of the first patterns introduced in many software design books. But don’t let this fool you like it did me. Its prominent position has nothing to do with its importance. The Singleton is usually listed first because it’s the easiest pattern to explain and implement. It made a convenient place for the author to start, but the Singleton’s real uses are very limited.

      Which is appropriate, actually, since the real use of the singleton is to limit usage. A class that implements the Singleton pattern allows only one object to be instantiated at a time. There are a few cases where this is desirable. For example, classes that control access to a single hardware device or that set up global variables. But the danger of the Singleton is that there are many cases where you’ll want to misuse it.

      Why are they bad?

      Scott Densmore lists the four key characteristics of the Singleton and how each can get you into trouble in his Why Singletons are Evil blog post.

      For another cautionary tale of the cycle attraction, infatuation, disappointment, and rejection, read Singleton, I love you, but you’re bringing me down.

      In our case, we’d gleefully implemented Singletons for database access, content indexing, security and access control, and in a few other places where we thought we needed just one instance. If Steve Yegge were here, he’d call what we’d done an instance of the Simpleton pattern — a failure to grasp basic principles of object-oriented programming. You can read more about Yegge’s thoughts on the singleton and design patterns for dummies.

      Our automated tests were running slowly because we had to set up and tear down the database for every test. Making a change to one component would frequently cause several tests to fail. Everything was tied together at the hip — at the Singleton classes — and it was impossible to disentangle our code to test particular items in isolation. We had tests, but not unit tests. They were integration tests, and the points of integration were the handful of singleton classes we’d built.

      Worse, our database performance was lousy. Since we had a global variable for our database object, we could sprinkle database access code throughout the rest of our object model. We discovered that we were opening and closing database connections all the time. And we’d had to implement tricky locking code to guarantee that our SQL statements would get executed in the right order.

      What did we do about them?

      The Singleton let us be lazy about our programming habits. It allowed us to make assumptions we shouldn’t have. You can call it premature optimization or a retreat into procedural programming techniques from an earlier era. Ultimately, we’d found that it allowed us to cut too many corners.

      So we slowly rooted out each Singleton class from our API and reimplemented the functionality in other ways. Fortunately, we had a large battery of integration tests to help guide us. And luckily, we’d decided to tackle the problem during our first Alpha test, when we could still afford to make sweeping changes. But correcting bad design takes much longer than avoiding it in the first place — even if you’ve read all the right books.

      Six weeks later, we finally sorted out the mess we’d made for ourselves. There’s a handful of odds and ends left to do, but the design feels better. My gut tells me it’s an improvement, and our tests — now we have both unit and integration tests — show that we’ve almost tripled the speed of the data access layer.

      It was worth our time to break the Curse of the Singleton. Beware lest ye, too, fall under its spell!

      Continue Reading

    • Review: Working Effectively with Legacy Code

      07 Nov 2008 by Dean / 1 Comment

      Working Effectively with Legacy Code

      I know what you’re thinking: “Infovark’s been around for barely a year! Surely you guys aren’t having to deal with legacy code already?” If you accept Michael Feather’s expansive definition of legacy code — code without unit tests — then yes, despite our best efforts, we have lots of legacy code.

      But even if you don’t buy that definition, and even if you’re working on a completely greenfield application, chances are you’ll have a lot of code in your project that isn’t fully understood. Or perhaps isn’t fully understood by all members of the team. And it’s in dealing with this issue that Working Effectively with Legacy Code really shines.

      What happens when you need to change code that isn’t fully understood? Are you making it better or worse? The author says that you can’t know the answer to this question without tests in place. Having documentation is nice, but unit testing provides measurable output.

      The brass tacks

      Unlike many programming books, this one is organized in a Q&A format. Once past the introduction — which you can skip if you already understand the importance of refactoring and test-driven development — you’ll find the chapters organized by topic. Here’s a sample of a few chapter headings:

      • It Takes Forever to Make a Change
      • I Can’t Run This Method in a Test Harness
      • Dependencies on Libraries are Killing Me
      • I Don’t Understand the Code Well Enough to Change It
      • This Class is Too Big and I Don’t Want It to Get Any Bigger

      This is a great way to organize a highly technical book. Each chapter has a specific purpose. The author then spends the chapter discussing the ways you can get out of the jam and weighing the pros and cons of each.

      You’ll find in-depth examples of each of the techniques used, but be prepared to shift between languages. To get the most out of the book, you’ll need to be comfortable scanning unfamiliar syntax.

      As a bonus, the book contains an index of common refactoring patterns. Certain patterns make appearances in more than one chapter, and the index provides another place for the author to work through some real-world examples.

      All in all, this is a practical field manual for a set of problems that occur too often out in the wild. I highly recommend it.

      Continue Reading

    • Switch By Type in C#

      09 Oct 2008 by Dean / No Comments

      The introduction of generics into C# 2.0 simplified many programming tasks. It especially helped in the creation of type-safe collections.

      During our reworking of the Infovark data access layer, we created several generic methods to return items from our database. This allowed us to eliminate many duplicated methods and eliminate a lot of type casting. For example, before we began using generics, we had methods with signatures like this:

      1.   public Entity GetEntity(long id, int revision) { … }
      2.   public Relationship GetRelationship(long id, int revision) { … }
      3.   public Resource GetResource(long id, int revision) { … }

      became this after our refactoring:

      1.   public T GetObject<T>(long id, int revision) where T : MetaInstance
      2.   {
      3.     Type type = typeof(T);
      4.  
      5.     if (type == typeof(Entity)) return _DatabaseHandler.GetEntity(id, revision) as T;
      6.     if (type == typeof(Relationship)) return _DatabaseHandler.GetRelationship(id, revision) as T;
      7.     if (type == typeof(Resource)) return _DatabaseHandler.GetResource(id, revision) as T;
      8.  
      9.     return null;
      10.   }

      Wait a minute. All we’re doing here is wrapping all our unique methods up in a generic method! Why bother? Good question. We abandoned that approach in favor of something more sensible later on.

      That’s actually not the point of this post. The point is that C# doesn’t have the ability to perform a switch on types. See all those if statements in our generic method? That’s how we worked around the lack of type switching. If anyone has a better approach, we’d like to hear it.

      Peter Hallam’s WebLog provides more information about why C# doesn’t have the ability to switch on a type. I’m not convinced by the reasons outlined there. As one commenter noted, there’s already a type-switching construct in C#: the catch statement.

      UPDATE: Switching by type is a common problem with MVC frameworks. There’s been quite a lot of discussion on Stack Overflow with regard to the best way to deal with this issue.

      • C# Switch Limitations
      • Is there a better alternative to switch on type?
      • MVC specific: Selecting the correct view for an object type

      Continue Reading

    • Categories

      • .NET (41)
      • AJAX (3)
      • Books (7)
      • HTML (9)
      • Infovark (8)
      • Programming (48)
      • REST (11)
      • SQL (3)
      • Testing (3)
      • Tools (13)
      • UI (3)
      • WCF (11)
      • Web Services (8)
      • WPF (4)
      • XML (4)
    • Archives

    • Get future articles


       

    • Blogroll

      • Ajaxian
      • Anne Van Kesteren
      • Brain.Save()
      • Coding Horror
      • Eric Sink
      • Joel Spolsky
      • John Resig
      • Mark Pilgrim
      • Raymond Chen
      • Scott Hansleman
      • Secret Geek
      • Steve Yegge
      • The Daily WTF
      • The Database Programmer
    • Meta

      • Log in
      • Entries RSS
      • Comments RSS
      • WordPress.org
  • Site map

    • News
    • Product
    • Download
    • Buy
    • Support
    • About
  • Recent Posts

    • Review: Brownfield Application Development in .NET
    • Using Modal Dialogs with a Splash Screen in WPF
    • Highlighting query terms in a WPF TextBlock
    • Getting XAML Hyperlink text to wrap
    • How to format the XAML Hyperlink NavigateUri
  • Twitter

    Copyright 2011 Infovark, Inc. All rights reserved.