Wednesday, May 17, 2017

Clean Code by Robert C. Martin

Subtitle: A handbook of Agile Software Craftsmanship. First published in 2008.

One of the core programming books. All code examples are in Java.


Should do one thing only.

One level of abstraction per function: making the code read like a top-down list of TO instructions is an effective technique to achieve that (the Stepdown Rule):

For example, for a non-configurable dashboard I could write:

"To create a Home Dashboard, get the System Status traffic light, Devices/Users vertical bar chart, and Workflow Pipeline horizontal bar chart."

The ideal number of arguments for a function is zero.

niladic - 0 arguments
monadic - 1 (monads)
dyadic - 2 (dyads)
triadic - 3 (triads)
polyadic - 3+ do not use

Why? More arguments = harder to read, harder to test: lots of combinations.
Flat, output arguments, and flags - ugly, confusing, terrible.
If your function needs to change the state of something, let it be the state of its owning object.

Temporal coupling - when a function can only be called at certain times.

Not having boolean arguments: but a boolean argument could prevent duplication: but the duplication can be solved by creating another function.

Because a function should do only one thing and a function with try/catch is doing error handling, it should only do error handling, i.e. in the try section it should just call one subfunction and in the catch it should handle all possible exceptions.

My argument against exceptions: they are like GOTO of old: arbitrarily move execution somewhere else in code. Also, handling exceptions in separate functions, as recommended, leads to abstraction leakage: the exception may be from many layers down.

My argument against small functions with only one or two arguments: class count and stack depth explosion: lots more classes, lots more layers.

My argument against "comments are always failures": comments are necessary when explaining the path taken: why did we code it this way. The author clarifies that a few pages later: intent comments are good.

Do not return null.

Side effects are evil.

Funny parts:
G25: Replace magic numbers with named constants, except for well known numbers like 5280: "the number 5280 is so very well known and so unique a constant that readers would recognize it even if it stood alone on a page with no context surrounding it." 

Really? If you belong to the 95% of the world population using the metric system (everyone, except the US, Myanmar, and Liberia), 5280 is a magic number to you. It is the number of feet in a mile.

G31: hidden temporal coupling - when functions must be executed in order, but they don't use arguments/return values to show it. Have fun debugging that. :-)

No comments:

Post a Comment