What is the most basic rule when writing code?

Focus on the "what", not the "how"

November 30 · 4 mins read

Do you like simple rules?

Simple rules

I like simple, but/and/yet all-encompassing rules (partly because I’m not very good at remembering lots of things :smile: ):

You can start anywhere.

“If it sounds good, it is good.” — Duke Ellington

“Everything should be as simple as possible, but not simpler.” — Albert Einstein

“The only way to go fast is to go well” — Uncle Bob Martin

“First make it work. Then make it right. Then make it fast” — Kent Beck

Another simple rule

I found another simple rule!

In the introduction videos of the Nand2Tetris Part 1 course, Noam Nisan and Shimon Schocken calls it “The Main Secret of Computer Science”:

The Main Secret of Computer Science

Don’t worry about the “how”, only about the “what”.

In other words, don’t worry about the “implementation”, only about the “abstraction”.

Steve Freeman and Nat Pryce, the authors of the GOOS book, also said something about it (p. 252):

All code should emphasize “what” it does over “how”, including test code.

Jonathan Boccara declared it as “the principle to rule them all”:.

…respecting levels of abstraction… , [focusing on] what a particular piece of code intends to do as opposed to how it is implemented… is the one principle to rule them all because it automatically applies all the best practices… When you follow it, you’ll find yourself naturally writing code with a high-quality design.

“what” over “how”

Simple, yet all-encompassing rule!

Focus on the “what”, not the “how”

Of course we might still be the one to write the “how” part. But if we focus on the “what” part when writing code, we will end up with code that is, what they call, “intention revealing” code.

“what does this code do?…”

“ahhh!”

And “intention revealing” code is easy to read! Remember that we, and our coleagues (we should think about our coleagues also :smile:) spend more time reading code than writing code!

I should put this in mind always then…

“what” over “how”

“what” over “how”

“what” over “how”

“what” over “how”

:smile:

“what does this button do?”


An example:

When computing the sum of a list of numbers, it is easier to read this

sum = listOfNumbers.computeSum();

or this

sum = computeSumOf(listOfNumbers);

than this

sum = 0 
index = 0
while index < listOfNumbers.length
    n = listOfNumbers[index]
    sum += n
    index++

The first two code snippets focuses on what the code does instead of how it does it.

Buy Me A Coffee