Uncle Bob’s Clean Code – Chapter 5: Formatting.

Uncle Bob argues that code formatting is about communication, and communication is the professional developer’s first priority. You might think “getting it working” is job one, but a mess left behind will eventually make the code unworkable for the next person.

In this chapter, he breaks formatting into two dimensions: Vertical and Horizontal.


1. Vertical Formatting (The Newspaper Metaphor)

Think of a source file like a newspaper article:

  • The Headline: The name of the file/class should tell you what it’s about.

  • The Summary: The top-level functions provide the high-level concepts.

  • The Details: As you move down, the level of abstraction decreases until you hit the lowest-level details at the bottom.

Key Rules:

  • Vertical Openness: Use blank lines to separate distinct thoughts (like variables from functions, or one logic block from another).

  • Vertical Density: Lines of code that are tightly related should appear close together.

  • Variable Declarations: Should be as close to their usage as possible.

2. Horizontal Formatting

This is about how wide your lines are. Uncle Bob’s rule of thumb is a limit of 100–120 characters. If you have to scroll right, the “flow” of reading is broken.

  • Horizontal Openness and Density: Use spaces to associate things that are strongly related and disassociate things that are weakly related.

    • result = (a * b) + c (Spaces around the assignment and operators clarify the order of operations).


Interactive Kotlin Comparison

Let’s look at how formatting changes the readability of a class.

The “Cramped” Version:

class ReportGenerator(val data:List<String>){
    private var title:String=""
    fun generate(){title=data[0]
        if(data.isNotEmpty()){
            renderHeader()
            renderBody()
        }
    }
    private fun renderHeader(){println("---$title---")}
    private fun renderBody(){data.drop(1).forEach{println(it)}}
}

The “Clean” Version (Chapter 5 Style):

class ReportGenerator(val data: List<String>) {

    private var title: String = ""

    fun generate() {
        title = data[0]

        if (data.isNotEmpty()) {
            renderHeader()
            renderBody()
        }
    }

    private fun renderHeader() {
        println("--- $title ---")
    }

    private fun renderBody() {
        data.drop(1).forEach { line -> 
            println(line) 
        }
    }
}

Reflection Point: The “Team Standard”

Uncle Bob admits that every team should have its own set of formatting rules, and once decided, every member must follow them. The consistency of the team is more important than your personal preference.

A quick question for you: In Kotlin, we often use trailing lambdas or one-line functions (e.g., fun sum(a: Int, b: Int) = a + b).

From a Clean Code perspective, do you think these one-liners help or hurt the “Newspaper Metaphor” of reading code top-to-bottom?

Loading more content...