Clean code functions
Clean code functions
Small!!
The first rule of functions is that they should be small.
The second rule of functions is that they should be
smaller than that.
FUNCTIONS SHOULD
DO ONE THING
DO IT WELL.
DO IT ONLY.
Guess the meaning of the following function
in 2 Min
Long Method
Long Method –continued
Long Method –continued
Refactored Versions
Version 1
Version 2
Sections within Functions
If you have a function divided in sections
like declarations, initialization etc, it's a obvious symptom of
the function is doing more than one thing.
Abstract 2
Abstract 1
Abstract 3
The "Single Level of Abstraction"
Principle
The "Single Level of Abstraction"
Principle
One Level of Abstraction per
Function
The Stepdown Rule
Reading Code from Top to Bottom
• We want the code to read like a top-down narrative
• We want every function to be followed by those at the
next level of abstraction so that we can read the program,
descending one level of abstraction at a time as we read
down the list of functions.
• we want to be able to read the program as though it were
a set of TO paragraphs, each of which is describing the
current level of abstraction and referencing subsequent
TO paragraphs at the next level down.
The Stepdown Rule
Reading Code from Top to Bottom
• To include the setups and teardowns, we include setups, then we include the
test page content, and then we include the teardowns.
• To include the setups, we include the suite setup if this is a suite, then
we include the regular setup.
These two uses are what readers expect when they see a
function. You should choose names that make the
distinction clear, and always use the two forms in a
consistent context.
Command Query Separation
Functions should either:
do something
or answer something,
but not both.
if (attributeExists("username")) {
setAttribute("username", "unclebob");
...
}
Flag Arguments
• Flag arguments are ugly.
• extract a new class like FieldWriter that takes the outputStream in its
constructor and has a write method.
Triads
Functions that take three arguments are significantly harder
to understand than dyads. The issues of ordering, pausing,
and ignoring are more than doubled.
vs
if (deletePage(page) == E_OK)