Los Techies : Blogs about software and anything tech!

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]

Kick It on DotNetKicks.com
Posted Jun 01 2009, 08:36 AM by Chris Missal

Comments

Chris Missal wrote Anti-Patterns and Worst Practices – You’re Doing it Wrong!
on 06-01-2009 9:20 AM

When shown ideal code, I think developers understand why it is favorable. When it is regarding Separation

Karthik Hariharan wrote re: Anti-Patterns and Worst Practices – Utils Class
on 06-01-2009 12:53 PM

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?

Chris Missal wrote re: Anti-Patterns and Worst Practices – Utils Class
on 06-01-2009 2:23 PM

@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.

Daniel Fisher wrote re: Anti-Patterns and Worst Practices – Utils Class
on 06-02-2009 2:43 AM

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

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

Rgs,

Daniel

Reflective Perspective - Chris Alcock » The Morning Brew #359 wrote Reflective Perspective - Chris Alcock &raquo; The Morning Brew #359
on 06-02-2009 3:30 AM

Pingback from  Reflective Perspective - Chris Alcock  » The Morning Brew #359

Utils anti-pattern & AutoMapper : David Laing’s blog wrote Utils anti-pattern &#038; AutoMapper : David Laing&#8217;s blog
on 06-02-2009 5:18 AM

Pingback from  Utils anti-pattern & AutoMapper : David Laing’s blog

Dustin Thostenson wrote re: Anti-Patterns and Worst Practices – Utils Class
on 06-02-2009 9:50 AM

Yet another handy installment of MissalCode!  Thanks Chris!

Chris Missal wrote re: Anti-Patterns and Worst Practices – Utils Class
on 06-02-2009 10:37 AM

@Dustin

Ha, I like that... "MissalCode"

Sanjeev Agarwal wrote Daily Tech Links - June 3, 2009
on 06-03-2009 2:23 AM

Daily Tech Links - June 3, 2009 Web Development Web Browsers Need a Social Layer XAML: Using Generic

Ryan Svihla wrote re: Anti-Patterns and Worst Practices – Utils Class
on 06-03-2009 11:33 PM

Can we have a special mention for "Manager" classes.

AndyB wrote re: Anti-Patterns and Worst Practices – Utils Class
on 06-04-2009 12:10 AM

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?

The Technology Post for June 2nd | rapid-DEV.net wrote The Technology Post for June 2nd | rapid-DEV.net
on 06-14-2009 12:38 PM

Pingback from  The Technology Post for June 2nd | rapid-DEV.net

What are some class names that would signal a need for refactoring? « Best Of StackOverflow wrote What are some class names that would signal a need for refactoring? &laquo; Best Of StackOverflow
on 07-28-2009 1:27 AM

Pingback from  What are some class names that would signal a need for refactoring? « Best Of StackOverflow

Add a Comment

(required)  
(optional)
(required)  
Remember Me?

Enter the numbers above:
Copyright Los Techies 2008, 2009. All rights reserved.
Powered by Community Server (Commercial Edition), by Telligent Systems