Skip to content

Conventions

Michael Riddle edited this page Aug 20, 2026 · 9 revisions

Coding conventions & contributing

The house style lives in two places: .editorconfig (mechanical, enforced by the build) and AGENTS.md (intent and patterns a linter can't express). This page walks both, with real examples, plus the PR checklist and license terms for anyone opening a pull request.

What's enforced vs. what's reviewed

.editorconfig is wired into the build with EnforceCodeStyleInBuild (dotnet_diagnostic.IDE0055.severity = warning), so most whitespace/style violations show up as build warnings, not just an IDE squiggle. What it actually pins down:

Rule .editorconfig setting
File-scoped namespaces csharp_style_namespace_declarations = file_scoped:warning
No this. qualification dotnet_style_qualification_for_* = false:warning
var when the type is apparent csharp_style_var_when_type_is_apparent = true:suggestion
Primary constructors, switch expressions, pattern matching, collection/object initializers all :suggestion
Expression-bodied members when_on_single_line:silent — one-liners only
Allman braces; single-line guard if without braces allowed csharp_new_line_before_open_brace = all, csharp_prefer_braces = when_multiline:silent
const fields → PascalCase naming rule constants_are_pascal_case (warning)
static readonly fields → PascalCase naming rule static_readonly_are_pascal_case (warning)
Private instance fields → _camelCase naming rule private_fields_underscore (warning)
Async methods end in Async naming rule async_methods_end_in_async (suggestion, not warning)
Indentation: 4 spaces (C#, Razor); 2 spaces (json/yml/css/js/html/xml/csproj/slnx) [*] / per-glob sections

Everything below that isn't in that table — folder-equals-namespace, sealed on every concrete type, sealed record vs. mutable class, primary-constructor parameter usage, logging levels, comment style, the named patterns — is convention a reviewer checks by reading the diff, not something the compiler flags. Match the surrounding code.

Language & style

  • File-scoped namespaces; folder = namespace. src/KHost.Mobile.Infrastructure/Services/JsonFileSingerStore.cs → namespace KHost.Mobile.Infrastructure.Services;.

  • sealed on every concrete type — classes, records, exceptions. Nothing in this codebase is designed for inheritance.

  • sealed record (positional) for DTOs/value types; mutable class for JSON-persisted, editable entities — and say why in a comment. Compare:

    // src/KHost.Mobile.Abstractions/Clients/Metadata/TrackMetadata.cs — immutable lookup result
    public sealed record TrackMetadata(string? MatchedTitle, string? MatchedArtist, int? Year, string? Genre, string? ArtworkUrl);
    // src/KHost.Mobile.Abstractions/Models/SongListItem.cs — mutable, edited in place, persisted to disk
    /// Mutable class (not a record) because a rating can be edited after the fact from the history sheet.
    public sealed class Performance
    {
        public Guid Id { get; set; } = Guid.NewGuid();
        public DateTimeOffset Date { get; set; }
        ...
    }
  • Primary constructors for DI and exceptions; use the parameter by name, don't copy it to a field.

    // src/KHost.Mobile.Infrastructure/Services/AlbumArtCache.cs
    internal sealed class AlbumArtCache(IAppDataDirectory paths, IHttpClientFactory httpFactory, IAtomicFileWriter? writer = null, ILogger<AlbumArtCache>? logger = null) : IAlbumArtCache
    {
        private readonly string _dir = Path.Combine(paths.AppDataDirectory, "album-art");

    (A store that must pass its logger up to the JsonFileStore<T> base uses a regular constructor instead — a primary constructor can't feed a base(...) call and stay a bare parameter. JsonFileSingerStore is the example.)

  • Modern C#: collection expressions ([]), target-typed new(), switch expressions, pattern matching, expression-bodied members for genuine one-liners only.

  • var when the type is obvious from the right-hand side (var query = string.IsNullOrWhiteSpace(...) ? ... : ...;), not when it obscures the type.

  • Naming: private fields _camelCase; const and static readonly fields PascalCase.

Async

  • Every Task-returning method gets the Async suffix — including passthroughs declared without the async keyword, which the .editorconfig rule can't see. AsyncNamingConventionTests closes that gap by reflecting over every assembly, so a violation is a failing test rather than a review comment.

  • Library/network methods take a trailing CancellationToken cancellationToken = default and thread it through every await — see LrcLibLyricsClient.FetchAsync below.

  • ConfigureAwait(false) in KHost.Mobile.Clients and other non-UI/background code. Exception: the UI-thread JSON stores (JsonFile*Store in src/KHost.Mobile.Infrastructure/Services/) omit it — they rely on the Blazor sync context.

  • Network calls use the filter idiom, cancel-check first, then rethrow a domain exception:

    // src/KHost.Mobile.Clients/Lyrics/LrcLibLyricsClient.cs
    try
    {
        response = await httpClient.GetAsync(url, cancellationToken).ConfigureAwait(false);
    }
    catch (Exception ex) when (ex is HttpRequestException or TaskCanceledException)
    {
        // A genuine caller-cancel bubbles as OperationCanceledException; only a real failure is wrapped.
        cancellationToken.ThrowIfCancellationRequested();
        throw new LyricsLookupException("Couldn't reach the lyrics service. Check your connection and try again.", ex);
    }
  • Guard arguments with ArgumentNullException.ThrowIfNull(...) (e.g. JsonFileSingerStore.AddAsync).

Errors, logging & docs

  • Best-effort external ops swallow and degrade — link launch, update check, cover-art fallback. "No result found" returns null, it never throws; only a genuine network/HTTP failure throws a domain exception.

  • Logging lives in KHost.Mobile.Infrastructure, KHost.Mobile.UI and the KHost.Mobile head; KHost.Mobile.Clients has none (see External services), and KHost.Mobile.Abstractions takes no package reference at all. Inject ILogger<T> via the constructor. On the JSON stores, caches and the small Logic/Search helpers it's an optional, defaulted parameter with a NullLogger<T>.Instance fallback, so the integration tests can new them without a logging stack:

    // src/KHost.Mobile.Infrastructure/Services/AlbumArtCache.cs
    private readonly ILogger _log = logger ?? NullLogger<AlbumArtCache>.Instance;
    
    // A JsonFileStore<T> subclass resolves the fallback in its base(...) call instead;
    // the base exposes it as the `Log` property.
    public JsonFileSingerStore(IAppDataDirectory paths, ILogger<JsonFileSingerStore>? logger = null, IAtomicFileWriter? writer = null,
        ISingerFileNames? names = null)
        : base(logger ?? NullLogger<JsonFileSingerStore>.Instance, writer)

    Every small Infrastructure helper (RatingScorer, SurprisePicker, TimeFormatter, AppVersionParser, DateTimeInputConverter, SingerProfileCodec, SongLinkBuilder, KaraFunVenueUrlParser) takes the same optional ILogger<T>? even where it doesn't log yet — the constructor seam exists up front so adding a log line later never means touching every call site.

  • Structured messages, named placeholders — never string interpolation:

    _log.LogInformation("Seeded the default singer {SingerId}", active.Id);
    _log.LogWarning(ex, "Couldn't delete removed singer's file {Path}", path);
  • Levels: Debug for routine flow (store load/save, a lookup's start/outcome), Information for notable one-offs (an import count, every outbound HTTP request/response), Warning for a swallowed/degraded failure (corrupt file, failed cover download, a lookup that will retry).

  • LoggingHttpMessageHandler (src/KHost.Mobile.Infrastructure/Diagnostics/) is chained onto every typed HttpClient — the one seam that captures what the native platform HTTP stack actually sent/received on-device. KHost.Mobile.Clients does no logging itself, so Project.cs's AddKHostClients takes a configureHandler callback and MauiProgram.cs passes the one that attaches it:

    // src/KHost.Mobile/MauiProgram.cs
    builder.Services.AddKHostClients(userAgent, http => http.AddHttpMessageHandler<LoggingHttpMessageHandler>());
  • Providers + filters are #if DEBUG-gated in MauiProgram (Debug build → logcat via a custom KHostCue-tagged logger on Android; Release stays quiet).

  • XML docs: interfaces carry a substantive <summary>; implementations use /// <inheritdoc /> plus a <remarks> for operational notes (rate limits, backend quirks — see LrcLibLyricsClient above). Document positional record parameters and enum members. Inline // comments explain why, not what.

Comment discipline

Keep comments short and to the point — comment the trap a developer would hit (the API gotcha, the non-obvious constraint), not the investigation that found it. No reconstructed reasoning chains, no restating what the code already says. 1–2 lines is normal; 4 is a lot.

Good (explains a real trap, stops someone "fixing" it into a bug):

// A genuine caller-cancel bubbles as OperationCanceledException; only a real failure is wrapped.
cancellationToken.ThrowIfCancellationRequested();

Bad (restates the code, adds nothing a reader couldn't see):

// Check if the response is not found and return null
if (response.StatusCode == HttpStatusCode.NotFound)
    return null;

The named patterns

Each pattern has a fixed shape used throughout the codebase. Skeletons only — see the linked pages for the full picture.

Local store — IFooStore (in Abstractions) + JsonFileFooStore (internal sealed in Infrastructure), singleton via Project.cs's AddKHostInfrastructure(). The base class owns the gate, the cache, the crash-safe write and the corrupt-file quarantine; a subclass supplies only which file and which serializer context:

internal sealed class JsonFileFooStore : JsonFileStore<Foo>, IFooStore
{
    public JsonFileFooStore(IAppDataDirectory paths, ILogger<JsonFileFooStore>? logger = null, IAtomicFileWriter? writer = null)
        : base(logger ?? NullLogger<JsonFileFooStore>.Instance, writer)
        => _filePath = Path.Combine(paths.AppDataDirectory, "foos.json");

    protected override JsonTypeInfo<List<Foo>> TypeInfo => FooJsonContext.Default.ListFoo;
    protected override string Label => "Foos";
    protected override string PathFor(Guid? key) => _filePath;

    // public methods: await Gate.WaitAsync(); try { ... await LoadAsync() / await SaveAsync(x) ... }
    //                 finally { Gate.Release(); }
    // RaiseChanged() fires AFTER the gate is released, only when something actually changed.
}

A per-singer store also overrides CurrentKey (the active singer). If the in-memory shape isn't the stored list — only JsonFileLyricsCache, which is keyed — derive from the two-parameter JsonFileStore<TItem, TCache> and supply Project/Flatten. IFooStore is the only thing a consumer outside Infrastructure ever names; the store class itself is internal.

See Data storage.

Client backend (KHost.Mobile.Clients) — MAUI-free, internal sealed, injected HttpClient, parsing isolated in a static parser class:

internal sealed class LrcLibLyricsClient(HttpClient httpClient) : ILyricsLookup
{
    public async Task<LyricsResult?> FetchAsync(string title, string artist, CancellationToken cancellationToken = default)
    {
        // HTTP + error mapping here; LrcLibResponseParser.ParseFirst(json) does the "pure — no network" parsing.
    }
}

See External services.

Project.cs — every project with implementations to register exposes exactly one public static class Project holding a single DI extension method, so a consumer wires up the project's interfaces without ever naming a concrete type:

// src/KHost.Mobile.Infrastructure/Project.cs
public static class Project
{
    public static IServiceCollection AddKHostInfrastructure(this IServiceCollection services)
    {
        services.AddSingleton<ISongListStore>(...);
        services.AddSingleton<ITimeFormatter, TimeFormatter>();
        // ...every store, cache and former-static helper this project owns.
        return services;
    }
}

KHost.Mobile.Infrastructure.Project.AddKHostInfrastructure(), KHost.Mobile.Clients.Project.AddKHostClients(userAgent, configureHandler) and KHost.Mobile.UI.Project.AddKHostUI() are each called once from src/KHost.Mobile/MauiProgram.cs. The head still registers what only it can: IAppDataDirectory (needs the real FileSystem.AppDataDirectory), the platform-conditional IQrScanner, the Maui* adapters, and the named "album-art" HttpClient.

See Architecture → Service inventory.

Blazor component — markup in the .razor, C# in a sibling .razor.cs partial, @inject, sheets wrap Sheet.razor, JS interop bound once behind a _bound flag in OnAfterRenderAsync. An @code block is a rule violation:

@* SingerEditSheet.razor *@
@inject ISingerStore Store
// SingerEditSheet.razor.cs — @implements moves here; @inherits must stay in the markup.
public sealed partial class SingerEditSheet
{
    private bool _bound;   // JS interop registered once, un-set on close/dispose

    protected override async Task OnAfterRenderAsync(bool firstRender)
    {
        if (Open && !_bound)
        {
            await JS.InvokeVoidAsync("khSheet.register", ...);
            _bound = true;
        }
    }
}

A .razor.cs inherits none of the markup's @using; the _Imports.razor set is mirrored as <Using Include=…> in KHost.Mobile.UI.csproj, so a new shared namespace goes in both. Formatting also bites harder here — IDE0055 plus TreatWarningsAsErrors turns indentation that an @code block tolerated into a build error, fixable with dotnet format whitespace <proj> --include <file>.

See UI components.

Housekeeping / PR checklist

  • Both test suites must pass before any commit or push — never commit with a failing or unrun suite:
    dotnet test tests/KHost.Mobile.UnitTests/KHost.Mobile.UnitTests.csproj "-p:BaseOutputPath=./obj/_build"
    dotnet test tests/KHost.Mobile.IntegrationTests/KHost.Mobile.IntegrationTests.csproj "-p:BaseOutputPath=./obj/_build"
    See Building & testing for what each suite covers.
  • Don't commit or push unless explicitly asked — applies to AI agents working in the repo and to contributors' own workflow alike.
  • Keep the docs in sync with the app. README.md is product-facing — update its feature list (and screenshot grid where relevant) whenever a user-facing feature changes. DEVELOPMENT.md is developer-facing — build/test commands and Design notes (rationale for a new reusable component, a storage/serving decision, a platform workaround) belong there, not in the README.
  • /research/ is gitignored and must never be committed — local planning/research notes and scratch data only.
  • Secrets via user-secrets/config — never hard-coded or committed.

License note

KHost Cue is licensed under PolyForm Shield License 1.0.0. In short: you may use, modify, and self-host it for any purpose, including commercial use, but you may not use it to provide a competing product or service (a hosted/managed offering, or a rebranded redistribution) without a separate license. This applies to contributions too — by opening a PR you're contributing under the same terms the repo is licensed under. Third-party components bundled in the app (all MIT/Apache-2.0) are listed in THIRD-PARTY-NOTICES.md.

See also

  • Architecture — project layout, the store/client-backend/component patterns in context.
  • Building & testing — build commands, device deploy, the two test suites.

Clone this wiki locally