Koleman Nix

Writing better code than Claude

I find small, concrete examples really valuable when it comes to talking about ‘code quality’.

Let’s get to it. Today I was tasked with fixing a bug in one of our internal expression languages. RecordTypes have fields. Fields have names and types. Some fields are arrays of ids of other records. And these other records can of course themselves have these ‘reference’ type fields. Cycles are allowed. When we initialize the RecordType objects, we do so only 1-layer deep, to avoid an infinite recursion. The result is that you can find a RecordType whose fields lie: they are an empty sequence, even though that record has fields. The bug is really in this shallow initialization; where we should be sharing the one true RecordType object for each type. (But we didn’t have the time or the risk tolerance to touch that code on this particular day; though we should have! More on that later)

When the source code that we are compiling wants to access a field of a record, this resolveField function is called. All field accesses go through this function. This is a great thing; we’re starting from a properly compressed base. Compressed means that this single idea, ‘get field of record type by name’, is expressed in one place in the code. (This is just DRY, properly understood)

I decided to have AI triage. AI is great at reading code, especially hermetically sealed code like a tiny programming language. This was my prompt:

In [expression language], there is a bug report that a field of type ‘record’ can’t be fully used transitively. So like, a.b.c, where b is a field of a, and c is a field of b, fails to access b’s fields. Try to make a test that reproduces first, then fix it if its actually broken

The slot machine pull was rewarded, and I got this out, along with a really verbose new (but sound) failing test case. This code comes from the typechecking, or semantic, layer:

Original

private def resolveField(
  recordType: RecordType, fieldName: String, span: Span
): PclResult[(index: Int, ty: Type)] = boundary {
  recordType.index(fieldName) match {
    case Left(msg) => break(errorAt(span, msg))
    case Right(i) =>
      val _                              = depFields.add((dataset = recordType.name, field = fieldName))
      val result: (index: Int, ty: Type) = (index = i, ty = recordType.fields(i).ty)
      result
  }
}

The problem is that we’ve been handed a RecordType who has no fields! One of the shallow ones. A natural fix: Claude fix 1

private def resolveField(
  recordType: RecordType, fieldName: String, span: Span
): PclResult[(index: Int, ty: Type)] = boundary {
  // A record type reached through a reference field may be a stub with incomplete fields
  // (reference types are only filled in one level deep), so resolve by name against the
  // environment — the same way the evaluator resolves references — before indexing.
  val resolved = env.datasetType(recordType.name).getOrElse(recordType)
  resolved.index(fieldName) match {
    ...
  }
}

Claude uses the env to resolve the real record type by name. This ‘works’, and the comment is true. But I’m going to argue that it is bad. First of all, the fix is too local. This is a hallmark LLM mistake; a local workaround is always preferred over a root-cause fix that requires changing code in another function. My fix, too, was too local, because I didn’t have time to do it properly, but it was a bit less local: I did end up asking local callers to change.

The second issue that it introduces a bad codepath that we should never take: when the name lookup misses, Claude falls back to the record type it was given: .getOrElse(recordType. The problem is that this lookup should never miss, and if it does, we’re going to be in a bad state. This function already has the ability to return an error. That miss should absolutely be an error case, but Claude is often too timid to make such semantic claims, preferring to silently tiptoe its way around problems; seeking the green test over all else.

Issue two is revealed once we remove this fallback: the true input to this function resolveField is now the field name, not the record type. The name is all we use; and its used to index into the env’s dataset repository. Once you realize this, everything makes sense. We completely eradicate from this function the existence of these shallow record types; it’s now a completely irrelevant thing since our job is simply to take a record name and find its type.

So here’s my edit: accepting just the name, since it’s the ’true’ input, erasing the silent failure case. We only update 2 callers, and those callsites become more honest, and we use the variable name coupled with our new signature to explain how the name relates to the record type (canonical). I don’t wax poetic in a comment about how another part of the system doesn’t always fill in all record types; I just do a simpler correct thing, require callers to give me a less misleading input, and render that information irrelevant trivia

private def resolveField(
  recordTypeName: String, fieldName: String, span: Span
): PclResult[(index: Int, ty: Type)] = boundary {
  val canonicalRecordType = env.datasetType.get(recordTypeName)
  canonicalRecordType match {
    case None => break(errorAt(span, s"record type not found: ${recordTypeName}"))
    case Some(recordType) =>
      recordType.index(fieldName) match {
        ...
      }
  }
}

Almost done; and I can’t remember why but there was another turn and Claude ruined a the good thing we had: it reintroduced the comment, with a now irrelevant fact about the shallow record types: irrelevant since we only ask our caller for a field name now anyway, and also removed my local variable whose name carried a semantic job and moved that information into the comment as well (“canonical record type”)

/** Field lookup goes through the environment's canonical record type: a record type reached through a reference field may be a stub with incomplete fields
* (reference types are only filled in one level deep), so resolve by name — the same way the evaluator resolves references.
*/
private def resolveField(
  recordTypeName: String, fieldName: String, span: Span
): PclResult[(index: Int, ty: Type)] = boundary {
  env.datasetType(recordTypeName) match {
    case None => break(errorAt(span, s"record type not found: ${recordTypeName}"))
    case Some(recordType) =>
      recordType.index(fieldName) match {
        ...
      }
  }
}

My final version

private def resolveField(
  recordTypeName: String, fieldName: String, span: Span
): PclResult[(index: Int, ty: Type)] = boundary {
  val canonicalRecordType = env.datasetType(recordTypeName)
  canonicalRecordType match {
    case None => break(errorAt(span, s"record type not found: ${recordTypeName}"))
    case Some(recordType) =>
      recordType.index(fieldName) match {
        ...
      }
  }

The ‘deep’ fix, as I alluded to, is to hoist the spirit of our change even higher up the chain. These shallow and faulty RecordType instances who contain no fields are just lies. We avoided working with them in our function here by asking for a name, but an even better change would be to adjust every current holder of a shallow RecordType to instead just hold an entirely different type RecordTypeByName(name: String). Note that by asking our callers to pluck out only the name from their shallow RecordTypes and give it to us, we are almost approximating that solution; we are encouraging them to, unknowingly, provide only the ‘good’ part of their RecordType handle, the name.

Because cycles between record types are possible, naming them by reference (name) to stop the recursion is a nice solution. It’s interesting to note that sometimes once you find the right solution, it wants to be applied more broadly than you are willing to go in that session. There’s a balance between being careful and making things right, but I’d argue the correct action is almost always to percolate the change as far as it deserves to go. You’re already changing this code, and thus will have to test it and you have some risk of breaking it, why not strike while the iron is hot and finish the job; who knows, in doing so, you may find more serious problems right then and there!

TLDR: This is a tiny change. Changing one parameter from an object type to a String that lived inside it. But from a semantic perspective, we’ve eliminated an entire class of problems and changed the meaning of the function for the better. This change exists within a more general family of ’tightening your input params’ which can consistently yield similar wins. Never make your caller jump to implementation to ask ‘which fields of this object does this function actually need?’