Skip to content

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 namespace Uspto) plus UsptoTests/Uspto.Tests.csproj. Folder is USPTO, namespace is Uspto.
  • Type-based folders, each with an Interfaces/ subfolder holding the I-contracts: Services/PatentService.cs + Services/Interfaces/IPatentService.cs; same for Helpers/, 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 occasionally public slips in (inconsistent): Services/Interfaces/IPatentService.cs: void AddPatent(Patent patent); and public bool HasReadyForEmailPatents();

Namespaces, usings, formatting

  • File-scoped namespaces everywhere: namespace Uspto.Services; (every file).
  • Usings are explicit, System*/Microsoft* first, then project Uspto.*, alphabetical, no implicit usings (Startup.cs has 20+ usings). Tests use one Usings.cs with global 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.cs ends }\n\n}).
  • No trailing newline at EOF in most files (ends right at }).

Types, fields, expression style

  • Private fields _camelCase, private readonly always, listed above the ctor: private readonly IPatentService _patentService;
  • var everywhere for locals; target-typed new() is a signature habit: Patent patent = new() { PatentId = new(), Email = ..., StatusId = StatusId.Unfulfilled }; and return 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!; for DbSets. Models/PatentRequest.cs: public string PatentNumber { get; init; } = string.Empty;
  • Nullable enabled (<Nullable>enable</Nullable> in Uspto.csproj), uses string?, ?., ??, ! freely: new(patentRequest?.DocumentCodes ?? Array.Empty<string>()); s.GetService<PatentContext>()!.
  • Enum with explicit integer values, Id suffix 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 factory Doc.CreateDocument(document, patent).
  • Extension methods in a *Extensions static class in Helpers/: 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 always Run. Functions are thin; real work goes to IUsptoService.
  • Request body parsed by hand: await new StreamReader(req.Body).ReadToEndAsync() then JsonConvert.DeserializeObject<PatentRequest>.

DI and configuration

  • All wiring in one Startup : FunctionsStartup, one fluent chain, AddScoped<IX, X>() for services, AddSingleton for settings: .AddScoped<IUsptoService, UsptoService>() ... .AddSingleton<IUsptoApiSettings, UsptoApiSettings>()
  • Constructor injection only; options via IOptionsMonitor<T> and .CurrentValue copied 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 in BuildConfiguration. Secrets via env var helper Startup.GetAppSettings("PatentContext") that throws ApplicationException if missing.
  • Feature toggles are a real concept: settings.json "FeatureToggles": { "IsStopwatch": false }.
  • Cron from config where it varies: [TimerTrigger("%UploadPdfToStorageAndNotifyScheduleTriggerTime%")].

