Readable Code
When I write code these days, I try to make it read like a book. When you open a file, it tells you, at the highest level of abstraction, what it does. The methods are small, specific and clear.
I think of this like words in a sentence or sentences in a story. When you see a word you have not seen before, what it means can often be inferred by the context it is in. To better understand it, you can drill down into the definition of the word, even to its etymology if you wish.
This concept can be applied to code. Each function has a definition that is made up of more functions, just like a word's definition is made up of more words with their own definitions. At any given level you have nice clean "sentences" describing what is being expressed.
The way to achieve this in code is by following 3 simple rules:
- A function's calls are always above its definition in the file.
- Function definitions are documented if necessary (e.g., if their names are insufficient to fully describe what they are doing or need elaboration). I like to err on the side of documentation.
- Functions have no more than 5 to 10 lines, so any behavior pushing this boundary gets refactored out into a helper function. This is not a hard rule and I fall back to "does the function do one thing?"
I hope the picture above is a good example of this developing practice of mine. I'd love to hear thoughts on this coding convention and the sample above.
I have recently adopted a similar strategy. I have begun commenting on function of each block of code. Great minds thinking alike.
I like this a lot! I wish more people focused on writing clear code that clearly communicates intent instead of implying intent as a side effect of the implementation. Ideally your abstractions create a tree all the way down that are small enough chunks that the cognitive 'buffer' doesn't overflow i.e. you can keep it all in short term memory at once at each layer. One concern/note with your example is that some of the function signatures don't hide any complexity -- the functions have no depth. This is a trigger for me since good abstractions hide complexity and have deep interfaces :) For example, maybe it is better to add a single line comment then add a layer of indirection. Then again, the comment might then need to be copied around everywhere so a function might be better even if it hides no complexity. Or maybe you could argue the indirection and shallowness is justified because it reveals intent more clearly. Just something to keep in mind
This is a habit that I am focusing on integrating now, while I am a student. I still fall short when I approach crunch times, but I believe writing code with a high level of readability is key to good programming.