For cleaner code, write ugly code

We want to write only clean code, right?

Wrong. I want to write eventually-clean code. It starts exploring a space, and then I refine it to be cleaner and more suited to purpose. Usually, that purpose becomes clearer through writing, reading, and using the code.

That process of refining or tidying up can feel tedious, compared to implementing more features. It can be tempting to leave off error handling. I have a strategy for that: meaningful ugliness.

When I’m prototyping, I make the code so ugly that it will be satisfying to clean up. No attempt at appearing clean. I put a bunch of casts, bad casing maybe, random names instead of plausible-but-inaccurate ones. No null-checking.

for (const gerald of allKindsOfStuff.fingerprints) {
    (gerald as any).displayName =
         allKindsOfStuff.feature.convertinate(gerald.name);            }

(exaggerated to show detail)

When cleaning, I often start by making the code uglier. To move from an OO style toward functional, start by replacing all global or class-level variables with parameters. Twelve parameters on a function?! That’s hideous! Yes. Yes. Let ogres look like ogres.

This lets me feel productive when I come back to the code and clean it up. Later, I know more about what this code is for, what might be null and what won’t, what dependencies I can eliminate and which are meaningful. This is a better time to clean.

Disguising rough code in socially-acceptable clothing prevents cleaning. Appearance-of-good is the enemy of better.

The next architecture book you must read

Today, another tweet about “how can I write the cleanest, best architected code?” gets piles of book references in response.

Yes, we want to be good at writing code. We want to write the best code. The best code for what? “Writing code” is an abstraction, like a transitive verb without an object. I can’t just “write code,” I must “write code to….”

The work is software development is not typing, it is making decisions. To make those decisions, we have to understand the details of code and technology, yes. We also have to understand the context and purpose, what we are writing the code to do.

My advice for “What should I read in order to write better code?” is usually, a book or magazine or internal memos about the business. Better is having conversations about the business with the experts inside your company, and to do that well, you need the vocabulary.

We need both the specific technical understanding and the business understanding. It’s so much easier to push for technical understanding. Because the business understanding is specific to each context. I can’t make a wide-audience tweet recommending a book, you have to find that closer-in.

Supplement Twitter with kitchen conversations or internal Slack channels that give you a broader perspective on the purpose of your work in the specific context you work in.

Zooming in and zooming out