DaedTech

Stories about Software

By

One Singleton to Rule Them All

I would like to preface this post by saying that I don’t like the Singleton design pattern at all. There are some who love it, others who view it as a sometimes-useful, often-abused tool in the toolbox, and then there are people like me who believe that it’s extremely rare to see a use of it that isn’t an abuse — so rare that I consider it better to avoid the pattern altogether. I won’t go into much more detail on my thoughts on the Singleton (stay tuned for that when I get to this pattern in my design patterns series), but here is some further reading that expounds a lot on reasons not to like this pattern:

  1. Scott Densmore: Why Singletons are Evil
  2. Misko Hevery: Singletons are Pathological Liars
  3. Alex Miller: Patterns I Hate
  4. Steve Yegge: Singleton Considered Stupid

With all of those arguments against Singleton in mind, and considering the damage that abuse (and I would argue use) of the pattern causes in code bases, I found myself thinking of code bases I’ve heard of or encountered where the code was littered with Singletons. In these code bases, refactoring becomes daunting for a variety of reasons: the hidden dependencies, the complex temporal dependencies, the sheer volume of references to the Singleton instances, the almost obligatory Law of Demeter violations, etc. Singletons cause/encourage a rich variety of problems in code bases. But I think that something could be done about two such problems: the redundant Singleton implementation logic and the Single Responsibility Principle (SRP) violation of which Singleton classes are prima facie guilty.

Take a look at how the Singleton is implemented (as recommended by Microsoft, here). The basic implementation initializes the static instance in the property accessor while variants use field initializing syntax and introduce thread safety.

The basic implementation is here:

public class Singleton
{
     private static Singleton instance;

     private Singleton() {}

     public static Singleton Instance
     {
          get
          {
               if (instance == null)
                    instance = new Singleton();
               return instance;
          }
     }
}

More specific even to C# is James Michael Hare’s implementation using the Lazy<T> class to eliminate the redundant if-instance-null-instantiate logic needed in each Singleton class. But that still leaves the redundant Instance property, the redundant _instance field, and the awkwardness (SRP violation) of an object managing its own cardinality. What if we got rid of both of those issues?

public static class Singleton where T : new()
{
     private static readonly Lazy _instance = new Lazy();

     public static T Instance { get { return _instance.Value; } }
}

public static class SingletonClient
{
     public void Demonstrate()
     {
          Singleton.Instance.Write("Look!! Logger isn't a Singleton -- it's a real class!!");
     }
}

Using generics, this implementation allows an instance of every Singleton to be expressed in the code of a single class. In this fashion, any type can be implemented as a Singleton without the type being coupled to an internal Singleton implementation. It also standardizes the Singleton implementation by making sure it exists only once in the code base. With this pattern, there is a similar feel to IoC containers — classes can be implemented without concern for who will instantiate them and how.

Here is my take on the disadvantages and potential disadvantages of this approach:

  1. You still have Singletons in your code base.
  2. This might actually encourage more Singleton usage (though fewer actual Singleton implementations) by removing responsibility for implementation.
  3. Since constructor of object in question must have public default constructor, removes the Singleton gimmick of making the constructor private and thus the safeguard against additional instances being created is also removed.
  4. A natural extension of the previous item is that it remains a matter of documentation or convention to use Singleton<T> and not instantiate rather than it being impossible to instantiate.

But the advantages that I see:

  1. Only one class implements cardinality management, meaning refactoring away from Singleton is nominally easier.
  2. No Singleton SRP violations
  3. Singleton implementation (initialization, lazy load, thread-safety) is standardized to prevent inconsistent approach.
  4. I actually consider preventing the private constructor gimmick to be a plus — particularly where potential refactoring may be needed (and it pretty much always is when Singletons exist).
  5. With this pattern in your code base developers are less likely to be come comfortable/familiar with implementing the Singleton pattern.
  6. No need to introduce interfaces for Singletons to inject instance into classes using dependency injection — just inject a non-Singleton managed instance.
  7. A code base with nothing but normal instances is very easy to reason about and test, so the closer you get to that, the better.