Async

  • Async suffix on every Task method, CancellationToken cancellationToken = default as the last parameter, threaded through every layer: Task SaveChangesAsync(CancellationToken cancellationToken = default);
  • Linked token sources for timeouts: CancellationTokenSource.CreateLinkedTokenSource(_internalTokenSource.Token, externalToken). externalToken / internalToken naming.
  • async Task methods that just forward still await (no elision): await _completeProcessingService.CompleteAsync(patent, cancellationToken);
  • Tests block with .Result in 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(...)).
  • DbContext named after the domain, not the app: PatentContext : DbContext, IUnitOfWork. The context itself implements IUnitOfWork (Data/Database/Interfaces/IUnitOfWork.cs) exposing DbSet<Patent> Patents, and services take IUnitOfWork, 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, StatusId enum column, RequestId identity int, virtual List<Doc> Docs { get; set; } = new(); for navs.
  • Sync LINQ on DbSet inside services (_patents.Any(...), .Include(p => p.Docs).First(...)), async only for SaveChangesAsync.
  • 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) in Models/. DTO suffixes: *Request, *Response; no Dto/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 MSAL ConfidentialClientApplicationBuilder: Helpers/GraphClientHelper.cs: .WithClientSecret(_emailConfiguration.ClientSecret) / AcquireTokenForClient(new[] { _emailConfiguration.ScopeUrl }).
  • Front end calls it with MSAL browser (see Angular) and an x-functions-key header.

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 (not ArgumentNullException.ThrowIfNull).
  • Lower layers catch, log, throw; (rethrow, never throw ex) with finally for completion logs: Services/StorageService.cs.
  • Domain failure state is data: currentDoc.StatusId = StatusId.Failed; then await _patentService.FailAsync(...) then throw;.
  • 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 with if (_logger.IsEnabled(LogLevel.Debug)).
  • Stopwatch-timed functions behind the IsStopwatch toggle (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 unfulfilled in UsptoService.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 project UsptoTests, namespace Uspto.Tests.<Folder>, folders mirror the app (Services/, Models/, Data/, Helpers/, Controllers/ for the functions, Extensions/).
  • Class <Type>Tests (sometimes Test), [TestFixture] + [Category("Unit Tests")], method name = behavior sentence, PascalCase, Async suffix for async tests, occasional Always_ prefix: HasNoUnfulfilledPatents, SavePdfToContainerSavesPdfAsync, Always_HasDocProperties.
  • Style: Arrange / Act / Assert without comments; Assert.That(x, Is.True); grouped with Assert.Multiple(() => { ... }); mocks with Mock.Of<IX>(x => x.Prop == value); custom VerifyLogging extension on Mock<ILogger<T>>; AsMockDbSet() extension to fake DbSet.

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-vuetify autoImport), @mdi/font, Luxon, JSZip + file-saver.
  • Options API with export default { data: () => ({...}), methods: {...} } in src/components/HelloWorld.vue, even though the Vuetify scaffold's App.vue uses <script setup lang="ts">. He did NOT convert the form to Composition API.
  • SFC order: <template>, then <script> (no <style> block at all). App.vue is a bare <v-app><v-main><HelloWorld/></v-main></v-app> shell.
  • Layout: src/components/, src/models/, src/plugins/ (vuetify.ts, webfontloader.ts). No views/, no store/, no router/, no services/ folder: no Vuex/Pinia, no vue-router wiring. (vue-router is 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 via import.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). .editorconfig sets 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-ignore before this.$refs.form.validate(), var in 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 under src/assets/scss, @azure/msal-angular 2.x / msal-browser 2.x.
  • Layout: src/app/components/documents/documents.component.{ts,html}, src/app/services/documents/documents.service.ts, src/app/models/*.ts, root app.module.ts, app-routing.module.ts, auth-config.ts. Path aliases @app/..., @environments/.... Feature folder per component and per service.
  • Component: selector: 'app-documents', templateUrl only (no inline template, no styleUrls), implements OnInit, constructor(private service: DocumentsService, private formBuilder: FormBuilder).
  • State: BehaviorSubject fields with $ suffix, public, .next()/.getValue(), templates use | async into an ng-template context: 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: HttpClient in an @Injectable({ providedIn: 'root' }) service, observe: 'response' as 'body', .pipe(retry(1), catchError(this.handleError)); a TokenInterceptor adds Authorization: WebJobsAuthLevel ${token} (services/token.interceptors.ts).
  • Auth: MSAL redirect flow; MsalGuard on the catch-all route, MsalInterceptor, factory functions in app.module.ts (MSALInstanceFactory, MSALGuardConfigFactory); tokens/email stashed in localStorage.
  • Models: lowerCamelCase classes with hand-written constructors (export class patentRequest { constructor(email: string, ...) {...} }; export class error), interface Account 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-key header, 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, no strict-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)

  1. Interface for everything, in a sibling Interfaces/ folder, one type per file, IOptionsMonitor<T>.CurrentValue assigned to an interface-typed _field.
  2. One Startup file, one fluent .AddScoped<I, T>() chain, services scoped, settings singletons.
  3. Uspto.<Folder> file-scoped namespaces, var, and target-typed new() / return new(...).
  4. Rich entities: behavior methods on the EF entity (AllDocumentsCompleted, GetDirectoryName, Doc.CreateDocument), StatusId enum state machine (Unfulfilled -> Started -> ReadyForEmail -> Fulfilled/Failed).
  5. Async suffix + CancellationToken cancellationToken = default + linked token sources on every layer.
  6. Guard clauses with throw new ArgumentNullException(nameof(x)), brace-less single-line if, early return.
  7. Catch at the boundary, log with a structured message, return the "submit a ticket to the Help Desk" text; rethrow with throw; below.
  8. Feature toggles and tunables in settings.json (IsStopwatch, MinutesLimit) bound as options classes.
  9. Test stack: NUnit + Moq + AutoFixture + Bogus, [Category("Unit Tests")], Assert.Multiple, Mock.Of<>(x => ...), *Tests mirroring folders.
  10. 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.