Andrew Jones: Personal Coding Style Guide¶
Source: his USPTO hackathon repos (andrewjonesdev/USPTO, USPTO-UI-Vue, USPTO-UI-Angular), read-only shallow clones.
Paths below are relative to each repo root. Note: the .NET repo is Azure Functions (not controllers), net6.0, EF Core 6.
Caveat: the Vue repo is a thin stub (one component, HelloWorld.vue, built on the Vuetify scaffold). The Vue "style" evidence is
therefore light; the Angular repo is the richer front-end sample.
1. C# back end¶
Layout and naming¶
- Two projects:
USPTO/Uspto.csproj(root namespaceUspto) plusUsptoTests/Uspto.Tests.csproj. Folder isUSPTO, namespace isUspto. - Type-based folders, each with an
Interfaces/subfolder holding the I-contracts:Services/PatentService.cs+Services/Interfaces/IPatentService.cs; same forHelpers/,Data/,Models/,Data/Database/. - One type per file, file name equals type name. Folders:
Data,Enums,Helpers,Logging,Migrations,Models,Models/Entities,Services. - Every service has an interface, even helpers and settings POCOs:
IMakeEmail,IEmailBuilder,IGraphClientHelper,ITimeSettings,IFeatureToggles. - Entry points sit at the project root, not in a folder:
GetPdfsByPatentNumberFunction.cs,ZipAndEmailFunction.cs,Startup.cs. - Service methods are Verb+Noun:
HasUnfulfilledPatents,GetNextUnfulfilledPatent,SavePdfToContainerAsync. - Interface members are bare (no
public) mostly, but occasionallypublicslips in (inconsistent):Services/Interfaces/IPatentService.cs:void AddPatent(Patent patent);andpublic bool HasReadyForEmailPatents();
Namespaces, usings, formatting¶
- File-scoped namespaces everywhere:
namespace Uspto.Services;(every file). - Usings are explicit,
System*/Microsoft*first, then projectUspto.*, alphabetical, no implicit usings (Startup.cshas 20+ usings). Tests use oneUsings.cswithglobal using NUnit.Framework;. - Allman braces for types and methods; braces are often omitted on single-statement
if(guard clauses, early returns):Services/UsptoService.cs:if (email == null) throw new ArgumentNullException(nameof(email)); - 4-space indent. Files are UTF-8 with BOM and CRLF (Visual Studio defaults). Stray blank lines before closing braces happen (
GetPdfsByPatentNumberFunction.csends}\n\n}). - No trailing newline at EOF in most files (ends right at
}).
Types, fields, expression style¶
- Private fields
_camelCase,private readonlyalways, listed above the ctor:private readonly IPatentService _patentService; vareverywhere for locals; target-typednew()is a signature habit:Patent patent = new() { PatentId = new(), Email = ..., StatusId = StatusId.Unfulfilled };andreturn new(HttpStatusCode.Created);and_internalTokenSource = new();- Block bodies for methods; expression-bodied members are essentially unused (
Services/PatentService.cs:public bool HasUnfulfilledPatents() { return _patents.Any(...); }). - Primary constructors / records not used (2022-era). DTOs are plain classes.
- Properties:
{ get; init; } = string.Empty;for settings/requests,{ get; set; } = string.Empty;for EF entities,= null!;forDbSets.Models/PatentRequest.cs:public string PatentNumber { get; init; } = string.Empty; - Nullable enabled (
<Nullable>enable</Nullable>inUspto.csproj), usesstring?,?.,??,!freely:new(patentRequest?.DocumentCodes ?? Array.Empty<string>());s.GetService<PatentContext>()!. - Enum with explicit integer values,
Idsuffix on the enum name:Enums/StatusId.cs->Unfulfilled = 0, Started = 1, ReadyForEmail = 2, Fulfilled = 3, Failed = 4. - Rich domain methods live on the entity (not anemic):
Patent.AllDocumentsCompleted(),Patent.GetDirectoryName(), static factoryDoc.CreateDocument(document, patent). - Extension methods in a
*Extensionsstatic class inHelpers/:FileContentResultExtensions.RenameFile(this FileContentResult file, Doc doc).
Functions instead of controllers¶
- Azure Functions in-proc,
[FunctionName("...")]+[HttpTrigger(..., Route = "...")]/[TimerTrigger(...)]. No controllers, no minimal APIs.GetPdfsByPatentNumberFunction.cs:[FunctionName("GetPdfsByPatentNumber")] public async Task<HttpResponseMessage> Run(...) - Class name =
<FunctionName>Function, entry method alwaysRun. Functions are thin; real work goes toIUsptoService. - Request body parsed by hand:
await new StreamReader(req.Body).ReadToEndAsync()thenJsonConvert.DeserializeObject<PatentRequest>.
DI and configuration¶
- All wiring in one
Startup : FunctionsStartup, one fluent chain,AddScoped<IX, X>()for services,AddSingletonfor settings:.AddScoped<IUsptoService, UsptoService>()....AddSingleton<IUsptoApiSettings, UsptoApiSettings>() - Constructor injection only; options via
IOptionsMonitor<T>and.CurrentValuecopied into an interface-typed field:public UsptoData(IOptionsMonitor<UsptoApiSettings> usptoApiSettingsMonitor) { _usptoApiSettings = usptoApiSettingsMonitor.CurrentValue; }Parameter naming:<thing>Monitor. - Settings POCO + matching interface, bound by section name:
.Configure<UsptoApiSettings>(configuration.GetSection("UsptoApiSettings")). Classes:FeatureToggles,TimeSettings,EmailConfiguration. settings.json(committed, non-secret) +local.settings.json+ env vars, hand-built inBuildConfiguration. Secrets via env var helperStartup.GetAppSettings("PatentContext")that throwsApplicationExceptionif missing.- Feature toggles are a real concept:
settings.json"FeatureToggles": { "IsStopwatch": false }. - Cron from config where it varies:
[TimerTrigger("%UploadPdfToStorageAndNotifyScheduleTriggerTime%")].
Async¶
Asyncsuffix on every Task method,CancellationToken cancellationToken = defaultas the last parameter, threaded through every layer:Task SaveChangesAsync(CancellationToken cancellationToken = default);- Linked token sources for timeouts:
CancellationTokenSource.CreateLinkedTokenSource(_internalTokenSource.Token, externalToken).externalToken/internalTokennaming. async Taskmethods that just forward stillawait(no elision):await _completeProcessingService.CompleteAsync(patent, cancellationToken);- Tests block with
.Resultin places (function.Run(req).Result).
Data access¶
- EF Core (SQL Server) with code-first migrations; no Dapper, no stored procs.
Migrations/20230526182058_InitialCreate.cs;.AddDbContext<PatentContext>(options => options.UseSqlServer(...)). DbContextnamed after the domain, not the app:PatentContext : DbContext, IUnitOfWork. The context itself implementsIUnitOfWork(Data/Database/Interfaces/IUnitOfWork.cs) exposingDbSet<Patent> Patents, and services takeIUnitOfWork, not the context. Registered via.AddScoped<IUnitOfWork>(s => s.GetService<PatentContext>()!).- Data annotations, not Fluent API:
[Key] public Guid PatentId,[StringLength(255)],[DatabaseGenerated(DatabaseGeneratedOption.Identity)]. Attribute on the same line as a simple property:[Key] public Guid PatentId { get; set; }. - Guid primary key named
<Entity>Id,StatusIdenum column,RequestIdidentity int,virtual List<Doc> Docs { get; set; } = new();for navs. - Sync LINQ on
DbSetinside services (_patents.Any(...),.Include(p => p.Docs).First(...)), async only forSaveChangesAsync. - Outbound HTTP data layer is separate from DB:
Data/UsptoData.cs(Flurl + Polly retry):url.GetJsonAsync<PatentResponse>(),return await result ?? new PatentResponse();. - Entities in
Models/Entities/; API shapes (PatentRequest,PatentResponse,DocumentResponse,ResultDocument) inModels/. DTO suffixes:*Request,*Response; noDto/ViewModel. Third-party JSON property casing preserved (Resultbag).
Auth¶
- Back end: Function-level key (
AuthorizationLevel.Function) + Entra app-only token to Microsoft Graph for sending mail via MSALConfidentialClientApplicationBuilder:Helpers/GraphClientHelper.cs:.WithClientSecret(_emailConfiguration.ClientSecret)/AcquireTokenForClient(new[] { _emailConfiguration.ScopeUrl }). - Front end calls it with MSAL browser (see Angular) and an
x-functions-keyheader.
Error handling and logging¶
- Controller/Function boundary: catch-all
catch (Exception exception), log, return a user-facing "submit a ticket to the Help Desk" message:_log.LogError(exception, "Your patents could not be returned. Please submit a ticket to the Help Desk."); - Guards use classic
throw new ArgumentNullException(nameof(x))at the top of public methods (notArgumentNullException.ThrowIfNull). - Lower layers
catch, log,throw;(rethrow, neverthrow ex) withfinallyfor completion logs:Services/StorageService.cs. - Domain failure state is data:
currentDoc.StatusId = StatusId.Failed;thenawait _patentService.FailAsync(...)thenthrow;. - Logging: Serilog + Application Insights sink,
ILogger<T>injected as_log(functions) or_logger(services). Structured templates preferred:"Function RunTime {elapsedTime}", with_logger.BeginScope(new Dictionary<string, object>{...}). Occasional$"..."interpolation in log calls (EmailService.cs) is a lapse, not the norm. Guard debug logs withif (_logger.IsEnabled(LogLevel.Debug)). - Stopwatch-timed functions behind the
IsStopwatchtoggle (copy-pasted across all three functions).
Comments¶
- Almost none. No XML doc comments, no
#region. One inline// if this doesn't complete set back to unfulfilledinUsptoService.cs. Self-documenting names instead. - ReSharper suppression comments are everywhere on entities (
// ReSharper disable once PropertyCanBeMadeInitOnly.Global); a ReSharper/NCrunch shop.[ExcludeFromCodeCoverage]on Startup, DbContext, PatentRequest, data/email classes.
Tests¶
- NUnit 3 + Moq + AutoFixture (
AutoFixture.NUnit3,[AutoData]) + Bogus (Faker), ncrunch, coverlet. Test projectUsptoTests, namespaceUspto.Tests.<Folder>, folders mirror the app (Services/,Models/,Data/,Helpers/,Controllers/for the functions,Extensions/). - Class
<Type>Tests(sometimesTest),[TestFixture]+[Category("Unit Tests")], method name = behavior sentence, PascalCase,Asyncsuffix for async tests, occasionalAlways_prefix:HasNoUnfulfilledPatents,SavePdfToContainerSavesPdfAsync,Always_HasDocProperties. - Style: Arrange / Act / Assert without comments;
Assert.That(x, Is.True); grouped withAssert.Multiple(() => { ... }); mocks withMock.Of<IX>(x => x.Prop == value); customVerifyLoggingextension onMock<ILogger<T>>;AsMockDbSet()extension to fakeDbSet.
2. Vue front end (USPTO-UI-Vue)¶
- Vue 3.2 (
"vue": "^3.2.38"), Vite 3, TypeScript 4, Vuetify 3 ("vuetify": "^3.0.0",vite-plugin-vuetifyautoImport),@mdi/font, Luxon, JSZip + file-saver. - Options API with
export default { data: () => ({...}), methods: {...} }insrc/components/HelloWorld.vue, even though the Vuetify scaffold'sApp.vueuses<script setup lang="ts">. He did NOT convert the form to Composition API. - SFC order:
<template>, then<script>(no<style>block at all).App.vueis a bare<v-app><v-main><HelloWorld/></v-main></v-app>shell. - Layout:
src/components/,src/models/,src/plugins/(vuetify.ts, webfontloader.ts). Noviews/, nostore/, norouter/, noservices/folder: no Vuex/Pinia, no vue-router wiring. (vue-routeris a dependency but unused.) - Models: lowerCamelCase type/class names that match the file:
src/models/pdf.ts->export type pdf = {...};document.ts->export type document;form.interface.ts->export interface IForm. Static helper class:documentCodes.getDocumentCodes(). - HTTP: axios called directly inside the component (no service layer),
.then().catch()chains (not try/await), env viaimport.meta.env.VITE_URL, key header"x-functions-key": import.meta.env.VITE_DEFAULT_KEY. - Validation: Vuetify
v-form+ inline rule arrays(v: string) => !!v || "Patent Number is required". - Quotes: double in script, 2-space indent, semicolons in the component but not in
plugins/*.ts(scaffold code)..editorconfigsets 2 spaces. - CSS: no custom CSS; Vuetify utility classes only (
class="d-flex align-center text-center fill-height",mr-4,py-14,text-h2 font-weight-bold). - Sloppy bits visible:
// tslint:disable-next-line+// @ts-ignorebeforethis.$refs.form.validate(),varin script, leftover unused imports (isTemplateNode,Vue),console.log(err.response)as error handling.
3. Angular (USPTO-UI-Angular)¶
- Angular 14.2, TypeScript 4.7 (
strict: true,strictTemplates), RxJS 7.5, NgModules (no standalone), MDB (Material Design for Bootstrap) UI kit, Bootstrap SCSS vendored undersrc/assets/scss,@azure/msal-angular2.x /msal-browser2.x. - Layout:
src/app/components/documents/documents.component.{ts,html},src/app/services/documents/documents.service.ts,src/app/models/*.ts, rootapp.module.ts,app-routing.module.ts,auth-config.ts. Path aliases@app/...,@environments/.... Feature folder per component and per service. - Component:
selector: 'app-documents',templateUrlonly (no inline template, no styleUrls),implements OnInit,constructor(private service: DocumentsService, private formBuilder: FormBuilder). - State:
BehaviorSubjectfields with$suffix, public,.next()/.getValue(), templates use| asyncinto anng-templatecontext:public loading$ = new BehaviorSubject<boolean>(false);and*ngTemplateOutlet="documents; context: { loading: loading$ | async, ... }". - Forms: reactive,
this.formBuilder.nonNullable.control('', [Validators.required, Validators.pattern(/^\d+$/)]). - HTTP:
HttpClientin an@Injectable({ providedIn: 'root' })service,observe: 'response' as 'body',.pipe(retry(1), catchError(this.handleError)); aTokenInterceptoraddsAuthorization: WebJobsAuthLevel ${token}(services/token.interceptors.ts). - Auth: MSAL redirect flow;
MsalGuardon the catch-all route,MsalInterceptor, factory functions inapp.module.ts(MSALInstanceFactory,MSALGuardConfigFactory); tokens/email stashed inlocalStorage. - Models: lowerCamelCase classes with hand-written constructors (
export class patentRequest { constructor(email: string, ...) {...} };export class error), interfaceAccount extends AccountInfo. - Quotes: single in
.ts(.editorconfig:quote_type = single), 2 spaces. User-facing error strings repeat "Please submit a ticket to the Help Desk." exactly like the back end.
Shared between Vue and Angular¶
- Same screen: one "Patent Document Download" page, one patent-number field,
^\d+$validation, hard-coded document-code list (documentCodes),x-functions-keyheader, env-based URL/key, same title and logo, Luxon for dates. - Same models names:
documentCodes, patent request shape. No state library, no router-driven navigation, nostrict-clean polish in the Vue copy. - 2-space TS/Vue indentation,
.editorconfig,azure-pipelines.yml,.deployment(Azure App Service hosting).
4. Signature habits (what makes code look like Andrew's)¶
- Interface for everything, in a sibling
Interfaces/folder, one type per file,IOptionsMonitor<T>.CurrentValueassigned to an interface-typed_field. - One
Startupfile, one fluent.AddScoped<I, T>()chain, services scoped, settings singletons. Uspto.<Folder>file-scoped namespaces,var, and target-typednew()/return new(...).- Rich entities: behavior methods on the EF entity (
AllDocumentsCompleted,GetDirectoryName,Doc.CreateDocument),StatusIdenum state machine (Unfulfilled -> Started -> ReadyForEmail -> Fulfilled/Failed). Asyncsuffix +CancellationToken cancellationToken = default+ linked token sources on every layer.- Guard clauses with
throw new ArgumentNullException(nameof(x)), brace-less single-lineif, earlyreturn. - Catch at the boundary, log with a structured message, return the "submit a ticket to the Help Desk" text; rethrow with
throw;below. - Feature toggles and tunables in
settings.json(IsStopwatch,MinutesLimit) bound as options classes. - Test stack: NUnit + Moq + AutoFixture + Bogus,
[Category("Unit Tests")],Assert.Multiple,Mock.Of<>(x => ...),*Testsmirroring folders. - ReSharper-aware code: suppression comments,
[ExcludeFromCodeCoverage]on infrastructure; Azure DevOps pipeline; Azure-first (Functions, Blob, App Insights, Entra, Graph).
He does NOT: write XML docs or #regions; use controllers, minimal APIs, MediatR, CQRS, repositories-per-entity (he uses IUnitOfWork with DbSets); use Fluent API config; use records/primary constructors/expression-bodied members; use Dapper/stored procs; use Pinia/Vuex/router/views folders in the UI; write CSS (Vuetify/MDB utility classes only); use Composition API for logic.
5. Dated 2022 items: keep modern, explain why¶
| Old habit (evidence) | Modern replacement and why |
|---|---|
net6.0 in-proc Functions, FunctionsStartup, [FunctionName], Microsoft.NET.Sdk.Functions |
.NET 10 isolated worker / Program.cs host builder. In-proc is end-of-life. KEEP the Startup-style single composition root idea. |
Newtonsoft.Json (JsonConvert.DeserializeObject) |
System.Text.Json. Faster, built in, and AOT-safe. |
| UTF-8 BOM + CRLF + no EOF newline | LF/UTF-8 no BOM + final newline via .editorconfig. Cleaner diffs, cross-platform. |
Block-bodied one-liners, ArgumentNullException ifs |
Expression-bodied members where trivial; ArgumentNullException.ThrowIfNull(x). Less noise. |
IOptionsMonitor<T>.CurrentValue captured once in the ctor |
IOptions<T> (static) or monitor with OnChange; validate with ValidateOnStart(). Capturing .CurrentValue defeats reload. |
Secrets in settings.json/env helper that throws ApplicationException |
Key Vault + managed identity; typed options with validation. Client secret in GraphClientHelper should be a managed identity/cert. |
Sync EF queries (_patents.Any, .First) in async flows |
AnyAsync/FirstAsync with the token. Avoid blocking threads. |
Parallel.ForEach mutating Docs.Add(...) (Patent.cs) |
Not thread-safe on List<T>; use sequential loop or Parallel.ForEachAsync with a concurrent collection. Real bug risk. |
Retry on 400 BadRequest with 10 exponential retries (UsptoData.cs) |
Polly v8 ResiliencePipeline / Microsoft.Extensions.Http.Resilience; never retry 400; add jitter. |
catch (Exception) returning 400 for all failures |
ProblemDetails with correct status codes; catch specific exceptions. |
Console.WriteLine for retry logs |
ILogger structured logging. |
.Result in tests; Test_Some_Http_Calling_Method placeholder names |
async Task tests; behavior-named tests (Method_Condition_Expected or his sentence style). |
| NUnit 3.13 / Moq 4.18 / Bogus / AutoFixture | Keep his stack but current versions (NUnit 4: Assert.That is already his style). Pin Moq carefully. |
Vue Options API + // @ts-ignore + $refs (HelloWorld.vue) |
Vue 3 <script setup lang="ts"> with ref/typed template refs; the scaffold's own App.vue already does it. Drop @ts-ignore. |
axios inline in component, .then/.catch, console.log(err.response) |
A src/services/*.ts API module + async/await + user-visible error state. |
var in TS, unused imports, tslint comments |
const/let; ESLint + vue-tsc --noEmit (already in package.json build script). TSLint is dead. |
x-functions-key header + key in VITE_* env (ships to browser) |
Keys in a bundle are public. Use Entra token auth end to end / BFF. |
Angular NgModules, constructor injection, BehaviorSubject triplets |
Standalone components, inject(), signals. (Only if a new Angular front end is made.) |
Angular package.json embeds a private registry URL with an access token |
Never commit credentials; use .npmrc with env var. (Token deliberately not reproduced here.) |
localStorage for access tokens |
MSAL cache only; do not hand-copy tokens into storage. |
Vue HelloWorld.vue name, Vuetify 3.0 alpha-era plugin, webfontloader |
Descriptive component name (PatentDownloadForm.vue), current Vuetify 3, no font loader. |
6. Quick rewrite checklist¶
File-scoped namespace <Root>.<Folder>; | one type per file | Interfaces/ sibling folder | _camelCase readonly fields | var + target-typed new() | *Async + CancellationToken cancellationToken = default | *Request/*Response DTOs, XContext : DbContext, IUnitOfWork | IOptions* settings classes bound by section | guard clauses + nameof | boundary catch + log + friendly message, throw; below | few comments, no XML docs | NUnit/Moq/AutoFixture/Bogus tests with [Category("Unit Tests")] and Assert.Multiple.