I would like to reiterate that I’m not suggesting that you run out and start doing this everywhere. It mitigates some of the natural problems with the Singleton design pattern but “mitigates some” is a long way from “fixes all”. But, if you have a code base littered with Singletons this could potentially be a nice intermediate refactoring step to at least standardize the singleton implementation and provide slightly more friendly seams to testing legacy code. Or if you’re faced with and outvoted by a group of other developers that love their global variables (er, excuse me, Singletons), this might be a decent compromise to limit the damage they cause to the code’s maintainability. On balance, I’d say that this is an interesting tool to add to your arsenal, but with the caveat that something is probably wrong if you find that you have a use for it.

I’d be curious to hear others’ takes on this as well. I just kind of dreamed this up off the top of my head without taking a lot of time to explore all potential ramifications of it use. If you’ve implemented something like this before or if you have opinions on the advantages/disadvantages that are different than mine or if you see ways it could be improved, I’d be interested to hear about it in the comments.

By

The Code that Cried Wolf: Proving that Comments are Unneeded

I spent a lot of years diligently commenting my code. I wrote what the code did next to the statements themselves and I wrote method headers and sometimes I even kept a journal of edits in that header as if there were no such thing as source control. As I mentioned in an earlier post, I’ve since drifted further and further from this approach to the point of almost never commenting my code if left to my own devices. The reason for this gradual but near-complete reversal is that I’ve come to view comments as a crutch that prevents code from standing on its own from a readability perspective.

For instance, consider the following class (and before we go any further, I would just like to mention that the relationship between the “Prepper” and “Employee” is not actually how I would design this — this is just an example for demonstrating a point):

public class EmployeePrepper
{
    private readonly IEnumerable _employees;

    public EmployeePrepper(IEnumerable employees)
    {
        _employees = employees;
    }

    public void SetupEmployees()
    {
        foreach (var employee in _employees)
        {
            if (string.IsNullOrEmpty(employee.FirstName))
                throw new Exception();
            if (string.IsNullOrEmpty(employee.LastName))
                throw new Exception();

            if (employee.LastName.Length < 3)
                employee.LoginName = employee.FirstName + employee.LastName;
            else
                employee.LoginName = employee.FirstName[0] + employee.LastName;
        }
    }
}

Imagine that you've asked for a code review and someone says "well, it's a little hard to read and follow -- you've got some magic numbers in there and it's not all that readable." What suggestion is coming next? Or, if none is forthcoming, what do you do to address this? Something like the next code snippet?

/// 
/// This class takes a bunch of employees that the user entered and sets up derived properties on them
/// 
public class EmployeePrepper
{
    /// 
    /// This is a collection of employees that the constructor will pass in
    /// 
    private readonly IEnumerable _employees;

    /// 
    /// This constructor takes the class's dependency and initializes it
    /// 
    /// The employees this class will work on
    public EmployeePrepper(IEnumerable employees)
    {
        _employees = employees;
    }

    /// 
    /// Sets up the employees by setting derived properties
    /// 
    public void SetupEmployees()
    {
        //Cycle through the employees
        foreach (var employee in _employees)
        {
            //Make sure a valid first name and last name are entered
            if (string.IsNullOrEmpty(employee.FirstName))
                throw new Exception();
            if (string.IsNullOrEmpty(employee.LastName))
                throw new Exception();

            //If the employee has a very short last name, then use first concatenated to last
            if (employee.LastName.Length < 3)
                employee.LoginName = employee.FirstName + employee.LastName;
            else //Otherwise, use first initial concatenated to last name
                employee.LoginName = employee.FirstName[0] + employee.LastName;
        }
    }
}

Ah, much better, right? From the outside looking in, with IntelliSense, I learn that (1) the class takes a collection of employees and sets their derived properties, (2) the constructor takes a dependency and initializes itself, and (3) the setup employee method sets up the employees with their derived properties. Of course, I could learn that by (1) inspecting the constructor, (2) common sense, and (3) see item (1).

Okay, so maybe I don't learn all that much of interest from IntelliSense, but there's a lot of clarity in the method itself. I learn that (1) I'm going to cycle through records, (2) I'm going to check properties for validity and (3) a descriptive business rule for setting up login names. Of course, I could learn (1) by knowing what foreach() is and (2) by basic inspection. (3) is interesting in that it's the first comment that isn't just pointless filler. It actually explains something that I need to know.

