Recipe 17.2 · C#
From ObjectState to Results and Exceptions in the Usage Layer
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.
// From CFATS Manager: CFATSLibrary\Usage\IncidentUse.cs
// lines 95-126 and 157-172 (abridged, re-wrapped)
public int InsertIncident()
{
SQLManager manager =
new SQLManager(ServerInfo.GetConnectionString());
string IncidentID = string.Empty;
int RecordID = 0;
if (_ObjectReference.IncidentType == "Incident")
{
IncidentID = manager.InsertFacilityIncidentDefault(
_ObjectReference.FacilityID, /* ... */);
}
else if (_ObjectReference.IncidentType == "Threat")
{ /* ... same call shape, 11 arguments ... */ }
else if (_ObjectReference.IncidentType == "NearMiss")
{ /* ... */ }
_State = manager.State;
if (_State.ErrorOccurred)
{
RecordID = 0;
_State.DisplayMessage = "DB Error: Insert failed.";
}
else
{
RecordID = Int32.Parse(IncidentID);
_State.DisplayMessage =
"Incident saved successfully, click Back to exit";
}
return RecordID;
}
public void UpdateIncidentFile(int IncidentID, string FileGUID)
{
SQLManager manager =
new SQLManager(ServerInfo.GetConnectionString());
manager.UpdateIncidentFile(IncidentID, FileGUID);
if (_State.ErrorOccurred)
{
_State.DisplayMessage = "DB Error: file delete failed";
}
// ...
}
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).
The improved recipe
No packages beyond the base class library.
using System;
using System.Collections.Generic;
using System.Threading;
using System.Threading.Tasks;
namespace ImproveCode.Cfats.Incidents;
public enum IncidentKind { Incident, Threat, NearMiss }
public sealed record NewIncident(
int FacilityId,
IncidentKind Kind,
string Name,
DateTimeOffset OccurredAt,
string Location,
string ReportedTo,
string? CommunicatedBy,
string? IdentifiedBy,
string Description,
string Response,
Guid? FileId);
public sealed class Result<T>
{
private Result(T? value, IReadOnlyList<string> errors)
{
Value = value;
Errors = errors;
}
public T? Value { get; }
public IReadOnlyList<string> Errors { get; }
public bool Succeeded => Errors.Count == 0;
public static Result<T> Ok(T value) => new(value, []);
public static Result<T> Fail(IReadOnlyList<string> errors) =>
new(default, errors);
}
public interface IIncidentStore
{
Task<int> InsertAsync(NewIncident incident, CancellationToken ct);
}
public sealed class IncidentService(
IIncidentStore store, TimeProvider clock)
{
public async Task<Result<int>> RecordAsync(
NewIncident incident, CancellationToken ct = default)
{
ArgumentNullException.ThrowIfNull(incident);
List<string> errors = Validate(incident, clock.GetUtcNow());
if (errors.Count > 0)
{
return Result<int>.Fail(errors);
}
// Infrastructure failures throw and reach the global handler.
int id = await store.InsertAsync(incident, ct);
return Result<int>.Ok(id);
}
private static List<string> Validate(
NewIncident i, DateTimeOffset now)
{
List<string> errors = [];
if (string.IsNullOrWhiteSpace(i.Name))
{
errors.Add("A name is required.");
}
if (i.OccurredAt > now)
{
errors.Add("The occurrence date is in the future.");
}
if (i.Kind == IncidentKind.Threat &&
(string.IsNullOrWhiteSpace(i.CommunicatedBy) ||
string.IsNullOrWhiteSpace(i.IdentifiedBy)))
{
errors.Add(
"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.