Writing Cleaner Code
What is “clean” code?
What is “clean” code?
What is “clean” code?
What is “clean” code?
What is “clean” code?
But first…��What is programming?
?
Programming is creative
Programming demands precision
Programming is collaborative
Programming is communication
“Always code as if the person who ends up maintaining your code is a violent psychopath who knows where you live.”
- Martin Golding
Ch. 1: Clean Code
What is “clean” code?
What is “clean” code?
What is “clean” code?
What is “clean” code?
What is “clean” code?
What is “clean” code?
Hemingway’s Rules
…and when to break them
Rules...
The rules are always�rules of thumb
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.”
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
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
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
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
Schools of thought
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.”
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.”
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.”
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.”
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:
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.”
Two core principles…
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.”
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.”
Ch. 2: Meaningful Names
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.”
Use intention-revealing names
Robert C. Martin, Clean Code, p. 18
Use intention-revealing names
Robert C. Martin, Clean Code, p. 18
Use intention-revealing names
Robert C. Martin, Clean Code, p. 18
Use intention-revealing names
Robert C. Martin, Clean Code, p. 18
Avoid disinformation
Robert C. Martin, Clean Code, p. 19
“Programmers must avoid leaving false clues that obscure the meaning of code.”
Make meaningful distinctions
Robert C. Martin, Clean Code, p. 20
Write for humans, not just the compiler
More rules of thumb for names
Robert C. Martin, Clean Code, p. 21-30
More rules of thumb for names
Robert C. Martin, Clean Code, p. 21-30
Don’t be afraid to rename! ��Don’t be afraid to argue �about names!
Ch. 3: Functions
Try to understand the
following function...
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.”
Refactored
Robert C. Martin, Clean Code, p. 18
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.”
Refactored, again
Robert C. Martin, Clean Code, p. 35
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
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.”
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.”
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);
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)
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.”
Side effect?
Robert C. Martin, Clean Code, p. 35
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);
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…”
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.”
Ch. 4: Comments
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.”
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.”
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.”
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.
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.”
Comments vs. bad code
Robert C. Martin, Clean Code, p. 55
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.”
Good comments?
Legal comments
Robert C. Martin, Clean Code, p. 55
Explanation of intent
Robert C. Martin, Clean Code, p. 56
Warning of consequences
Robert C. Martin, Clean Code, p. 58
TODOs
Robert C. Martin, Clean Code, p. 58
Amplification
Robert C. Martin, Clean Code, p. 59
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.”
Bad comments?
Redundant comments
Robert C. Martin, Clean Code, p. 61
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.”
Misleading comments
Robert C. Martin, Clean Code, p. 63
Mandated comments
Robert C. Martin, Clean Code, p. 63
Journal comments
Robert C. Martin, Clean Code, p. 64
Noise comments
Robert C. Martin, Clean Code, p. 65
Scary noise
Robert C. Martin, Clean Code, p. 66
Prefer variables to comments
Robert C. Martin, Clean Code, p. 67
Commented out code
Robert C. Martin, Clean Code, p. 68
Ch. 5: Formatting
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.”
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?”
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.”
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.”
Vertical separation
Robert C. Martin, Clean Code, p. 79
Vertical separation
Robert C. Martin, Clean Code, p. 79
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.”
Vertical density
Robert C. Martin, Clean Code, p. 79
Vertical density
Robert C. Martin, Clean Code, p. 80
Vertical density
Concepts that are closely related should be kept vertically close to each other.
Robert C. Martin, Clean Code, p. 80-84
Horizontal formatting
Most of what holds for vertical spacing also applies to horizontal formatting.
Robert C. Martin, Clean Code, p. 85
Horizontal spacing
Robert C. Martin, Clean Code, p. 80-84
Horizontal alignment
Robert C. Martin, Clean Code, p. 87
Horizontal alignment
Robert C. Martin, Clean Code, p. 87
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.”
Indentation
Robert C. Martin, Clean Code, p. 88
Indentation
Robert C. Martin, Clean Code, p. 88
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
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
End of Day 1��Questions?
Ch. 6: Objects and Data Structures
[ Picture of Gandalf ]
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?”
Data abstraction
Robert C. Martin, Clean Code, p. 94
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.”
Data abstraction
Robert C. Martin, Clean Code, p. 94-95
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.”
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.”
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.”
Law of Demeter
Robert C. Martin, Clean Code, p. 97-98
More precisely: A method m of class C should only call methods of these:
Law of Demeter
http://devblog.avdi.org/2011/07/05/demeter-its-not-just-a-good-idea-its-the-law/
Law of Demeter
http://devblog.avdi.org/2011/07/05/demeter-its-not-just-a-good-idea-its-the-law/
Talking to strangers
http://www.dan-manges.com/blog/37
Talking to friends
http://www.dan-manges.com/blog/37
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’].”
Summary: Objects and data structures
Ch. 9: Unit tests
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
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
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
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
Combatting fear
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
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
Clean test?
Robert C. Martin, Clean Code, p. 125
Cleaner test
Robert C. Martin, Clean Code, p. 126
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
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
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
F.I.R.S.T
Robert C. Martin, Clean Code, p. 132-133
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
Ch. 10: Classes
Most of what holds for
functions also holds
for classes
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
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
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
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
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
“SuperDashboard”
Robert C. Martin, Clean Code, p.136
Refactored… Still not okay?
Robert C. Martin, Clean Code, p. 138
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
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
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
Single responsibility
Robert C. Martin, Clean Code, p. 139
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
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
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
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
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
Cohesion
Robert C. Martin, Clean Code, p.140
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
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
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.
Ch. 12: Emergence
Getting cleaner code
via emergent design principles
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
Kent Beck’s rules of simple design
Robert C. Martin, Clean Code, p. 172
A design is “simple” if it:
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
Steps 2-4: Refactoring
Elimination duplication
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
Duplicate implementation
Robert C. Martin, Clean Code, p. 173
Be expressive
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…
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
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
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
Ch. 17: Smells and Heuristics
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
Environment smells
Robert C. Martin, Clean Code, p. 287
E1. Build requires more than one step
E2. Tests require more than one step
Function smells
Robert C. Martin, Clean Code, p. 288
F1. Too many arguments
F2. Output arguments
F3. Flag arguments
F4. Dead function
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
General smells
Robert C. Martin, Clean Code, p. 292-293
G10. Vertical separation
G14. Feature envy
Feature envy
Robert C. Martin, Clean Code, p. 293
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
Function names do what they say
Robert C. Martin, Clean Code, p. 297
General smells
Robert C. Martin, Clean Code, p. 300-301
G25. Replace magic numbers with named constants
G28. Encapsulate conditionals
Name the conditional
Robert C. Martin, Clean Code, p. 301
General smells
Robert C. Martin, Clean Code, p. 302-304
G29. Avoid negative conditionals
G30. Functions should do one thing
G33. Encapsulate boundary conditions
Encapsulate boundary conditions
Robert C. Martin, Clean Code, p. 304
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
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
Summary
Write for your readers
Sources: CleanCode:Ch1, CodeComplete:Ch34
Write for your readers
Sources: CleanCode:Ch1, CodeComplete:Ch34
Leave it better than you found it
Sources: CleanCode:Ch1
Principle of least surprise
Sources: CleanCode:Ch1
Choose descriptive names
Sources: CleanCode:Ch1, CodeComplete:Ch7,Ch11
Choose descriptive names
Sources: CleanCode:Ch1, G20; CodeComplete:Ch7,Ch11
Avoid duplication
Sources: CleanCode:G5, CleanCode:Chapter3
Do only one thing
Sources: CleanCode:G30, CleanCode:Chapter3
Use explanatory variables
Sources: CleanCode:G19; Refactoring:IntroduceExplainingVariable, ExtractMethod
Use explanatory methods
Sources: CleanCode:G19; Refactoring:IntroduceExplainingVariable, ExtractMethod
Write code that can be tested
Sources
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
Thank you!� �धन्यवाद