So 1 out of 6 comments is helpful, but isn't that still a net gain? Well, it is if we assume that there is no downside to having commented code. But there is a downside. Specifically, the addition of comments to the file means extra artifact that must be maintained or else the comments drift from noise to lies. For example, what if we add a constructor parameter and don't pay attention to the doc comments (which pretty much no one does when editing classes)? Suddenly that comment about taking a single employee dependency is nonsensical. So you have 5 liabilities and 1 asset in terms of comments here, which seems like a poor tradeoff (although I'm not going to attempt to place an actual measurable value on the concept of misleading comments versus helpful, explanatory comments -- even if I could, it wouldn't matter much since it's pretty unlikely I'll read your comments anyway :) ).

Okay, I've sold you on my premise, but what do you say to the architects/leads/coworkers/project managers/etc who aren't buying what I'm selling? How do you convince them that this activity is somewhere between pointless and detrimental? Well, prove to them that the comments are pointless. Take away the crutch and make your class names, method names, variable names, and logic flow so clean and so self documenting that the comments look preposterous. Take the original code and turn it into this:

public class EmployeeDerivedPropertySetter
{
    private const int LastNameMinimumLength = 3;

    public class FirstNameEmptyException : Exception { }

    public class LastNameEmptyException : Exception { }

    private readonly IEnumerable _employeesPassedInFromConstructor;

    public EmployeeDerivedPropertySetter(IEnumerable employees)
    {
        _employeesPassedInFromConstructor = employees;
    }

    public void SetupDerivedProperties()
    {
        foreach (var employee in _employeesPassedInFromConstructor)
            SetupDerivedProperties(employee);
    }

    private static void SetupDerivedProperties(Employee employee)
    {
        ValidateFirstAndLastName(employee);
        SetLoginName(employee);
    }

    private static void ValidateFirstAndLastName(Employee employee)
    {
        if (string.IsNullOrEmpty(employee.FirstName))
            throw new FirstNameEmptyException();
        if (string.IsNullOrEmpty(employee.LastName))
            throw new LastNameEmptyException();
    }

    private static void SetLoginName(Employee employee)
    {
        if (IsEmployeeLastNameVeryShort(employee))
            employee.LoginName = ConcatenateFirstAndLastNames(employee);
        else
            employee.LoginName = ConcatenateFirstInitialAndLast(employee);
    }

    private static bool IsEmployeeLastNameVeryShort(Employee employee)
    {
        return employee.LastName.Length < LastNameMinimumLength;
    }

    private static string ConcatenateFirstAndLastNames(Employee employee)
    {
        return employee.FirstName + employee.LastName;
    }

    private static string ConcatenateFirstInitialAndLast(Employee employee)
    {
        return employee.FirstName.ElementAt(0) + employee.LastName;
    }
}

Now, small factored methods might not be your thing, particularly if you love debugger (or just love big methods and classes for some reason). But I think you'd be hard pressed to argue that this isn't quite readable and self explanatory. There's no method here that you'd look at, then squint at, then rub your head and say, "what the...?" You have things like "If the last name is very short, set login name to first concatenated to last." This class reads like an instruction manual or... kinda like the version with a bunch of comments. Except unlike that version, your code is actually the comments, so it's impossible for it to become obsolete and misleading.

But I'm not trying to tell you how to code -- I'm trying to tell you how to sell this. I'm trying to tell you how to prove that comments are unnecessary. "How," you ask? Well, put the comments back in and see how completely obtuse they now look:

public class EmployeeDerivedPropertySetter
{
    /// 
    /// The minimum length of the last name
    /// 
    private const int LastNameMinimumLength = 3;

    /// 
    /// Thrown when the first name is empty
    /// 
    public class FirstNameEmptyException : Exception { }

    /// 
    /// Thrown when the last name is empty
    /// 
    public class LastNameEmptyException : Exception { }
    /// 
    /// This is a collection of employees that the constructor will pass in
    /// 
    private readonly IEnumerable _employeesPassedInFromConstructor;

    /// 
    /// This constructor takes the class's dependency and initializes it
    /// 
    /// The employees this class will work on
    public EmployeeDerivedPropertySetter(IEnumerable employees)
    {
        //Set the employee variable to the passed in value
        _employeesPassedInFromConstructor = employees;
    }

