1 of 219

Writing Cleaner Code

Neal Enssle

http://neal.enssle.me

April 2017

Last updated: November 2019

2 of 219

3 of 219

What is “clean” code?

4 of 219

What is “clean” code?

  • What makes code “clean”?

5 of 219

What is “clean” code?

  • What makes code “clean”?
  • Why is “clean” code better?

6 of 219

What is “clean” code?

  • What makes code “clean”?
  • Why is “clean” code better?
  • Can we measure it?

7 of 219

What is “clean” code?

  • What makes code “clean”?
  • Why is “clean” code better?
  • Can we measure it?
  • Can we find a common vocabulary to talk about what makes code good or bad?

8 of 219

But first…��What is programming?

9 of 219

?

10 of 219

11 of 219

Programming is creative

12 of 219

13 of 219

Programming demands precision

14 of 219

Programming is collaborative

15 of 219

Programming is communication

16 of 219

“Always code as if the person who ends up maintaining your code is a violent psychopath who knows where you live.”

- Martin Golding

17 of 219

Ch. 1: Clean Code

18 of 219

What is “clean” code?

19 of 219

  • What are the rules?

What is “clean” code?

20 of 219

  • What are the rules?
  • Are there common standards?

What is “clean” code?

21 of 219

  • What are the rules?
  • Are there common standards?
  • Is it entirely subjective?

What is “clean” code?

22 of 219

  • What are the rules?
  • Are there common standards?
  • Is it entirely subjective?
  • Can we measure it?

What is “clean” code?

23 of 219

  • What are the rules?
  • Are there common standards?
  • Is it entirely subjective?
  • Can we measure it?
  • Can we teach it?

What is “clean” code?

24 of 219

25 of 219

  1. Use short sentences.
  2. Use short first paragraphs.
  3. Use vigorous English.
  4. Be positive, not negative.

Hemingway’s Rules

26 of 219

…and when to break them

Rules...

27 of 219

28 of 219

The rules are always�rules of thumb

29 of 219

30 of 219

Craftsmanship

Robert C. Martin, Clean Code, p. xxv

Which door represents your code? �Which door represents your team or your company?�

How can we make sure we wind up

behind the right door when the going gets tough?

�The answer is: craftsmanship.”

31 of 219

Bad code exists

“Indeed, we have a name for it. We call it wading. We wade through bad code. We slog through a morass of tangled brambles and hidden pitfalls. We struggle to find our way, hoping for some hint, some clue, of what is going on; but all we see is more and more senseless code.”

Robert C. Martin, Clean Code, p. 3

32 of 219

Why does bad code exist?

“We have lots of explanations for [bad code].

We complain that the requirements changed in ways that thwart the original design. We bemoan the schedules that were too tight to do things right. We blather about stupid managers and intolerant customers and useless marketing types and telephone sanitizers.

But the fault, dear Dilbert, is not in our stars, but in ourselves. We are unprofessional.”

Robert C. Martin, Clean Code, p. 5

33 of 219

Good code is worth fighting for

“But wait!” you say. “If I don’t do what my manager says, I’ll be fired.” Probably not.

Most managers want the truth, even when they don’t act like it. Most managers want good code, even when they are obsessing about the schedule.

They may defend the schedule and requirements with passion; but that’s their job. It’s your job to defend the code with equal passion.

Robert C. Martin, Clean Code, p. 6

34 of 219

How to write clean code?

“Writing clean code requires the disciplined use of a myriad little techniques applied through a painstakingly acquired sense of ‘cleanliness.’

This ‘code-sense’ is the key. Some of us are born with it. Some of us have to fight to acquire it.”

Robert C. Martin, Clean Code, p. 7

35 of 219

Schools of thought

36 of 219

What is clean code?

Robert C. Martin, Clean Code, p. 7

Bjarne Stroustrup, Inventor of C++

“I like my code to be elegant and efficient. The logic should be straightforward to make it hard for bugs to hide, the dependencies minimal to ease maintenance, error handling complete according to an articulated strategy, and performance close to optimal so as not to tempt people to make the code messy with unprincipled optimizations.

Clean code does one thing well.

37 of 219

What is clean code?

Robert C. Martin, Clean Code, p. 8

Grady Booch, Object Oriented Analysis and Design with Applications

“Clean code is simple and direct. Clean code reads like well-written prose. Clean code never obscures the designer’s intent but rather is full of crisp abstractions and straightforward lines of control.”

38 of 219

What is clean code?

Robert C. Martin, Clean Code, p. 10

Michael Feathers, author of Working

Effectively with Legacy Code

“Clean code always looks like it was written by someone who cares.

There is nothing obvious that you can do to make it better…. If you try to imagine improvements, you’re led back to where you are, sitting in appreciation of the code someone left for you — code left by someone who cares deeply about the craft.”

39 of 219

What is clean code?

Robert C. Martin, Clean Code, p. 11

Ward Cunningham, inventor of Wiki, co-inventor of eXtreme Programming, motive force behind Design Patterns

“You know you are working on clean code when each routine you read turns out to be pretty much

what you expected.”

40 of 219

What is clean code?

Robert C. Martin, Clean Code, p. 10

Ron Jeffries, The Nature of Software Development

“I begin…with [Kent] Beck’s rules of simple code. In priority order, simple code:

  • Runs all the tests;
  • Contains no duplication;
  • Expresses all the design ideas that are in the system;
  • Minimizes the number of entities such as classes, methods, functions, and the like.”

41 of 219

Schools of thought

Robert C. Martin, Clean Code, p. 12, 15

“None of these different schools is absolutely right. Indeed, many of the recommendations in this book are controversial. You will probably not agree with all of them. You might violently disagree with some of them. That’s fine…”

