Recipe 15.7 · Python
A Lean Utility Library Instead of a Junk Drawer
The Python listings are conversions of the book's C# code to Python 3.12. Each file's header says what it needs to run. The explanations were written for the C# version, so some names in the text refer to .NET.
- Problem
- The way it's often written
- The improved recipe
- How it works
- Variations and pitfalls
- On .NET Framework
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.
Requirements: Python 3.12+. Standard library only, nothing to install.
"""A single catch-all Utility class mixing unrelated concerns
Source: ImproveCode, Chapter 15, Recipe 15.7 "A Lean Utility Library Instead of a Junk Drawer"
Section: The way it's often written
Book page: 345 -- original C# listing
Converted from C# to Python.
ANTI-PATTERN: kept deliberately faithful to the C# 'not to copy' example; do not use.
Static class becomes a class of staticmethods; DataSet becomes a list of row tuples.
"""
from typing import Any
# Not to copy: one static class for everything.
class Utility:
@staticmethod
def format_phone(s: str) -> str: ...
@staticmethod
def is_valid_phone(s: str) -> bool: ...
@staticmethod
def get_conn_string() -> str: ...
@staticmethod
def run_query(sql: str) -> list[tuple[Any, ...]]: ...
@staticmethod
def send_error_email(ex: Exception) -> None: ...
@staticmethod
def get_current_user_name() -> str: ...
# ... 60 more
The improved recipe
The fix is mostly organization, with a few rules. Here is the shape I use:
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:
Usage snippet:
Requirements: Python 3.12+. Standard library only, nothing to install.
"""A US phone-number value type with strict parsing and E.164 output
Source: ImproveCode, Chapter 15, Recipe 15.7 "A Lean Utility Library Instead of a Junk Drawer"
Section: The improved recipe
Book page: 346-347 -- original C# listing
Converted from C# to Python.
The readonly record struct becomes a frozen dataclass; TryParse(out ...) returns the
value or None, and UsPhoneNumber.EMPTY stands in for default(UsPhoneNumber).
"""
from __future__ import annotations
from dataclasses import dataclass
from typing import ClassVar
_SEPARATORS = frozenset(" -.()+")
@dataclass(frozen=True)
class UsPhoneNumber:
_digits: str | None = None # always 10 digits when set
EMPTY: ClassVar[UsPhoneNumber]
@property
def is_empty(self) -> bool:
return self._digits is None
@classmethod
def try_parse(cls, text: str | None) -> UsPhoneNumber | None:
if text is None:
return None
buffer: list[str] = []
for c in text:
if "0" <= c <= "9":
if len(buffer) == 11:
return None
buffer.append(c)
elif c not in _SEPARATORS:
return None
digits = "".join(buffer)
if len(digits) == 11 and digits[0] == "1":
digits = digits[1:]
if len(digits) != 10 or digits[0] in ("0", "1"):
return None
return cls(digits)
def to_e164(self) -> str:
return "" if self._digits is None else "+1" + self._digits
def __str__(self) -> str:
d = self._digits
return "" if d is None else f"({d[:3]}) {d[3:6]}-{d[6:]}"
UsPhoneNumber.EMPTY = UsPhoneNumber()
Requirements: Python 3.12+. Standard library only, nothing to install.
"""Validate a form phone field and store it in E.164 form
Source: ImproveCode, Chapter 15, Recipe 15.7 "A Lean Utility Library Instead of a Junk Drawer"
Section: The improved recipe
Book page: 347 -- original C# listing
Converted from C# to Python.
Usage fragment wrapped in a function; ModelState.AddModelError becomes appending to a
field-error dict.
"""
from typing import Any
from p346_r15_7_us_phone_number_value_type import UsPhoneNumber
def example(form: Any, customer: Any, model_errors: dict[str, list[str]]) -> None:
phone = UsPhoneNumber.try_parse(form.phone)
if phone is None:
model_errors.setdefault("Phone", []).append("Enter a 10-digit US number.")
phone = UsPhoneNumber.EMPTY
customer.phone = phone.to_e164() # "+15555550123"
How it works
The rules behind the layout are simple:
- 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.
GetConnStringbecomes the options pattern (Chapter 6),SendErrorEmailbecomes a logger sink (Chapter 4),GetCurrentUserNamebecomes an injected user accessor (Chapter 16). - 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. - Promote repeated validation into a type. When the same string is validated and formatted in many places, a value type such as
UsPhoneNumberdoes both once. Once a method accepts aUsPhoneNumberinstead of astring, it can't receive an unvalidated value. - 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
Utilityclasses. - 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
internalwhen only one project needs them. Public surface area in a shared library is a promise to every consumer. - Before deleting old
Utilitymethods, 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 forUtility.with the method names is crude but effective. - Value types need a story for persistence and JSON. Store the canonical string, and add a
JsonConverterand 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.