    /// 
    /// Sets up the employees by setting derived properties
    /// 
    public void SetupDerivedProperties()
    {
        //Cycle through the employees
        foreach (var employee in _employeesPassedInFromConstructor)
            SetupDerivedProperties(employee);
    }

    /// 
    /// Setup the derived properties
    /// 
    /// Employee to set them up for
    private static void SetupDerivedProperties(Employee employee)
    {
        //Make sure a valid first name and last name are entered
        ValidateFirstAndLastName(employee);
        //Set the employee's login name
        SetLoginName(employee);
    }

    /// 
    /// Validate the first and last name of the employee
    /// 
    /// The employee to validate
    private static void ValidateFirstAndLastName(Employee employee)
    {
        //If first name is null or empty throw an exception
        if (string.IsNullOrEmpty(employee.FirstName))
            throw new FirstNameEmptyException();
        //If last name is null or empty, throw an exception
        if (string.IsNullOrEmpty(employee.LastName))
            throw new LastNameEmptyException();
    }

    /// 
    /// Set the employee's login name
    /// 
    /// Employee whose login name to set
    private static void SetLoginName(Employee employee)
    {
        //If the employee has a very short last name, then user first concatenated to last
        if (IsEmployeeLastNameVeryShort(employee))
            employee.LoginName = ConcatenateFirstAndLastNames(employee);
        else //Otherwise, use first initial concatenated to last name
            employee.LoginName = ConcatenateFirstInitialAndLast(employee);
    }

    /// 
    /// Returns true if the employee last name is very short
    /// 
    /// Employee to check for a short last name
    /// True if the last name is very short, false if not
    private static bool IsEmployeeLastNameVeryShort(Employee employee)
    {
        //Returns whether or not the last name's length is shorter than the minimum length of the last name
        return employee.LastName.Length < LastNameMinimumLength;
    }

    /// 
    /// Concatenate an employee's first and last name
    /// 
    /// Employee whose first and last name to calculate
    /// The concatenated first and last name
    private static string ConcatenateFirstAndLastNames(Employee employee)
    {
        //Concatenate the first and last names of the employee
        return employee.FirstName + employee.LastName;
    }

    /// 
    /// Concatenates the first initial and last name of the employee
    /// 
    /// Employee whose first initial and last name to concatenate
    /// The concatenated first initial and last name
    private static string ConcatenateFirstInitialAndLast(Employee employee)
    {
        //Concatenate the first initial and last name of the employee
        return employee.FirstName.ElementAt(0) + employee.LastName;
    }
}

I think you'd be hard pressed to find someone who thought that this level of commenting on this self-describing code made any sense. That's the beauty of this demonstration -- more even than just the self documenting code, adding comments next to it demonstrate that there's really nothing left to say. And hey, if this gambit backfires and you find someone who thinks this is a good idea, you've learned a valuable piece of information about someone to bear in mind when considering which projects to work on and where to work in the future. In all seriousness, though, I think this will do a fairly good job of demonstrating that you can express the vast majority of what you would express in comments with the code itself.

There is another very practical benefit to proving this and the resulting Spartan approach to comments beyond the fact that the comments and code tend not to get out of sync; when comments are a rarity, you're more likely to read them. Think of heavily commented code as "The Code that Cried Wolf." If you see a lot of code that looks like the code in this snippet immediately above, don't you start to just kind of tune out the comments? They appear in some other color than the main code, and rather than information, they become comforting white noise, separating your methods and fields from one another the way a little bit of margin/padding separates a bunch of text boxes on the form from one another. You don't study the buffering space -- you just take it for granted. This is how it works with over-commented code bases. If you find yourself in code bases like this, do an exercise and ask yourself when the last time you paid attention to a comment was. Yesterday? Last week? Last month? Now ask yourself how many times you've looked at the code since then? A hundred? A thousand? Ten thousand? That's a pretty low percentage of time that you pay attention to comments.

But imagine a code base with almost no comments. You're flipping between classes and looking at methods, and there's no extras -- just code. Now, you open some class and there's a big, fat, 10 line comment. Betcha notice it immediately and, what's more, betcha read it. And, I'm also willing to wager it's worth reading. If a code base has an absence of noise comments, the developer that wrote this one probably has something important to say: why he chose to do it this way even though it seems obtuse or where she found a template/inspiration for this code via google and why she chose to use it.

