Recipe 17.2 · Python
From ObjectState to Results and Exceptions in the Usage Layer
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
Every Usage class in CFATSLibrary has the same shape. It holds an ObjectReference (the model being saved) and a State (an ObjectState with ErrorOccurred, ErrorMessage and DisplayMessage). Methods return a value and leave success or failure in State. Pages check State after every call and copy DisplayMessage to the screen. Nothing throws, and that means a missed check is a silent failure.
The way it's often written
Anti-pattern: shown so you can recognize it. Don't copy this one.
From CFATS Manager, abridged. The argument lists were 9 to 11 items long.
Look closely at UpdateIncidentFile. It never copies manager.State into _State, so it checks the state from the constructor, which is always clean. If the update fails, the page reports success. Nothing in the pattern catches this: no compiler warning, no exception, no log entry. The error logging in DataObject.HandleException was also commented out at some point, so a database error left no trace anywhere.
The method also mixes three jobs: choosing a stored procedure by a magic string, translating database state into UI text, and deciding what a "record ID" is when things fail (zero).
Requirements: Python 3.12+. Standard library only, nothing to install.
"""Usage-layer insert that branches on type strings and reports via shared ObjectState
Source: ImproveCode, Chapter 17, Recipe 17.2 "From ObjectState to Results and Exceptions in the Usage Layer"
Section: The way it's often written
Book page: 386-387 -- original C# listing
Converted from C# to Python.
ANTI-PATTERN: kept deliberately faithful to the C# 'not to copy' example; do not use.
ObjectState/SQLManager/ServerInfo are minimal placeholders; Int32.Parse becomes int().
"""
from dataclasses import dataclass
from typing import Any
@dataclass
class ObjectState:
error_occurred: bool = False
display_message: str = ""
class SQLManager: # placeholder for the legacy data class
def __init__(self, connection_string: str) -> None:
self.state = ObjectState()
def insert_facility_incident_default(self, facility_id: int, *args: Any) -> str: ...
def update_incident_file(self, incident_id: int, file_guid: str) -> None: ...
class ServerInfo: # placeholder
@staticmethod
def get_connection_string() -> str: ...
# From CFATS Manager: CFATSLibrary\Usage\IncidentUse.cs
# lines 95-126 and 157-172 (abridged, re-wrapped)
class IncidentUse:
def __init__(self, object_reference: Any) -> None:
self._object_reference = object_reference
self._state = ObjectState()
def insert_incident(self) -> int:
manager = SQLManager(ServerInfo.get_connection_string())
IncidentID = ""
RecordID = 0
if self._object_reference.IncidentType == "Incident":
IncidentID = manager.insert_facility_incident_default(
self._object_reference.FacilityID, # ...
)
elif self._object_reference.IncidentType == "Threat":
... # same call shape, 11 arguments
elif self._object_reference.IncidentType == "NearMiss":
...
self._state = manager.state
if self._state.error_occurred:
RecordID = 0
self._state.display_message = "DB Error: Insert failed."
else:
RecordID = int(IncidentID)
self._state.display_message = "Incident saved successfully, click Back to exit"
return RecordID
def update_incident_file(self, IncidentID: int, FileGUID: str) -> None:
manager = SQLManager(ServerInfo.get_connection_string())
manager.update_incident_file(IncidentID, FileGUID)
if self._state.error_occurred:
self._state.display_message = "DB Error: file delete failed"
# ...
The improved recipe
No packages beyond the base class library.
Requirements: Python 3.12+. Standard library only, nothing to install.
"""Incident service returning a Result for validation errors; infrastructure errors raise
Source: ImproveCode, Chapter 17, Recipe 17.2 "From ObjectState to Results and Exceptions in the Usage Layer"
Section: The improved recipe
Book page: 387-389 -- original C# listing
Converted from C# to Python.
Records become frozen dataclasses, the enum an Enum, Result<T> a generic class and
IIncidentStore a Protocol. TimeProvider becomes a Clock Protocol; CancellationToken is
dropped in favour of asyncio task cancellation.
"""
from __future__ import annotations
import uuid
from dataclasses import dataclass
from datetime import datetime
from enum import Enum, auto
from typing import Protocol
class IncidentKind(Enum):
INCIDENT = auto()
THREAT = auto()
NEAR_MISS = auto()
@dataclass(frozen=True)
class NewIncident:
facility_id: int
kind: IncidentKind
name: str
occurred_at: datetime
location: str
reported_to: str
communicated_by: str | None
identified_by: str | None
description: str
response: str
file_id: uuid.UUID | None
class Result[T]:
def __init__(self, value: T | None, errors: tuple[str, ...]) -> None:
self._value = value
self._errors = errors
@property
def value(self) -> T | None:
return self._value
@property
def errors(self) -> tuple[str, ...]:
return self._errors
@property
def succeeded(self) -> bool:
return len(self._errors) == 0
@staticmethod
def ok[V](value: V) -> Result[V]:
return Result(value, ())
@staticmethod
def fail[V](errors: list[str] | tuple[str, ...]) -> Result[V]:
return Result[V](None, tuple(errors))
class IncidentStore(Protocol):
async def insert(self, incident: NewIncident) -> int: ...
class Clock(Protocol):
def get_utc_now(self) -> datetime: ...
class IncidentService:
def __init__(self, store: IncidentStore, clock: Clock) -> None:
self._store = store
self._clock = clock
async def record(self, incident: NewIncident) -> Result[int]:
if incident is None:
raise TypeError("incident must not be None")
errors = self._validate(incident, self._clock.get_utc_now())
if len(errors) > 0:
return Result.fail(errors)
# Infrastructure failures raise and reach the global handler.
id_ = await self._store.insert(incident)
return Result.ok(id_)
@staticmethod
def _validate(i: NewIncident, now: datetime) -> list[str]:
errors: list[str] = []
if not i.name or not i.name.strip():
errors.append("A name is required.")
if i.occurred_at > now:
errors.append("The occurrence date is in the future.")
if i.kind == IncidentKind.THREAT and (
not (i.communicated_by or "").strip() or not (i.identified_by or "").strip()
):
errors.append("A threat needs 'communicated by' and 'identified by'.")
return errors
How it works
The rewrite separates two kinds of failure that ObjectState lumped together. Expected failures are things a user can fix: a blank name, a date in the future, a threat without the two extra names. These come back as a Result<int> with messages the page can show. Unexpected failures are a dropped connection, a constraint violation or a timeout. These throw. One global handler logs them with the stack trace and shows a generic error page (Chapter 5). Nobody has to remember to check anything for the second kind. Forgetting is no longer possible.
The magic strings "Incident", "Threat" and "NearMiss" become an enum. A typo is now a compile error, not a branch that silently does nothing.
The service depends on IIncidentStore and TimeProvider, both passed in. That makes the business rule ("an incident can't be in the future") testable without a database or a clock. Use FakeTimeProvider from Microsoft.Extensions.TimeProvider.Testing in tests. The original rule lived in the page, in a date-comparison helper, and could only be tested by clicking.
UI text is no longer the service's business. "Incident saved successfully, click Back to exit" belongs to the page that has a Back button.
Variations and pitfalls
- Don't overuse Result. If every method returns
Result<T>, you have rebuiltObjectStatewith generics. Return results for validation and business-rule outcomes. Let infrastructure exceptions fly. - One entity, one service is fine. The
Usagefolder's one-class-per-entity layout was sound. Keep that structure and change only how failure is reported. - Copy-paste breeds the
UpdateIncidentFilebug. The library has 38Usageclasses, and every method repeats the "create manager, call, copy state, check state" ritual by hand. Any ritual repeated a few hundred times will be skipped somewhere. Patterns that need no ritual (exceptions, results returned from the call) are safer than ones that rely on discipline. - Three insert procedures, one shape. The three incident kinds differ by two optional names. One
NewIncidentwith nullableCommunicatedByandIdentifiedBy, and one procedure (Recipe 17.3), replace six procedures and three branches.