“Books on art don’t promise to make you an artist. All they can do is give you some of the tools, techniques, and thought processes that other artists have used.”

42 of 219

Two core principles…

43 of 219

1. Write for your readers

Robert C. Martin, Clean Code, p. 14

“The ratio of time spent reading vs. writing

is well over 10:1...

Because this ratio is so high, we want the reading of code to be easy, even if it makes the writing harder. Of course there's no way to write code without reading it, so making it easy to read actually makes it easier to write.”

44 of 219

2. Care about your code

Robert C. Martin, Clean Code, p. 14

If we all checked-in our code a little cleaner than when we checked it out, the code simply could not rot.

The cleanup doesn’t have to be something big. Change one variable name for the better, break up one function that’s a little too large, eliminate one small bit of duplication, clean up one composite if statement.”

45 of 219

Ch. 2: Meaningful Names

46 of 219

Use intention-revealing names

Robert C. Martin, Clean Code, p. 18

“The name of a variable, function, or class, should answer all the big questions. It should tell you why it exists, what it does, and how it is used.

If a name requires a comment, then the name does not reveal its intent.”

47 of 219

Use intention-revealing names

Robert C. Martin, Clean Code, p. 18

48 of 219

Use intention-revealing names

Robert C. Martin, Clean Code, p. 18

49 of 219

Use intention-revealing names

Robert C. Martin, Clean Code, p. 18

50 of 219

Use intention-revealing names

Robert C. Martin, Clean Code, p. 18

51 of 219

Avoid disinformation

Robert C. Martin, Clean Code, p. 19

“Programmers must avoid leaving false clues that obscure the meaning of code.”

  • Avoid entrenched meanings: hp, aix, mac, ie, ff.
  • Don’t refer to a group of accounts as an “AccountList” unless it’s actually a List.
  • Avoid small variances in names:
  • XYZControllerForEfficientHandlingOfStrings
  • XYZControllerForEfficientStorageOfStrings
  • Inconsistent or incorrect spelling is disinformation: HTTP_referer
  • Avoid ambiguous names: l, 1, 0, O, etc.

52 of 219

Make meaningful distinctions

Robert C. Martin, Clean Code, p. 20

  • Avoid number-series naming: a1, a2…; i, j, k, l, m…
  • Avoid low-value “noise” words: Product, then ProductInfo, ProductData.
  • Avoid redundant type-based naming: “myVariable”, “productsTable”, “nameString”, “customerObject”, “ordersArray”
  • Make names meaningful and distinct, unlike these examples:
    • getActiveAccount()
    • getActiveAccounts()
    • getActiveAccountInfo()

Write for humans, not just the compiler

53 of 219

More rules of thumb for names

  • Avoid single-letter names.
  • Use pronounceable names.
  • Use searchable names.
  • Avoid encodings and Hungarian notation (e.g. iAccountNum, phoneString).
  • Prefer the names used by the business or customer.
  • A long, descriptive name is better than a comment.

Robert C. Martin, Clean Code, p. 21-30

54 of 219

More rules of thumb for names

  • Class names should have nouns (e.g. Customer).
  • Method/function names should have verbs (e.g. postPayment, deletePage).
  • Pick one word per concept (e.g. get vs. fetch vs. retrieve vs find).
  • Don’t be cute! (e.g. HolyHandGrenade, FireHoseOfData, ThisIsADangerousVariable, Stimpy, KyloRules, DestroyerOfWorlds).
  • Don’t be afraid to rename!

Robert C. Martin, Clean Code, p. 21-30

55 of 219

Don’t be afraid to rename! ��Don’t be afraid to argue �about names!

56 of 219

Ch. 3: Functions

57 of 219

Try to understand the

following function...

58 of 219

59 of 219

60 of 219

Robert C. Martin, Clean Code, p. 33

Bad function

“Do you understand the function after

three minutes of study?

Probably not.

There’s too much going on in there at too many different levels of abstraction. There are strange strings and odd function calls mixed in with doubly nested if statements controlled by flags.”

61 of 219

Refactored

Robert C. Martin, Clean Code, p. 18

62 of 219

Functions should be small

Robert C. Martin, Clean Code, p. 34

“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 not be 100 lines long. Functions should hardly ever be 20 lines long.”

63 of 219

Refactored, again

Robert C. Martin, Clean Code, p. 35

64 of 219

Do one thing well

Robert C. Martin, Clean Code, p. 35

“Functions should do one thing.

They should do it well.

They should do it only.”

Beware: AND, OR, IF, SWITCH

65 of 219

Avoid arguments

Robert C. Martin, Clean Code, p. 40

“The ideal number of arguments for a function is zero (niladic).

Next comes one (monadic), followed closely by two (dyadic).

Three arguments (triadic) should be avoided where possible. More than three (polyadic) requires very special justification—and then shouldn’t be used anyway.”

66 of 219

Argument objects

Robert C. Martin, Clean Code, p. 43

“Reducing the number of arguments by creating objects out of them may seem like cheating, but it’s not.

When groups of variables are passed together… they are likely part of a concept that deserves a name of its own.”

67 of 219

Flag arguments

Robert C. Martin, Clean Code, p. 41

“Flag arguments are ugly.

Passing a boolean into a function is a truly terrible practice. It immediately complicates the signature of the method, loudly proclaiming that this function

does more than one thing.

It does one thing if the flag is true

and another if the flag is false!”

render(true);

68 of 219

Name functions with verbs

Robert C. Martin, Clean Code, p. 43

“Choosing good names for a function can go a long way toward explaining the intent of the function and the order and intent of the arguments.”

writeField(name)

updatePassword(password)

assertEquals(?, ?) // vs.

assertExpectedEqualsActual(expected, actual)

69 of 219

Have no side effects