Method, parameter, class, and variable names can tell you a lot about what the code elements are. Source control checkin comments can tell you a lot about why various changes were made. Unit tests/BDD Tests/Integration tests can tell you a lot about business rules and requirements. None of these things require adding redundancy to the code itself. Comments in your code should be the exception rather than the rule. And you can prove it.

By

You Can Tell a Lot About Developers From Their Scratchpads

What is a Scratchpad?

When you have a question like “what exception is thrown when I try to convert a long that is too big to an integer” or “what is the difference in performance between iterating over a list or a dictionary converted to a list” what do you do? Google it? Phone a friend? Open up an instance of your IDE and give it a try? I think that sooner or later, most developers ‘graduate’ to the latter, particularly for things that can’t be answered with a quick search or question of a coworker. And, if they wind up doing this enough times, they start creating a project or project(s) with titles like “dummy”, “scratchpad”, “throwaway”, “junk”, etc — you get the idea.

As this practice grows and flourishes, it starts to replace google searches and ask a coworker to a degree, even when those things might be quicker. If you get very used to setting up experiments in this fashion, it tends to be almost as quick as a search, and there’s less potential for wrong or misleading information. This is a very useful practice but, more interestingly for the purposes of this post, I think the makeup of this scratchpad (I’m using this term because it’s what I name mine) can tell you a lot about the developer using it. In fact, I believe strongly enough in this that I see a lot of value in the interview question “tell me about your scratchpad and how you use it.”

I’ll say in advance that I’m going to paint with some broad strokes here. So, please read the following while bearing in mind the caveat that there will, of course, be exceptions to the ‘rules’ that I’m describing. In the examples below that describe a single type of scratchpad, please note that I’m referring to situations where this is the primary or only scratchpad that the developer uses. I’ll describe the “arsenal” of scratchpads further down.

No Scratchpad

If someone doesn’t have something like this, they’re quite likely either not very seasoned as a developer or else not very inquisitive when it comes to understanding their craft. The lack of such a playpen project implies that they either don’t experiment or that they experiment in production code, which is pretty low rent and sloppy. (One possible exception is that they experiment in a project’s unit tests, which is actually a pretty reasonable thing to do, and an example of a reason for my “broad strokes” caveat). In either case, they’re lacking a place that they can go in and just throw some code around to see what happens.

Extrapolating out to the way a person with no scratchpad works, it seems very likely that you will observe a lot of “debugger driven development” and “programming by coincidence”. The reason I say this is that this person’s natural reaction to a lack of understanding of some facet of code will most likely be to try it in the production code, fire up the application, and hope it works. I mean, lacking a playpen and tests, what else can you really do? It’s all well and good to ask a coworker or read something on stack overflow, but at some point an implementation has to happen, and when it does, it’s going to be in the production code and it’s probably going to be copy-pasted in as a matter of faith.

I’d be leery of a programmer with no scratchpad. It might be lack of experience, lack of curiosity, or lack of interest, but I’d view this as most likely a lack of something.

Application Scratchpad

This is a scratchpad project that has the kitchen sink, from persistence on up to the GUI. In shops/groups that make a single product, it may be as simple as a duplicate of that project. In shops with more projects, it may be one of them or a composite of them. But, whatever it is, it’s a full fledged application.

Extra points here for being clever enough to have a consequence-free, dummy environment and for recognizing the value of experimentation. This is usually a sign of an inquisitive developer who wants to take things apart and poke at them, or at least a conscientious one who wants to try things out in dress-rehearsal before going live. I’d take some points away, however, for the monolithic approach here, assuming that this is the primary scratchpad and not an auxiliary or temporary approach. The reason I’m not such a fan of this is that it’s indicative of someone who hasn’t yet learned to think of an application in seams, components, modules, units, etc.

I mean, think about how this goes. “I wonder what happens if I use a string array instead of a string list here” leads to trying out the change and then firing up an entire application, complete with GUI bells and whistles, database access, file reads/writes, loggers, etc. This represents a view of the software that essentially says “it’s all or nothing, baby — here we go.” Good on them for the experimentation, but we can certainly do better.

Console Based Scratchpad

The console scratchpad (and this is a little Visual Studio specific, though it’s applicable to other IDE/environments as well) is one in which the main running application is one that writes to and reads from the console. If you wanted to time stuff you’d be doing so using a lot of System.out.println() or Console.WriteLine() or whatever the equivalent in your choice of language.

