This is a set of demo code guidelines for a Typescript project. They are used to exemplify how I go about writing code guidelines.

While Typescript is only rarely mentioned, each language have weaknesses and strengths. Code guidelines are a set of rules that in particular mitigates the weaknesses of a language.

Code Locality

Context: The entire code base

Advice: Prefer to keep code close to where it is used. Eg, when writing a utility function that turns an enum "FINANCE" into the string "Finance" refrain from putting that into a utility code. Instead put it in the same file where it is used.

Some qualification of this rule:

  1. If the file is big, create a utility.ts (or _utility.ts in the page hierarchy) and save it there.
  2. If the semantically equivalent function is need somewhere else in the code, find a place that is between these place.

    • If this is in two apps, put it in a package
    • If that is on two pages, put it in the junction of the hierarchy
    • etc.

Occam's Razor for Code

Advice: When there are two competing solutions that solve the same problem. Choose the simplest one.

Prefer Records over Lists for Local Data Structures

Context: Local and complex data structures used for rich user interaction.

Anti-context: Database models, API data structures.

Advice: Prefers using sub objects indexed using a intrinsic ID of each elements.

[  { id: "abc",    elements: [      { id: "123",        field: "value" }    ]  }];

vs.

{  "abc": {    id: "abc",    elements: {      "123": {        id: "123",        field: "value"      }    }  }}

The former requires complex iteration if we want to update the value in a type safe manner while the latter requires v["abc"].elements["123"].field = "New Value".

Extra notes:

  • If we need a list, we can always Object.values(v) and we are back!
  • If there are no intrinsic ID, generate one using UUIDv4

Prefer Mutations to Not Return the Entity in Question

Context: API development (GraphQL here)

Advice: Prefer that API that POST or Mutate data does not return the entity in question.

Background: Systems at scale takes time to propagate change. This is usually not long time but enough that we don't want to wait for it being written to the database before we can respond in the API.