Robert C. Martin, Clean Code, p. 44

“Side effects are lies. Your function promises to do one thing, but it also does other hidden things.

Sometimes it will make unexpected changes to the variables of its own class. Sometimes it will make them to the parameters passed into the function or to system globals. In either case they are devious and damaging mistruths that often result in strange temporal couplings and order dependencies.”

70 of 219

Side effect?

Robert C. Martin, Clean Code, p. 35

71 of 219

Commands vs. queries

Robert C. Martin, Clean Code, p. 45

“Functions should either do something or answer something, but not both.

Either your function should change the state of an object, or it should return some information about that object. Doing both often leads to confusion.”

Bad example:

public boolean set(String attribute, String value);

72 of 219

How to write good functions?

Robert C. Martin, Clean Code, p. 49

“Writing software is like any other kind of writing…

When I write functions, they come out long and complicated. They have lots of indenting and nested loops. They have long argument lists. The names are arbitrary, and there is duplicated code…

So then I massage and refine that code, splitting out functions, changing names, eliminating duplication. I shrink the methods and reorder them. Sometimes I break out whole classes…”

73 of 219

Tell me a story

Robert C. Martin, Clean Code, p. 49

“Every system is built from a domain-specific language designed by the programmers to describe that system.

Functions are the verbs of that language,

and classes are the nouns.

Master programmers think of systems

as stories to be told rather than

programs to be written.”

74 of 219

Ch. 4: Comments

75 of 219

76 of 219

Pros and cons

Robert C. Martin, Clean Code, p. 53

“Nothing can be quite so helpful as a �well-placed comment.

Nothing can clutter up a module more than �frivolous dogmatic comments.

Nothing can be quite so damaging as an �old crufty comment that propagates �lies and misinformation.”

77 of 219

A necessary evil

Robert C. Martin, Clean Code, p. 53

“Comments are not like Schindler’s List.

They are not ‘pure good.’

Indeed, comments are, at best,

a necessary evil.

78 of 219

Failure

Robert C. Martin, Clean Code, p. 54

“The proper use of comments is to compensate for our failure to express ourself in code.

Note that I used the word failure. I meant it.

Comments are always failures.

79 of 219

Failure

Robert C. Martin, Clean Code, p. 54

So when you find yourself in a position where you need to write a comment, think it through and see whether there isn’t some way to turn the tables and express yourself in code.

Every time you express yourself in code, you should pat yourself on the back.

Every time you write a comment, you should grimace and feel the failure of your ability of expression.

80 of 219

Lies

Robert C. Martin, Clean Code, p. 54

“Why am I so down on comments?

Because they lie.

Not always, and not intentionally, but too often.

�The older a comment is, and the farther away �it is from the code it describes, �the more likely it is to be just plain wrong.”

81 of 219

Comments vs. bad code

Robert C. Martin, Clean Code, p. 55

82 of 219

Comments vs. bad code

Robert C. Martin, Clean Code, p. 55

“One of the more common motivations for writing comments is bad code…We know it’s a mess. So we say to ourselves, ‘Ooh, I’d better comment that!’

No! You’d better clean it!

…Rather than spend your time writing the comments that explain the mess you’ve made,

spend it cleaning that mess.”

83 of 219

Good comments?

84 of 219

Legal comments

Robert C. Martin, Clean Code, p. 55

85 of 219

Explanation of intent

Robert C. Martin, Clean Code, p. 56

86 of 219

Warning of consequences

Robert C. Martin, Clean Code, p. 58

87 of 219

TODOs

Robert C. Martin, Clean Code, p. 58

88 of 219

Amplification

Robert C. Martin, Clean Code, p. 59

89 of 219

Comments for APIs?

Robert C. Martin, Clean Code, p. 59

“There is nothing quite so helpful and satisfying as a well-described public API…

If you are writing a public API, then you should certainly write good [documentation] for it.

But keep in mind the rest of the advice in this chapter. [API documentation] can be just as misleading, nonlocal, and dishonest �as any other kind of comment.”

90 of 219

Bad comments?

91 of 219

Redundant comments

Robert C. Martin, Clean Code, p. 61

92 of 219

Redundant comments

Robert C. Martin, Clean Code, p. 61

What purpose does this comment serve?

It’s certainly not more informative than the code. It does not justify the code, or provide intent or rationale. It is not easier to read than the code. Indeed, it is less precise than the code and entices the reader to accept that lack of precision in lieu of true understanding.”

93 of 219

Misleading comments

Robert C. Martin, Clean Code, p. 63

94 of 219

Mandated comments

Robert C. Martin, Clean Code, p. 63

95 of 219

Journal comments

Robert C. Martin, Clean Code, p. 64

96 of 219

Noise comments

Robert C. Martin, Clean Code, p. 65

97 of 219

Scary noise

Robert C. Martin, Clean Code, p. 66

98 of 219

Prefer variables to comments

Robert C. Martin, Clean Code, p. 67

99 of 219

Commented out code

Robert C. Martin, Clean Code, p. 68

100 of 219

Ch. 5: Formatting

101 of 219

Code formatting

Robert C. Martin, Clean Code, p. 76

“You should choose a set of simple rules that govern the format of your code, and then you should consistently apply those rules.

If you are working on a team, then the team should agree to a single set of formatting rules and all members should comply. It helps to have an automated tool that can apply those formatting rules for you.”

102 of 219

The purpose of formatting

Robert C. Martin, Clean Code, p. 76

“Code formatting is about communication, and communication is the professional developer’s first order of business….

So what are the formatting issues that help us to communicate best?”

103 of 219

Newspaper metaphor

Robert C. Martin, Clean Code, p. 78

“We would like a source file to be like a newspaper article.