This correlates with the good characteristics of the GUI/application scratchpad (curiosity, judiciousness) but adds a bit more sophistication. A developer with a console based scratchpad understands how to decompose and abstract concepts and how to isolate problems. I think that this is potentially indicative of a competent and potentially great developer perhaps ready for a push.

Class Library Scratchpad

The most sophisticated scratchpad, in my mind, is the class library scratchpad. This is a scratchpad that has no program output of any sort and cannot be run independently. What this means is that the developer is used to reasoning about units and experimenting in very small, isolated fast feedback loops. Someone doing things this way clearly understands that increasingly complex applications are assembled from solutions to manageable problems rather than with some kind of irreducibly complex, inter-connected gestalt. Someone with this style of scratchpad is almost certainly a unit tester and most likely a practitioner of TDD (I certainly recognize my own bias here). But the most important thing here is the ultra fast and simple feedback loop, where answers to “how does this work” are provided right in the IDE itself (and extra points for anyone running a continuous integration tool like NCrunch.

Monolithic Scratchpad

A monolithic scratchpad is one that tends to be a developer’s only scratchpad. I think that this tends to be indicative of an architecturally minded developer capable of thinking in significant abstractions. The monolithic scratchpad is one that encompasses all of the projects above in one. It has test projects for fast feedback. It has a persistence model or two and a domain of sorts. It has a web front end and a desktop front end and mobile front end. In short, the developer organically evolves this scratchpad to suit whatever experimentation needs arise, demonstrating an ability to grow an application in response to whatever needs arise. Someone with this sort of scratchpad setup is someone I’d keep my eye on as a potential architect.

Arsenal of Scratchpads

An arsenal of scratchpads is indicative of a developer seasoned enough to understand that different questions call for different environments, but someone more silo-oriented and, perhaps, very well organized in a sense. While it may not occur to this person to blend scratchpad needs into an ad-hoc, decently architected application, the work nevertheless exists in such a way that it’s easy to find, access, and use. Since the response to new situations is new scratchpads, the critical fast feedback loop is there since they never get very big. I think that this practice is indicative of someone who might excel in small to medium sized picture development work or, who might do well on the path to project management. A monolith scratchpadder and an arsenal scratchpadder could probably form a pretty good leadership tandem on a project.

What Does your Scratchpad Look Like?

I’d like to reemphasize that this is a fairly lighthearted post that I fully acknowledge may completely miss the mark in categorizing some people. But, I do think there’s a grain of truth to it, and I stand by my assertion that this would make for an excellent interview question. If you have one of these types of scratchpads and either reinforce or poke holes in my premise, please weigh in. Same if you have a scratchpad setup I hadn’t thought of.

By

Static Methods: Time to Hit Rock Bottom

A Tragic Story

It starts out innocently enough. You’re out at a party with some friends, and some people you want to impress are there. Everyone is having a good time, but you notice that some of the ‘cool’ kids are periodically going into a room and coming out giggling. Not wanting to be left out, you ask what’s going on, and are told that it’s none of your business. You have some concept that they’re doing something wrong — something forbidden — and you see what a mystique it creates. Later on, you ask around subtly and figure out what’s going on, and the next time you’re at a party, you know the right things to say to get an invitation to that coveted side room. You make your way in nervously, and there, you are introduced to the exhilarating euphoria of casting aside all thoughts of dependency and responsibility and writing a static method. Now, you’re one of the cool kids.

It’s no problem at first. You just write static methods on the weekends sometimes because it feels good to allow all your classes to access some service without passing an instance around. It’s not as if all of your code is procedural, by any stretch. And, yeah, sometimes you get a little weird behavior or hard to track down defects, but you’ve got it under control. Some of your less cool friends tell you that maybe you should think about modeling those behaviors with instances, but you tell them to mind their own business — they wouldn’t understand.

Static methods are just a way of blowing off steam and dealing with stress. When you’ve got project managers riding you to get things done, deadlines to meet and lots of things on your plate, it’s really gratifying to write a static method or two. They’re so easy, so efficient. It helps you get through the day.

But then, something weird starts to happen. They’re not helping you feel good anymore — they’re not cleaning up your code or making it more efficient. You need them just to get by. You have 50 classes that all depend on some static class with static variables, and they need to retrieve and set those variables in just the right order. It’s a mess, and it’s impossible to figure out why you’ve got this stupid defect that the stupid user shouldn’t care about anyway, that only occurs on Windows 7 when two specific screens are showing, the database connection is closing and a window was opened previously. If only you didn’t have all of these stupid global variables in your static classes, this wouldn’t be a problem. If only you’d listened to your friends. The only way out of this static nightmare for even a few minutes is… another static global flag.

Okay, okay, you admit it. This has gotten a little out of hand. So, you go to the project managers and tell them that the code can’t be fixed. It’s time for version 2.0. You’re going to rewrite everything with a much better design, and this time, you swear, you’re only going to use static methods in moderation. You’ll be a lot more responsible with them this time around. You’ve learned your lesson. Yessiree, this time, everything’s going to be different.

But it’s not. You need to hit rock bottom. Only then can you find your way back.

Static Methods are Like an Addiction

It never seems to fail in a code base of decent size. Poke around the portions of the code that tend to cause the most issues and be hardest to reason about, and the ‘static’ keyword will tend to abound. The worse it is, the more of them you’ll see. People know that global variables are bad, and it is becoming widely accepted that singletons tend to be problematic and abused (if one doesn’t believe use counts as abuse). People generally concur that static state is problematic. And yet, it keeps on keeping on. More is introduced every day. Here are some observations that I’ve made about the use of statics in code:

  1. Most people rationalize their use.
  2. Time constraints and stress are often cited as justifications.
  3. Promises to do something about them at a nebulous future date abound.
  4. People continue using them in spite of being aware of demonstrable, negative effect.
  5. The ‘solution’ for the problems they’ve caused is often using more of them.
  6. People get defensive when asked about them.

One blogger that I follow, Julian Birch, compares them to crack in a post entitled “Going Cold Turkey on Static Methods”:

Static methods are like crack, they’re convenient, they solve your problems quickly and you quickly become dependent upon them. You’re so dependent you don’t even know you’ve got a problem.

I hadn’t seen this particular post when I started mine, but it was nice to google around a bit and see that I’m not the only one to whom this particular metaphor had occurred.

Emerging from the Metaphor

The metaphor here is just that – a literary device intended for illustrative effect in demonstrating a point. I’m not actually suggesting that static methods will ruin your life, and I’m not attempting to trivialize the struggles that people have with actual addiction. I’m posting this because of my observation of the tendency of static methods in a code base to become a real, huge problem, that people immersed in the code base don’t see, but outside observers are immediately alarmed by.

Static state/methods in a code base generally represent a tradeoff, but a subtly different one, in my opinion, than their advocates would have you believe. They claim a tradeoff between complex instantiation logic and complex runtime logic. I claim a tradeoff of a little extra reasoning up front for an avalanche of future problems. To me, introducing a bunch of static functionality into a code base is like saying “I’m making a conscious choice to avoid all the effort needed to plug in my sump pump, and if my basement floods with sewage, I’m fine with that.” What?!? Seriously?!?

Rationale

In a post with a different device theme, the pun, John Sonmez says:

I don’t like static methods. They make me cringe. In the universe of OO static methods are anti-matter.

He goes on to talk about specific issues with the concept of static methods, including:

  1. A tendency to violate the SRP since they are methods on a class that have nothing to do with the state of that class.
  2. They are global procedures (as in procedural code) that are categorically not object oriented programming.
  3. They kill testability of code bases. Misko Hevery agrees.
  4. They are not polymorphic in that they cannot inherit, be inherited, or implement interfaces.
  5. They force programmers to know more things up front.

I would add to this list:

  1. They hide dependencies and allow an illusion of simplicity in APIs to be created (they cause your API to ‘lie’.)
  2. They make runtime reasoning about the code very difficult when they encapsulate state.
  3. Simply by existing, they tend to promote global flags if there is a need to extend functionality and not break existing clients.
  4. Static classes tend naturally to balloon in size, since their methods can’t be extended.
  5. They increase potential dependencies in your code base by a factor of order combinatorial.
  6. They cast temporal couplings in stone within your code.

Recovery

If you’ve been reading this and not nodding along, you’ve probably experienced some indignation. Please don’t take this as an assault on the choices you’ve made as a programmer. I’m talking from experience here. Ben Franklin famously said “Experience is the best teacher, but a fool will learn from no other.” I am that fool. I’ve struggled with ugly messes that I (and others) have created via the static concept, and I’ve hit that rock bottom state.

The transition away isn’t as bad as you think. I’ve now regularly been creating entire programs and applications that have no static methods. Zip, zero. It isn’t impossible. Heck, it isn’t even hard. It just requires up front reasoning about your dependency graph, but that reasoning is a skill that sharpens with practice. Like unit testing or TDD, it’s a skill that seems a little unnatural, especially if you started in a procedural language, but it does come, and faster than you think. Before you know it, you’ll be loving your static-free existence and offering counseling to those who are walking your current path through a static nightmare.

By

Adventures in Pure Test-Driven Development

In a previous post some time back, I had expressed some skepticism about TDD as a design practice. I talked about test-driven development and its relationship with prototyping and the “make one to throw away” concept.

Since I’m not one ever to believe that I’ve arrived at the optimal solution, I’m doing another round of pure TDD to see if I can ‘refactor’ my process a little and find improvements in efficiency and/or code quality. As I’m doing this, I’m finding that I’m a little more proficient in the TDD concept than I was in previous attempts, but I’m still not convinced that TDD is a golden hammer appropriate for all solutions, all the time.

I’m going to make a list of pros and cons here as I work, both for myself and for posterity. Once I’ve compiled the list, I’ll wait a little bit, reflect, and write a conclusion on it (so yes, the part at the bottom will be written two or days removed from what you’re reading right now).

Pros

  • Using mocking frameworks (Moles and Moq), maintaining 100% code coverage is effortless
  • Tests tend to be more meaningful for your use cases than retrofitted ones.
  • Better gaurding against regressions
  • TDD is better even than I remember at forcing me to think through various scenarios of method control flow and object state. I’m having far fewer cases of, “oh, I didn’t consider scenario X!”
  • Cuts down on potential for dead code. I’m not doing things like declaring a setter because I’m already declaring a getter and I might as well. The rules of the process don’t let you code that until you have a test for it.
  • Tends to help generate useful and well-conceived abstract utility classes (such as a no-exception wrapper for string splitting that I wrote) that can be reused elsewhere.

Cons

  • Larger design concepts do not seem to be emergent the way they might be in a more shoot-from-the-hip approach. Figuring out when you need a broader pattern seems to require stepping out of the TDD frame of mind
  • There is no specific element of the process that naturally pushes me away from the happy path. You wind up creating tests for exceptional/edge cases the way you would without TDD (I guess that’s not strictly a con, just a lack of pro).
  • It becomes easier to keep plodding away at an ultimately unworkable design. It’s already hard to throw work you’ve put in away, and now you’re generating twice as much code.
  • Correcting tests that have been altered by changing requirements is magnified since your first code often turns out not to be correct. I find myself refactoring tests as often as code in the early going.
  • It has the potential to slow development when you’re new to the process. I suppose one might look at this as a time investment to be paid off when you get more fluid and used to doing it.

Conclusions

I like aspects of this process, and I like it enough that I’m going to keep making stabs at it to find exactly how it works best for me. In my earlier post, I mentioned that I’d do prototyping without tests and then do TDD in earnest when I started writing my “for-real” code. I think I’m going to try to phase it in increasingly to my prototyping as well.

My biggest issue is my perception that TDD removes more emergent macroscopic principles of design. There is no straightforward refactoring I’m aware of that leads to a MVVM pattern of development or to using something like a flyweight. So it’s going to be up to me and my refinement of my own process to reconcile Uncle Bob’s three laws of TDD with sophisticated design concepts.

Of course, I’d be interested to hear, in comments, anyone’s take on how to reconcile these two concepts. Perhaps I just haven’t been at it long enough to see a test that I can write that demands a refactoring to a more complex pattern. Or, perhaps I’ve become so used to recognizing good fits for patterns ahead of time that it’s no longer part of a refactoring for me, but the original ‘factoring’. In that case, I suppose I’d have to retool my methodology for arriving at design patterns.

Regardless, though, it should be an interesting endeavor. I like to shake up my way of doing things as often as possible to look for opportunities for improvement.