IC Improve Code Recipes

Recipe 15.7 · C#

A Lean Utility Library Instead of a Junk Drawer

Problem

The Utility class has grown to two thousand lines. It references System.Web, System.Data.SqlClient and the SMTP client, so any project that wants FormatPhone drags along the whole web and data stack. Nobody can tell which methods are used, and each team has its own slightly different copy.

The way it's often written

Anti-pattern: shown so you can recognize it. Don't copy this one.

C#
// Not to copy: one static class for everything.
public static class Utility
{
    public static string FormatPhone(string s) { /* ... */ }
    public static bool IsValidPhone(string s) { /* ... */ }
    public static string GetConnString() { /* ... */ }
    public static DataSet RunQuery(string sql) { /* ... */ }
    public static void SendErrorEmail(Exception ex) { /* ... */ }
    public static string GetCurrentUserName() { /* ... */ }
    // ... 60 more
}

The improved recipe

The fix is mostly organization, with a few rules. Here is the shape I use:

Text
ImproveCode.Common/             (no dependencies beyond the BCL)
    Text/TextHelpers.cs
    Text/CommonExtensions.cs
    Time/ZoneTime.cs
    Time/BusinessDays.cs
    Time/UsFederalHolidays.cs
    Parsing/SafeParse.cs
    Values/UsPhoneNumber.cs
ImproveCode.Data/               (connections, queries: Chapter 1)
ImproveCode.Mail/               (MailKit sender: Chapter 9)

And here is what a pair of string helpers becomes when it turns into a type:

C#
using System;
using System.Diagnostics.CodeAnalysis;

namespace ImproveCode.Utilities;

public readonly record struct UsPhoneNumber
{
    private readonly string _digits;   // always 10 digits

    private UsPhoneNumber(string digits) => _digits = digits;

    public bool IsEmpty => _digits is null;

    public static bool TryParse(
        [NotNullWhen(true)] string? text, out UsPhoneNumber phone)
    {
        phone = default;
        if (text is null)
        {
            return false;
        }

        Span<char> buffer = stackalloc char[11];
        int count = 0;
        foreach (char c in text)
        {
            if (char.IsAsciiDigit(c))
            {
                if (count == buffer.Length)
                {
                    return false;
                }
                buffer[count++] = c;
            }
            else if (c is not (' ' or '-' or '.' or '(' or ')' or '+'))
            {
                return false;
            }
        }

        ReadOnlySpan<char> digits = buffer[..count];
        if (digits.Length == 11 && digits[0] == '1')
        {
            digits = digits[1..];
        }

        if (digits.Length != 10 || digits[0] is '0' or '1')
        {
            return false;
        }

        phone = new UsPhoneNumber(digits.ToString());
        return true;
    }

    public string ToE164() => IsEmpty ? "" : "+1" + _digits;

    public override string ToString() =>
        IsEmpty
            ? ""
            : $"({_digits[..3]}) {_digits[3..6]}-{_digits[6..]}";
}

Usage snippet:

C#
if (!UsPhoneNumber.TryParse(form.Phone, out UsPhoneNumber phone))
{
    ModelState.AddModelError("Phone", "Enter a 10-digit US number.");
}
customer.Phone = phone.ToE164();   // "+15555550123"

How it works

The rules behind the layout are simple:

  1. Pure helpers only in the common library. If a method touches a database, the file system, the network, configuration, the current user or the clock, it's not a utility. It's a service, and it gets an interface and constructor injection. GetConnString becomes the options pattern (Chapter 6), SendErrorEmail becomes a logger sink (Chapter 4), GetCurrentUserName becomes an injected user accessor (Chapter 16).
  2. Group by topic, not by "helper". Small static classes named after what they do (TextHelpers, ZoneTime, SafeParse) are easy to find and easy to delete.
  3. Promote repeated validation into a type. When the same string is validated and formatted in many places, a value type such as UsPhoneNumber does both once. Once a method accepts a UsPhoneNumber instead of a string, it can't receive an unvalidated value.
  4. One copy, shipped as a package. Publish the common library to an internal NuGet feed (Azure Artifacts, a file share, or GitHub Packages) and version it. Copying the file into each solution is how the archive ended up with 463 Utility classes.
  5. Every helper has a test. Pure functions are the easiest code in the system to test. If a helper is too awkward to test, that's a sign it belongs in a service.

UsPhoneNumber shows the third rule. It accepts the formats people type, rejects letters and impossible numbers (area codes can't start with 0 or 1), and stores one canonical form. ToString formats it for display and ToE164 formats it for SMS providers and storage. The parsing loop uses a stack buffer, so it allocates only the final string.

Variations and pitfalls

  • Resist adding a dependency to the common library "just for one method". The day it references Microsoft.AspNetCore.Http, a console job can no longer use it without pulling in the web stack.
  • Mark helpers internal when only one project needs them. Public surface area in a shared library is a promise to every consumer.
  • Before deleting old Utility methods, find out which ones are called. An IDE's "find all references" or a Roslyn analyzer works within a solution; across many solutions, a text search for Utility. with the method names is crude but effective.
  • Value types need a story for persistence and JSON. Store the canonical string, and add a JsonConverter and an EF Core value converter if you use them.

On .NET Framework

If the common library must serve both .NET Framework 4.8 and modern .NET during a migration, multi-target it (<TargetFrameworks>net8.0;net48</TargetFrameworks>) or target netstandard2.0. Some members used in this chapter, such as DateOnly, TimeProvider, IParsable<T> and char.IsAsciiDigit, don't exist on .NET Framework, so keep those parts behind #if NET8_0_OR_GREATER or in the modern-only target.