The name should be simple but explanatory…The topmost parts of the source file should provide the high-level concepts and algorithms. Detail should increase as we move downward, until at the end

we find the lowest level functions and details in the source file.”

104 of 219

Vertical separation between concepts

Robert C. Martin, Clean Code, p. 78

“Nearly all code is read left to right and top to bottom.

Each line represents an expression or a clause, and each group of lines represents a complete thought.

Those thoughts should be separated from each other with blank lines.”

105 of 219

Vertical separation

Robert C. Martin, Clean Code, p. 79

106 of 219

Vertical separation

Robert C. Martin, Clean Code, p. 79

107 of 219

Vertical density

Robert C. Martin, Clean Code, p. 79

“If openness separates concepts, then vertical density implies close association.

So lines of code that are tightly related should appear vertically dense.”

108 of 219

Vertical density

Robert C. Martin, Clean Code, p. 79

109 of 219

Vertical density

Robert C. Martin, Clean Code, p. 80

110 of 219

Vertical density

  • Conceptual affinity: Related bits of code should be close to each other.
  • Local variables should be declared as close to their usage as possible.
  • Instance variables should be declared at the top of the class.
  • Functions: Caller and callee should be close to each other.
  • Functions: Caller should generally be above callee.*

Concepts that are closely related should be kept vertically close to each other.

Robert C. Martin, Clean Code, p. 80-84

111 of 219

Horizontal formatting

Most of what holds for vertical spacing also applies to horizontal formatting.

Robert C. Martin, Clean Code, p. 85

112 of 219

Horizontal spacing

Robert C. Martin, Clean Code, p. 80-84

113 of 219

Horizontal alignment

Robert C. Martin, Clean Code, p. 87

114 of 219

Horizontal alignment

Robert C. Martin, Clean Code, p. 87

115 of 219

Indentation

Robert C. Martin, Clean Code, p. 88

“A source file is a hierarchy rather like an outline… Each level of this hierarchy is a scope into which names can be declared and in which declarations and executable statements are interpreted.

To make this hierarchy of scopes visible, we indent the lines of source code in proportion to their position in the hierarchy…

Programmers rely heavily on this indentation scheme.”

116 of 219

Indentation

Robert C. Martin, Clean Code, p. 88

117 of 219

Indentation

Robert C. Martin, Clean Code, p. 88

118 of 219

Team rules

“Every programmer has his [or her] own favorite formatting rules, but if he works in a team, then the team rules.”

A team of developers should agree upon a single formatting style, and then every member of that team should use that style.

We want the software to have a consistent style. We don’t want it to appear to have been written by a bunch of disagreeing individuals.”

Robert C. Martin, Clean Code, p. 90

119 of 219

Team rules

“Remember, a good software system is composed of a set of documents that read nicely.

They need to have a consistent and smooth style.

The reader needs to be able to trust that the formatting gestures he or she has seen in one source file will mean the same thing in others.”

Robert C. Martin, Clean Code, p. 90

120 of 219

End of Day 1��Questions?

121 of 219

Ch. 6: Objects and Data Structures

122 of 219

[ Picture of Gandalf ]

123 of 219

Keep it secret, keep it safe

Robert C. Martin, Clean Code, p. 93

“There is a reason that we keep our variables private. We don’t want anyone else to depend on them. We want to keep the freedom to change their type or implementation on a whim or an impulse.

Why, then, do so many programmers automatically add getters and setters to their objects, exposing their private variables as if they were public?”

124 of 219

Data abstraction

Robert C. Martin, Clean Code, p. 94

125 of 219

Hiding implementation

Robert C. Martin, Clean Code, p. 94

“Hiding implementation is not just a matter of putting a layer of functions between the variables.

Hiding implementation is about abstractions!

A class does not simply push its variables out through getters and setters. Rather it exposes abstract interfaces that allow its users to manipulate the essence of the data, without having to know its implementation.”

126 of 219

Data abstraction

Robert C. Martin, Clean Code, p. 94-95

127 of 219

Data abstraction

Robert C. Martin, Clean Code, p. 95

“We do not want to expose the details of our data.

Rather we want to express our data in abstract terms. This is not merely accomplished by using interfaces and/or getters and setters.

Serious thought needs to be put into the best way to represent the data that an object contains. The worst option is to blithely add getters and setters.”

128 of 219

Data/object “anti-symmetry”

Robert C. Martin, Clean Code, p. 95

The difference between objects and data structures:

Objects hide their data behind abstractions and expose functions that operate on that data.

Data structures expose their data and have no meaningful functions.

Go back and read that again. Notice the complimentary nature of the two definitions. They are virtual opposites.”

129 of 219

Law of Demeter

Robert C. Martin, Clean Code, p. 97

“There is a well-known heuristic called the Law of Demeter that says a module should not know about the innards of the objects it manipulates. As we saw in the last section, objects hide their data and expose operations.

This means that an object should not expose its internal structure through accessors because to do so is to expose, rather than to hide, its internal structure.”

130 of 219

131 of 219

Law of Demeter

  • C.
  • An object held in an instance of C.
  • An object passed as an argument of m.
  • An object created by m.

Robert C. Martin, Clean Code, p. 97-98

More precisely: A method m of class C should only call methods of these:

132 of 219

Law of Demeter

  • Your method (m) can call other methods in its class (C) directly.
  • Your method can call methods on its own fields directly (but not on the fields’ fields).
  • When your method takes parameters, your method can call methods on those parameters directly.
  • When your method creates local objects, that method can call methods on the local objects.

http://devblog.avdi.org/2011/07/05/demeter-its-not-just-a-good-idea-its-the-law/

133 of 219

Law of Demeter

  • You can play with yourself.
  • You can play with your own toys. (But you can’t take them apart).
  • You can play with toys that were given to you.
  • And you can play with toys that you’ve made yourself.

