Anti-Patterns and Worst Practices – Utils Class

tools If you ever start typing “Utils” or “Utility” stop and think a bit; if you need some help, ask a fellow developer a question of what this code actually does. This anti-pattern is caused either by lack of domain knowledge, or laziness, sometimes both. The problem isn’t with the functions that these Utils are performing, but what they’re called and how they’re grouped together. Most often, I see the following types of functions inside a Utils class.

public static class Utils
{
    private const string _filePath = "logfile.txt";

    public static void LogMessage(string message)
    {
        using(TextWriter writer = File.AppendText(_filePath))
        {
            writer.WriteLine(message);
        }
    }

    public static void LogException(Exception ex)
    {
        using (TextWriter writer = File.AppendText(_filePath))
        {
            writer.WriteLine(ex.Message);
        }
    }
}

There’s really no reason that this type of functionality belongs in a Utils class (usually as a static method). If you’re logging something, why not create a Logger class; it is what it is. Something as common as logging has been solved by others in more robust ways than opening a file and writing some text. Better yet, use a solution that already exists and save yourself the time to implement it on your own:

  • log4net (.Net)
  • log4r (Ruby)
  • log4j (Java)

Maybe you have some more specific functionality for which you can’t seem to find a place. You’re taking in some data and spitting out something a bit different. Rather than coding it right inline the objects that need it, you decided to place it somewhere it can be re-used (Good! Following DRY: Don’t Repeat Yourself), inside the Utils class.

public static class Utils
{
    public static string CreateShippingMessage(DayOfWeek dayOfWeek, TimeSpan currentTime)
    {
        var message = "Your package will be delivered ";
        if (dayOfWeek >= DayOfWeek.Monday && dayOfWeek <= DayOfWeek.Thursday)
            message += currentTime < new TimeSpan(0, 17, 45, 0) ? "today" : "tomorrow";
        else
            message += "soon";
        return message;
    }
}

BAD! You got the DRY part right, but you can do better! The first line of this post asks you to ask yourself (or somebody else) what your code is doing. Let’s ask ourselves what this code is doing. It is taking in a day of the week and the current time and is spitting out a shipping delivery message. I’m not always great with naming, but I don’t see anything wrong with creating a class named ShippingMessageGenerator. At least when I come across a function that exists in a ShippingMessageGenerator class I have more of an idea of what it is all about than if I saw the same function in a Utils class.

Call it What it is

We recently needed to modify some code that sends text requests (a RequestExecutor class) to a third-party system. There were characters that needed to be removed from the requests because they are delimiters in the text. Not a hard task, but tackling it at the point of concern would probably cause a lot of repetition in our code for cleaning up this data. We could put it in a static RequestUtils class so the code is in one place. This is better, but still doesn’t give the full clarity of what is going on.

One of our guys was working on this bug and implemented a RequestSanitizer class that does exactly what it sounds like. Sanitizes or cleans up the request. Our RequestExecutor has a dependency on this class since it only worries about sending clean requests. It doesn’t have the job of cleaning them. Why is this good?

  • The code that sanitizes the requests is in one place, and is obvious.
  • The RequestSanitizer class has only one reason to change.

Filling that Gap

I’m not trying to tell anybody that they shouldn’t use a Utils class, but rather that they should know that there’s probably a better way. Since the problem I see with Utility classes is that they’re usually just a collection of a whole bunch of stuff that doesn’t really belong together, they probably exist for common reasons. There’s a lot of functionality that people have to write that seems fitting in a Utility class. However, if you’re writing this code, somebody else has probably already written it. You can more than likely take advantage of some open source libraries to fulfill this need.

  • If you have some methods that take in one object to create another, why not consider Jimmy Bogard’s AutoMapper.
  • Any of the log4__ libraries mentioned prior.
  • If you’re using ASP.NET MVC, there’s a lot of value in using MvcContrib.

Remember, ask yourself: What does this code do?

[See more Anti-Patterns and Worst Practices]

Related:

Post Footer automatically generated by Add Post Footer Plugin for wordpress.

About Chris Missal

