This document summarizes key principles for writing clean code as outlined in the book "Clean Code" by Robert C. Martin. It discusses ideas like writing code that is easy to read and understand through use of meaningful names, small functions that do one thing well, and avoiding duplication. It also covers principles for object-oriented design like encapsulation, organization for change, and separation of concerns. Testing philosophies like test-driven development and ensuring tests are fast, independent, repeatable, self-validating, and timely are also emphasized. The overall message is that writing clean code requires attention to structure, naming, formatting and testing to produce software that is simple, well-organized and a pleasure to maintain.
2. A HANDBOOK OF AGILE SOFTWARE CRAFTMANSHIP
Robert C. “Uncle Bob” Martin has been a software
professional since 1970 and an international software
consultant since 1990. He is founder and president of
Object Mentor, Inc., a team of experienced consultants who
mentor their clients worldwide in the fields of C++, Java,
C#, Ruby, OO, Design Patterns, UML, Agile Methodologies,
and eXtreme programming.
3. DO YOU CARE ABOUT YOUR CODE? SHOW IT!
• Clean Code shall be simple and well written
• Clean Code shall be easy to read
• Clean Code shall be literate
• Clean Code shall be small and expressive pieces
• Clean Code reduce duplication
“You know you are working on clean code when each routine turns out to be pretty much
what you expected.”
- Ward Cunningham
4.
5. WHY CLEAN CODE?
• You like your code to be simple and efficient
• It will reduce the implementation time
• You will simplify for others that will use your code
• It will make your life much easier!
6. MY CODE WORKS, WHY CHANGE IT?
• Well, read previous slides…
• Understand that agile craftmanship is not a one-man job
• Implementation is done in iterations
• Constantly question your own code – How can I improve this?
• If you don’t know your IDE, learn it.
”In general programmers are pretty smart people. Smart people sometimes like to show off their smarts by
demonstrating their mental juggling abilities. One difference between a smart programmer and a
professional programmer is that the professional understands that clarity is king. Professionals use their
powers for good and write code that others can understand.”
7. MEANINGFUL NAMES
• Choosing good names takes time but saves more than it takes
• 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
8. FUNCTIONS/METHODS
• The first rule of functions is that they should be small. The second rule of functions is
that they should be smaller than that.
• Rule of thumb – Maximum length of 20 lines
• Functions should either do something or answer something, but not both
• Command Query Separation
FUNCTIONS SHOULD DO ONE THING. THEY SHOULD DO IT WELL.
THEY SHOULD DO IT ONLY!
10. METHOD NAMES
• Methods should have verb or verb phrase names like postPayment,
deletePage, or save.
• Accessors, mutators, and predicates should be named for their value and
prefixed with get, set, and is according to the javabean standard
• Don’t be afraid to make a name long
• Be consistent in your name
• When constructors are overloaded, use static factory methods with names
that describe the arguments.
11. PICK ONE WORD AND STICK TO IT
• Avoid to have fetch, retrieve, and get as equivalent methods of different classes.
• Avoid to have a controller and a manager and a driver in the same code base.
What is the essential difference between a DeviceManager and a ProtocolController?
12. PARAMETERS
• The ideal number of arguments for a function is zero
• SetupTeardownIncluder.renderData()
• SetupTeardownIncluder.render(pageData)
• SetupTeardownIncluder.render(“my name”, “this is not good”, false)
• The maximum number of arguments is three
• Need more? Consider wrap some into a class
• The fewer parameters a function has, the easier it is to test it
• A function with zero parameters is easy to test
• Avoid passing a boolean into a function – It is a truly terrible practice
• Loudly proclaiming that this function does more than one thing.
13. RETURN VALUES
• If a function is going to transform its input, the transformation should appear as
the return value
• void includeSetupPageInto(StringBuilder pageText)
• StringBuilder includeSetupPageInto(StringBuilder pageText)
• Prefer exceptions to returning error codes
14. SWITCH STATEMENTS
Functions should do one thing, what about the switch statements?
• Hard to make a switch statement do one thing
• By their nature they do N things
• Hard to avoid switch statements
So, what can we do?
16. TRY/CATCH BLOCKS
Problem
• Try/catch blocks are ugly
• They confuse the structure of the code and mix error processing with normal processing
Solution
• Extract the bodies of the try and catch blocks out into functions
of their own
Functions should do one thing. Error handing 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 the
catch/finally blocks
17. DON’T REPEAT YOURSELF
• Duplication may be the root of all evil in software
• It´s not always easy to spot duplications
• Strategies for eliminating duplication
• Structured programming
• Aspect Oriented Programming
• Component Oriented Programming
• and more ..
18. COMMENTS
• Comments are always failures
• The proper use of comments is to compensate for our failure to express ourself in
code
• Ask yourself – can you always rely on a comment?
• Easy to copy/paste code with comments and forget the change comment
• Warnings, TODOs, Amplifications, Copyright, Javadoc
19. SOME COMMENTS ARE NOTHING BUT NOISE
• Legacy use before we had a source code control system
• Journal Comments
• Closing Brace Comments
• Don’t use a comment when you can use a function or a variable
Are you sure it is?
No, really?
Oh, I didnt get that.
20. IS JAVADOC GOOD OR BAD?
• Javadoc is good, but think first. It’s easy to create javadoc just because ..
• Ask yourself - What purpose does this comment serve?
21. FORMATTING
When people look under the hood, we want them to
be impressed with the neatness, consistency, and
attention to detail that they perceive. We want them to
be struck by the orderliness.
We want their eyebrows to rise as they scroll through
the modules. We want them to perceive that
professionals have been at work
22. THE PURPOSE OF FORMATTING
• Code formatting is about communication, and communication is the professional
developer’s first order of business
• The Newspaper Metaphor
• The name should be simple but explanatory
• Use newlines with care
• Each line represents an expression or a clause,
and each group of lines represents a complete
thought
• Know your IDE
23.
24. OBJECTS
• Objects hide their data behind abstractions and expose functions that operate on
that data
• OOO – Encapsulation
• Abstraction – What does the user need to know?
• Control how your class is supposed to be used
25. DATA STRUCTURES
• A data structure is a class with public variables and no meaningful functions
• DTOs are very useful structures
• Often implemented in “bean” form using OO principles
• Don’t mix and match, choose your side!
26. EXCEPTION HANDLING
• Use exceptions rather than return codes
• Easy to forget to check codes – you can force a user to check for exception
• Don’t return null – consider throw exception
• Don’t pass null
27. UNIT TESTS
• Keep your tests clean
• It´s a Unit test… UNIT test..
• High test coverage -> less fear
• Fewer asserts per test the better
• Name the test in a proper way
Test code is just as important as production code. It is not a second-class citizen. It
requires thought, design, and care. It must be kept as clean as production code!
28. TDD
With Test Driven Design you will write your production code together with the tests
where the tests are just a few seconds ahead. This will lock you into a cycle that is
perhaps thirty seconds long.
• 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.
29. F.I.R.S.T
• Fast - Tests should be fast
• Independent - Tests should not depend on each other
• Repeatable - You should be able to run the tests in any environment
• Self-Validating – A test should either pass or fail
• Timely - The tests need to be written in a timely fashion
30. CLASSES
• Keep your classes small
• Prioritize encapsulation and restriction
• The Single Responsibility Principle (SRP)
With functions we measured size by counting physical lines. With classes we use a
different measure. We count responsibilities.
31. ORGANIZING FOR CHANGE
• In a clean system we organize our classes so as to reduce the risk of change
• Every change subjects us to the risk that the remainder of the system no longer works
as intended
• As soon as we find ourselves opening up a class, we should consider fixing our design
32. OBJECT CREATION
• Sometimes we need to control when and/or how an object gets created
• Factory pattern
• Dependency Injection
• As a user I don’t care about the implementation
• Hide implementation from user
33. CROSS-CUTTING CONCERNS
• Same code that implements the same strategy across many objects
• Transaction
• Logging
• Authorization
• …
• Java Proxies
• AOP – Aspect Oriented Programming
• Cutting points
34. THE BOY SCOUT RULE
Leave the campground cleaner than you
found it!