http://devblog.avdi.org/2011/07/05/demeter-its-not-just-a-good-idea-its-the-law/

134 of 219

Talking to strangers

http://www.dan-manges.com/blog/37

135 of 219

Talking to friends

http://www.dan-manges.com/blog/37

136 of 219

Why is this better?

http://haacked.com/archive/2009/07/14/law-of-demeter-dot-counting.aspx/

“The Paperboy code is now ‘asking’ the customer for a payment. The paperboy does not have direct access to the wallet.

The second reason that this is better is because the Wallet class can now change, and the paperboy is completely isolated from that change…

The third, and probably most ‘object-oriented’ answer is that we are now free to change the implementation of [‘pay’].”

137 of 219

Summary: Objects and data structures

  • Expose abstractions, not raw data.
  • Objects hide data by default.
  • Data structures expose data by default.
  • Hybrids should be avoided – chose with intention.
  • Law of Demeter: Be careful about what objects know about each other.
  • Really, this is all about API design! (Also known as “designing contracts”.

138 of 219

Ch. 9: Unit tests

139 of 219

Three laws of TDD

First Law: �You may not write production code until you have written a failing unit test.

Second Law: �You may not write more of a unit test than is sufficient to fail, and not compiling is failing.

Third Law: �You may not write more production code than is sufficient to pass the currently failing test.

Robert C. Martin, Clean Code, p. 122

140 of 219

Three laws of TDD

“These three laws lock you into a cycle

that is perhaps thirty seconds long.

The tests and the production code are written together, with the tests just a few seconds ahead of the production code.

If we work this way, we will write

dozens of tests every day,

hundreds of tests every month,

and thousands of tests every year.”

Robert C. Martin, Clean Code, p. 122

141 of 219

Combatting fear

Without tests “you lose the very thing that keeps your production code flexible.

Yes, you read that correctly. It is unit tests that keep our code flexible, maintainable, and reusable.

The reason is simple. If you have tests, you do not fear making changes to the code! Without tests every change is a possible bug.”

Robert C. Martin, Clean Code, p. 124

142 of 219

Combatting fear

Kent Beck says: “All methodologies are based on fear”. He’s talking, of course, about TDD.

For Beck, “test-driven development is a way of managing fear during programming […]. �Fear makes you tentative. �Fear makes you want to communicate less. �Fear makes you shy away from feedback. �Fear makes you grumpy.”

Robert C. Martin, Clean Code, p. 124

143 of 219

Combatting fear

144 of 219

Keep your test code clean too

“Having dirty tests is equivalent to, if not worse than, having no tests.

The problem is that tests must change as the production code evolves. The dirtier the tests, the harder they are to change. The more tangled the test code, the more likely it is that you will spend more time cramming new tests into the suite than it takes to write the new production code.

Test code is just as important as production code.

Robert C. Martin, Clean Code, p. 123-124

145 of 219

Clean tests?

“What makes a clean test?

Three things. Readability, readability, and readability.

Readability is perhaps even more important in unit tests than it is in production code.”

Robert C. Martin, Clean Code, p. 124

146 of 219

Clean test?

Robert C. Martin, Clean Code, p. 125

147 of 219

Cleaner test

Robert C. Martin, Clean Code, p. 126

148 of 219

Build-Operate-Check

“The BUILD-OPERATE-CHECK pattern is made obvious by the structure of these tests. Each of the tests is clearly split into three parts. The first part builds up the test data, the second part operates on that test data, and the third part checks that the operation yielded the expected results.”

Robert C. Martin, Clean Code, p. 127

149 of 219

Testing DSLs

“The tests [above] demonstrate the technique of building a domain-specific language (DSL) for your tests.

Rather than using the APIs that programmers use to manipulate the system, we build up a set of functions and utilities that make use of those APIs and that make the tests more convenient to write and easier to read.”

Robert C. Martin, Clean Code, p. 127

150 of 219

Single concept per test

“There is a school of thought4 that says that every test… should have one and only one assert statement…

I think the single assert rule is a good guideline…

[but] perhaps a better rule is that we want to �test a single concept in each test function.”

Robert C. Martin, Clean Code, p. 130-131

151 of 219

F.I.R.S.T

  • Fast: Tests should be fast. When tests run slow, you won't want to run them frequently.
  • Independent: Tests should not depend on each other. Dependency makes diagnosing problems difficult.
  • Repeatable: Tests should be repeatable in any environment, and always return the same results.
  • Self-Validating: Tests should have a boolean output; they either pass or fail.
  • Timely: Tests need to be written, ideally, just before the production code.

Robert C. Martin, Clean Code, p. 132-133

152 of 219

Unit tests summary

“I think an entire book could be written about clean tests.

Tests are as important to the health of a project as the production code is. Perhaps they are even more important, because tests preserve and enhance the flexibility, maintainability, and reusability of the production code. So keep your tests constantly clean. Work to make them expressive and succinct. Invent testing APIs that act as domain-specific language that helps you write the tests.

If you let the tests rot, then your code will rot too. �Keep your tests clean.”

Robert C. Martin, Clean Code, p. 133

153 of 219

Ch. 10: Classes

154 of 219

Most of what holds for

functions also holds

for classes

155 of 219

Class organization

“Following the standard Java convention, a class should begin with a list of variables. Public static constants, if any, should come first. Then private static variables, followed by private instance variables.

There is seldom a good reason to have �a public variable.”

Robert C. Martin, Clean Code, p.136

156 of 219

Class organization

“Public functions should follow the list of variables.

We like to put the private utilities called by a public function right after the public function itself.

This follows the stepdown rule and helps the program read like a newspaper article.”

Robert C. Martin, Clean Code, p.136

157 of 219

Breaking encapsulation

“We like to keep our variables and utility functions private, but we’re not fanatic about it.

Sometimes we need to make a variable or utility function protected [or even public] so that it can be accessed by a test.

For us, tests rule.”

Robert C. Martin, Clean Code, p.136

158 of 219

Small classes!

“The first rule of classes is that they should be small.

The second rule of classes is that �they should be smaller than that.”

Robert C. Martin, Clean Code, p.136

159 of 219

What do we mean by small?

“With functions we measured size �by counting physical lines.

With classes we use a different measure. �We count responsibilities.

Robert C. Martin, Clean Code, p.136

160 of 219

“SuperDashboard”

Robert C. Martin, Clean Code, p.136

161 of 219

162 of 219

Refactored… Still not okay?

Robert C. Martin, Clean Code, p. 138

163 of 219

Small classes!

“The name of a class should describe what responsibilities it fulfills. ��In fact, naming is probably the first way of helping determine class size. ��If we cannot derive a concise name for a class, then it’s likely too large.”

Robert C. Martin, Clean Code, p.138

164 of 219

No “ifs”, “ands” or “buts”.

“We should also be able to write a brief description of the class in about 25 words, without using the words “if,” “and,” “or,” or “but.”

“The SuperDashboard provides access to the component that last held the focus, and it also allows us to track the version and build numbers.” The first “and” is a hint that SuperDashboard has too many responsibilities.”

Robert C. Martin, Clean Code, p.138

165 of 219

Single responsibility principle

“The Single Responsibility Principle (SRP) states that a class or module should have one, and only one, reason to change.”

Robert C. Martin, Clean Code, p.138

166 of 219

Single responsibility

Robert C. Martin, Clean Code, p. 139

167 of 219

Single responsibility rant

“Getting software to work and making software clean are two very different activities.

Most of us have limited room in our heads, so we focus on getting our code to work more than organization and cleanliness.

This is wholly appropriate. Maintaining a separation of concerns is just as important in our programming activities as it is in our programs.”

Robert C. Martin, Clean Code, p.139

168 of 219

Single responsibility rant

“The problem is that too many of us think that we are done once the program works.

We fail to switch to the other concern of organization and cleanliness.”

Robert C. Martin, Clean Code, p.139

169 of 219

Single responsibility rant

“Many developers fear that a large number of small, single-purpose classes makes it more difficult to understand the bigger picture.

They are concerned that they must navigate from class to class in order to figure out how a larger piece of work gets accomplished.”

Robert C. Martin, Clean Code, p.139

170 of 219

Single responsibility rant

“However, a system with many small classes has no more moving parts than a system with a few large classes. There is just as much to learn in the system with a few large classes.

So the question is:

Do you want your tools organized into toolboxes with many small drawers each containing well-defined and well-labeled components? Or do you want a few drawers that you just toss everything into?”

Robert C. Martin, Clean Code, p.139

171 of 219

Cohesion

“Classes should have a small number of instance variables. ��Each of the methods of a class should manipulate one or more of those variables. ��In general the more variables a method manipulates the more cohesive that method is to its class. A class in which each variable is used by each method is maximally cohesive.”

Robert C. Martin, Clean Code, p.140

172 of 219

Cohesion

Robert C. Martin, Clean Code, p.140

173 of 219

Cohesion

“Maintaining cohesion results in many small classes… breaking a large function into many smaller functions often gives us the opportunity to split several smaller classes out as well. This gives our program a much better organization and a more transparent structure."

Robert C. Martin, Clean Code, p.141

174 of 219

Isolating from Change

“We want to structure our systems so that we muck with as little as possible when we update them with new or changed features.

In an ideal system, we incorporate new features by extending the system, not by making modifications to existing code.”

Robert C. Martin, Clean Code, p.149

175 of 219

Small is the fundamental design principle

Small classes and functions are easier to read and understand.

Small classes and small functions are easier to test.

Small classes and small functions are isolated from each other, meaning we can change their implementations separately.

Small classes and small functions give us the freedom to embrace change without fear.

176 of 219

Ch. 12: Emergence

177 of 219

Getting cleaner code

via emergent design principles

178 of 219

Four simple rules

“What if there were four simple rules that you could follow that would help you create good designs as you worked?…

What if these four rules facilitated the emergence of good designs?”

Robert C. Martin, Clean Code, p. 171

179 of 219

Kent Beck’s rules of simple design

  1. Runs all the tests.
  2. Contains no duplication.
  3. Expresses the intent of the programmer.
  4. Minimizes the number [and size] of classes and methods.

Robert C. Martin, Clean Code, p. 172

A design is “simple” if it:

180 of 219

Runs all the tests

“Making our systems testable pushes us toward a design where our classes are small �and single purpose…

Remarkably, following a simple and obvious rule that says we need to have tests and run them continuously impacts our system’s adherence to the primary OO goals of low coupling and high cohesion.

Writing tests leads to better designs.”

Robert C. Martin, Clean Code, p. 172

181 of 219

Steps 2-4: Refactoring

182 of 219

Elimination duplication

183 of 219

Avoid duplication

“Duplication is the primary enemy of a well-designed system. It represents additional work, additional risk, and additional unnecessary complexity.

Duplication manifests itself in many forms. Lines of code that look exactly alike are, of course, duplication.

Lines of code that are similar can often be massaged to look even more alike so that they can be more easily refactored.

And duplication can exist in other forms such as duplication of implementation.”

Robert C. Martin, Clean Code, p. 173

184 of 219

Duplicate implementation

Robert C. Martin, Clean Code, p. 173

185 of 219

Be expressive

  • Choosing good names.
  • Keeping functions and classes small.
  • Using standard nomenclature, syntax, and patterns.
  • Spending time making sure your tests are well-written.

Robert C. Martin, Clean Code, p. 175

“Code should clearly express the intent of its author. The clearer the author can make the code, the less time others will have to spend understanding it.”

Express yourself by…

186 of 219

Be expressive

But the most important way to be expressive is to try.

All too often we get our code working and then move on to the next problem without giving sufficient thought to making that code easy �for the next person to read.

Remember, the most likely next person �to read the code will be you.”

Robert C. Martin, Clean Code, p. 175

187 of 219

Be expressive

“So take a little pride in your workmanship. ��Spend a little time with each of your functions and classes. Choose better names, split large functions into smaller functions, and generally just take care of what you’ve created.

Care is a precious resource.

Robert C. Martin, Clean Code, p. 176

188 of 219

Minimal classes and methods

“Our goal is to keep our overall system small while we are also keeping our functions and classes small.

Remember, however, that this rule is the lowest priority of the four rules of Simple Design. So, although it’s important to keep class and function count low, it’s more important to have tests, eliminate duplication, and express yourself.”

Robert C. Martin, Clean Code, p. 176

189 of 219

Ch. 17: Smells and Heuristics

190 of 219

191 of 219

Comment smells

Robert C. Martin, Clean Code, p. 286-287

C1. Inappropriate information

C2. Obsolete comment

C3. Redundant comment

C4. Poorly written comment

C5. Commented out code

192 of 219

Environment smells

Robert C. Martin, Clean Code, p. 287

E1. Build requires more than one step

E2. Tests require more than one step

193 of 219

Function smells

Robert C. Martin, Clean Code, p. 288

F1. Too many arguments

F2. Output arguments

F3. Flag arguments

F4. Dead function

194 of 219

General smells

Robert C. Martin, Clean Code, p. 288-292

G1. Multiple languages in one source file

G5. Duplication

G6. Code at the wrong level of abstraction

G7. Base classes depending on derivatives

G8. Too much information

G9. Dead code

195 of 219

General smells

Robert C. Martin, Clean Code, p. 292-293

G10. Vertical separation

G14. Feature envy

196 of 219

Feature envy

Robert C. Martin, Clean Code, p. 293

197 of 219

General smells

Robert C. Martin, Clean Code, p. 294-297

G15. Selector/flag arguments

G17. Misplaced responsibility

G19. Use explanatory variables

G20. Function names say what they do

198 of 219

Function names do what they say

Robert C. Martin, Clean Code, p. 297

199 of 219

General smells

Robert C. Martin, Clean Code, p. 300-301

G25. Replace magic numbers with named constants

G28. Encapsulate conditionals

200 of 219

Name the conditional

Robert C. Martin, Clean Code, p. 301

201 of 219

General smells

Robert C. Martin, Clean Code, p. 302-304

G29. Avoid negative conditionals

G30. Functions should do one thing

G33. Encapsulate boundary conditions

202 of 219

Encapsulate boundary conditions

Robert C. Martin, Clean Code, p. 304

203 of 219

Name smells

Robert C. Martin, Clean Code, p. 309-312

N1. Choose descriptive names

N3. Use standard nomenclature

N4. Unambiguous names

N5. Long names for long scopes

N7. Names should describe side effects

204 of 219

Test smells

Robert C. Martin, Clean Code, p. 313-314

T1. Insufficient tests

T2. Use a coverage tool

T3. Don’t skip tests

T5. Test boundary conditions

T6. Test exhaustively near bugs

T9. Tests should be fast

205 of 219

Summary

206 of 219

Write for your readers

  • Readability is our first principle. Code that is easy to understand is our highest priority as craftsmen.
  • Simplicity and ease of maintenance (or “maintainability”) will usually trump elegance. “Tricky code” or “magical code” are usually synonyms for “bad code”.
  • Always write for your team, your future self, and for those who come after you and will have to maintain the code.

Sources: CleanCode:Ch1, CodeComplete:Ch34

207 of 219

Write for your readers

  • Bob Martin: “The ratio of time spent reading vs. writing is well over 10:1... Because this ratio is so high, we want the reading of code to be easy, even if it makes the writing harder. Of course there's no way to write code without reading it, so making it easy to read actually makes it easier to write.”
  • Steve McConnell: “Readable code doesn’t take any longer to write than confusing code does… It’s easier to be sure your code works if you can easily read what you wrote… Making code readable is not an optional part of the development process, and favoring write-time convenience over read-time convenience is a false economy.”

Sources: CleanCode:Ch1, CodeComplete:Ch34

208 of 219

Leave it better than you found it

  • Refactor constantly, and relentlessly. Always look for ways to make things a little better.
  • Bob Martin: “If we all checked-in our code a little cleaner than when we checked it out, the code simply could not rot... Change one variable name for the better, break up one function that's a little too large, eliminate one small bit of duplication, clean up one composite if statement.”
  • Our mantra should be “N + 1” in everything we do.

Sources: CleanCode:Ch1

209 of 219

Principle of least surprise

  • Ward Cunningham: “You know you are working on clean code when each routine you read turns out to be pretty much what you expected.”
  • “Ward expects that when you read clean code you won't be surprised at all. Indeed, you won't even expend much effort. You will read it, and it will be pretty much what you expected. It will be obvious, simple, and compelling.”
  • Also worth mentioning: Clean code lives where you’d expect to find it.

Sources: CleanCode:Ch1

210 of 219

Choose descriptive names

  • Bob Martin: “Names in software are 90 percent of what make software readable. You need to take the time to choose them wisely and keep them relevant. Names are too important to treat carelessly.”
  • Names should fully and accurately describe the variable or function they represent.
  • Names should be as specific as possible. Names that are vague enough to be used for more than one purpose should be avoided.
  • Names should be memorable. Avoid meaningless abstractions.

Sources: CleanCode:Ch1, CodeComplete:Ch7,Ch11

211 of 219

Choose descriptive names

  • Technique: Avoid abbreviations and single-character variable names.
  • Technique: Introduce explaining variables. Add variables or entire methods purely for the value they add by clarifying your intent.
  • Technique: Iterate twice. Ask yourself: “What’s a better name for this?”. Then ask it again.

Sources: CleanCode:Ch1, G20; CodeComplete:Ch7,Ch11

212 of 219

Avoid duplication

  • Don’t repeat yourself (DRY) is a core principle. Many people identify duplicate code as the root of all evil in programming.
  • Bob Martin: “Every time you see duplication in the code, it represents a missed opportunity for abstraction.”
  • Most design patterns are simply techniques to eliminate duplication. So too with “normal forms” in database design.
  • Important note: Avoiding duplication is very important, but not necessarily as important as clarity or maintainability.

Sources: CleanCode:G5, CleanCode:Chapter3

213 of 219

Do only one thing

  • Methods, functions, classes and even individual lines of code should do only one thing, and do that one thing well.
  • Technique: Look for ANDs and ORs, and extract functions or blocks of code that do more than one thing into multiple functions or blocks.
  • Technique: Ask yourself if this code is testable. Code that does more than one thing is very hard to test.

Sources: CleanCode:G30, CleanCode:Chapter3

214 of 219

Use explanatory variables

  • Bob Martin: “One of the more powerful ways to make a program readable is to break the calculations up into intermediate values that are held in variables with meaningful names.”
  • Technique: Replace pieces of expressions with explaining variables. This is great for regular expressions: “text.gsub!(/<\/?[^>]*>/, ‘’)” becomes “html_tags = /<\/?[^>]*>/; text.gsub!(html_tags, ‘’)”.

Sources: CleanCode:G19; Refactoring:IntroduceExplainingVariable, ExtractMethod

215 of 219

Use explanatory methods

  • Technique: Extract the expression into a separate method. This is often preferable to introducing a temporary explaining variable because the expression can then be re-used. The previous example would be even better as: “remove_html_tags( text )”.
  • Technique: Give the conditional a name. Here’s a trivial example: Replace “if post.comments.size > 0 && post.active” with “if post.has_comments?”.

Sources: CleanCode:G19; Refactoring:IntroduceExplainingVariable, ExtractMethod

216 of 219

Write code that can be tested

  • Testing eliminates our fear of making changes.
  • Small methods that do only one thing are trivial to test.
  • Tests should be small: Test one concept at a time.
  • Treat your tests with the same care you treat your production code with.
  • Write code (DSL) to help make your tests easier to read, easier to change, and easier to re-use.
  • In most cases, write your tests first.* Thinking about the test helps refine requirements and provide a target.

217 of 219

Sources

  • Clean Code: Robert C. Martin, "Clean Code", Prentice Hall, 2009
  • CodeComplete: Steve McConnell, “Code Complete”, 2nd ed., Microsoft Press, 2004.
  • Refactoring: Martin Fowler, “Refactoring”, Addison-Wesley, 1999.
  • Wikipedia: http://en.wikipedia.org

218 of 219

Image credits

Clean Code book cover: http://ecx.images-amazon.com/images/I/51oXyW8WQwL._SX258_BO1,204,203,200_.jpg

WTFs per minute: https://s-media-cache-ak0.pinimg.com/736x/27/69/8a/27698a48b044a7f8d46ccb4e5974d38d.jpg

House and blueprints: http://venusgccwbe.com/wp-content/uploads/2013/08/construction_home.jpg

Mona Lisa: http://uploads6.wikiart.org/images/leonardo-da-vinci/mona-lisa.jpg

Writing: http://bibsandbaubles.com/wp-content/uploads/2011/09/writing-with-pen.jpg

Creativity Corporation: https://cyberetto.files.wordpress.com/2012/04/corporate-creativity-cartoon.jpg

Psychopath: http://4.bp.blogspot.com/-3NsWfjz0YZU/UVBKv-2_n1I/AAAAAAAAAzQ/U4EygDznr50/s1600/psychopath.jpg

Hemingway: http://netdna.copyblogger.com/images/650/hemingway.jpg

Painting (Picasso): http://www.saleoilpaintings.com/paintings-image/pablo-picasso/pablo-picasso-guernica-1937-gallery-wrap.jpg

http://img.topofart.com/images/artists/Pablo_Picasso/paintings/picasso012.jpg

Painting (Pollock): https://chocolatepencils.files.wordpress.com/2014/03/autumn_rhythm.jpg

Programming together: http://starscomputingcorps.org/sites/default/files/programs.pair%20programming.jpg

Boys communicating: http://cdn-media-2.lifehack.org/wp-content/files/2012/12/improve-communications.jpg

Coding like writing a book: https://pbs.twimg.com/media/BpRR8KZIEAAXfm1.jpg

Stranger danger: http://rewards4mom.s3.amazonaws.com/2014/03/Stranger-Danger-Monkey.jpg

Fight club: http://www.michaelcwheeler.com/wp-content/uploads/2013/06/tumblr_m4i1ecYGgS1qzsnfto1_500.jpg

Yoda/Grumpy Cat: https://s-media-cache-ak0.pinimg.com/564x/b1/8b/26/b18b2685435f0ce5678694f490f20891.jpg

Matrix: http://blogs.discovermagazine.com/notrocketscience/files/2012/05/Hey_you_try_illustrating_a_.jpg

219 of 219

Thank you!� �धन्यवाद

Neal Enssle

http://neal.enssle.me

Twitter: @nealenssle