Oh hey, I'm a Senior Consultant for Headspring in Austin, TX. I've been working in software professionally since 2006 and I really, really love it. I'm mostly in the Microsoft world, but enjoy building computer things of all sorts (to be vague). When I'm not slinging code, I'm probably out and about slinging discs, bowling balls, or good beer with great friends.
This entry was posted in Best Practices, Design Principles, DRY. Bookmark the permalink. Follow any comments here with the RSS feed for this post.
  • http://webgambit.com Karthik Hariharan

    It’s clear to me why I shouldn’t have a Utils class and that I should probably see if there’s a better existing place to put the logic or a library that might do it for me.

    Now how do I determine where the logic should go if there is NO existing class that it can be a part of and no third party library does what I need?

    How should I name my new class, where should it go, and what patterns make the most sense to follow in its implementation?

  • http://www.lostechies.com/members/chrismissal/default.aspx Chris Missal

    @Karthik
    Foremost, you want to make sure that your classes only have one reason to change. If you’re looking to add something new, there’s likely a chance you’ll want to add a new class(es). Modifying existing functionality would probably allow you to keep the code in an existing class. As for naming it, something obvious is always good; I don’t mind long class names most of the time, intellisense helps speed things up so you don’t have to type the whole class name most of the time (there should be limits of course ;) A lot of this has to do with the domain you’re working in and there isn’t a set of rules you must follow, just keep an open mind and don’t be afraid to see and fix any mistakes.

  • http://www.lennybacon.com/ Daniel Fisher

    1) Since Extension Methods are in place ther mustn’t be Util-Classes

    2) Take whats already in the platform: System.Diagnostics

    Rgs,
    Daniel

  • http://delta3consulting.com Dustin Thostenson

    Yet another handy installment of MissalCode! Thanks Chris!

  • http://www.lostechies.com/members/chrismissal/default.aspx Chris Missal

    @Dustin
    Ha, I like that… “MissalCode”

  • http://www.lostechies.com/members/rssvihla/default.aspx Ryan Svihla

    Can we have a special mention for “Manager” classes.

  • AndyB

    Chris

    After following the SRP and DRY principles a couple of times, what you explain above should become almost instinctive for a good developer.
    What I mean by instinctive isn’t necessarily that you remove or avoid these Utility classes without thinking but rather when you see or think of them, you get that stench of bad / rotting code. Your design nose then gets more sensitive as you plough on to the next projects.
    Anyways, good post!

    @Ryan – a single Manager class or multiple XYZManager classes or both?

  • steve

    I think Utilities classes are a great way to PREVENT code redundancy – they give the common developer a single place to look for utilities. Also they make code more readable.

    I agree, that Log4J should be used instead of writing your own logger…. But in a typical application , there often exist clumsy , verbose API’s for doing simple tasks … i.e. low level API’s for executing queries. Its alot easier to read code that sais

    List employees = db.getAllEmployees();
    BeanUtilities.sortResults(employees, “birthday”);

    then to write

    Collections.sort(employees, new Comparable(Object e){
    return java.util.Date.compare … (Employee)e.getBirthday()…….}; //you get the point !

    Furthermore when internal APIs for such tasks are used, they encourage developers to actually USE the same mechanism and logic over.

    Classes and object orientation are great, but its easy to get lost in a sea of objects…. Utilities classes that wrap objects and muddy APIs are extremely valuable.

  • http://pulse.yahoo.com/_OXSLJJIVWOEGOGNVRDBGSUN3PU Any name which u like to call

    The code snippets are not line wrapped. It’s annoying.

    • http://chrismissal.lostechies.com Chris Missal

      Thanks for pointing that out, it’s fixed now. I also found some broken links that I could correct, cheers!

  • Dark Phoenix

    Well, I don’t really see a need for a Utils collection in something like Java/.NET, but I know in my PHP library I have a utilities file.  It contains functions that perform generic actions on primitives that don’t really belong in any specific class (for example, merging two arrays, checking for string prefixes/suffixes, and so on).  And even in that situation, when a lot of functions on one primitive start to pile up, it’s usually a clue to write a class abstraction over that primitive (for example, I have 15 or so string functions, so I’m working on refactoring them into a String abstraction class rather than leave them as loose functions).