Contents
- Meaningful names
- Functions/Methods
Meaningful names
- use intention-revealing names
- use pronouncable names
- The length of a name should correspond to the size of its scope.
- Class names should be noun and not verbs. (avoid words like Manager, Processor, Info, Data)
- Methods names should be verb . Accessors (get), Mutators (set) and Predicates (is) have such prefixes.
Choose one word for a concept and stick with it. e,g Choose one between fetch, retrieve, get - Describe the thing that you are visualising
- The author is responsible for making himself clear.
Functions/Methods
- functions should do one thing and do it well
- they should be SMALL
- they should be SMALLER than that
- all your functions together can tell a story
- the blocks following if else , while statement can be just be one line, preferably a function call, where the function name provides nice description
- the indent level of function should never be greater than one or two
- hence complex nested if else should be avoided
- the function should be at particular level of abstraction
- one function should not have multiple levels
- functions should be placed one below another like a story such that it is easy reading code from top to bottom like a newspaper article.
Function arguments
- the ideal number of arguments to a function should be zero ,
- one is acceptable, when we ask question
fileExists(filename)
or operatingopenFile(filename)
. Flag arguments: Passing a boolean to a function is very poor practice. - two arguments are tolerable,
createPoint(0, 0)
is reasonable
three should be avoided and four should have specific reason
Switch statement
- its hard to make a small switch statement
- switch statement can be tolerated if they appear only once and are used to create polymorphic objects
Command query separation
- Function should either do something or answer something but not both.
- It should either change the state of object or return some information about it.
Exception Handling
- Function should do one thing and error handling is one thing.
- if the keyword
try
exists in a function, it should be the very first word in the function and that there should be nothing after thecatch/finally
blocks.
How to write such perfect functions?
- Make it work first no matter with good or bad code.
- Write unit test covering success and failure cases.
- Now,
- refine that code,
- split out functions,
- eliminate duplication,
- shrink the methods and reorder them