Category: Uncategorized

  • Zen and the Art of Code Maintenance

    There are 3 questions that I think it’s useful to actually ask to your code. Frankly, they’re useful to ask your self, too.

    I cover these in my React Alicante 2025 talk:

    Despite my nerves at the start, I’m glad I managed to make it clear how important it is to use types to prevent your code from leaking away valuable information.

    Types are a tool for describing your reality; the ontological space in which your code exists. This is usually domain-specific, but even if it’s pretty generic (the distinction between Admin and User, for example), it should be clear when these are two independent things in your digital reality.

    Do real things have optional properties?

    I basically always watch out for optional properties in types. Often a property is not truly optional — we just haven’t made clear the conditions under which it always holds true.

    For example:

    export type User_Not_Zen = {
    name: string;
    email: string;
    age: number;
    role?: "admin"; // optional - but is it really? 
    };

    This type is not ontologically accurate if your admin users always have the property role: admin, and your other users never have that property.

    Compare the above type with the following more accurate (thus more Zen) types:

    type User = {
      name: string;
      email: string;
      age: number;
    };
    
    /** In reality, admin users always have a role. So this is the true type. */
    type Admin = {
      name: string;
      email: string;
      age: number;
      role: "admin";
    };

    When we go to add an if block with the condition (role === admin) then we (and our IDE) can actually see that we are deadling with one type of thing (admin user), and not another (user).

    For parsimony, we may wish to extend User to create the Admin type (below) — but only if they otherwise always covary:

    export type AdminUser = User & {
      role: "admin";
    };

    If they always covary (i.e. when User changes, Admin also changes) then we know these are properly codependent. Interdependency is also information that can be expressed in the code, through proper use of type extension.

    So why is this more Zen? Zen speech is truthful. It expresses understanding, aids understanding, and therefore reduces suffering.