SlideShare ist ein Scribd-Unternehmen logo
1 von 36
CLEAN CODE
SIMON SÖNNBY
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.
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
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!
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.”
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
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!
Iteration 1
Iteration 2
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.
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?
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.
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
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?
BURY THE STATEMENT IN A LOW-LEVEL CLASS
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
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 ..
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
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.
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?
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
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
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
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!
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
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!
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.
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
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.
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
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
CROSS-CUTTING CONCERNS
• Same code that implements the same strategy across many objects
• Transaction
• Logging
• Authorization
• …
• Java Proxies
• AOP – Aspect Oriented Programming
• Cutting points
THE BOY SCOUT RULE
Leave the campground cleaner than you
found it!
Questions?
THANK YOU

Weitere ähnliche Inhalte

Was ist angesagt?

Practical (J)Unit Testing (2009)
Practical (J)Unit Testing (2009)Practical (J)Unit Testing (2009)
Practical (J)Unit Testing (2009)
Peter Kofler
 

Was ist angesagt? (13)

Clean Code
Clean CodeClean Code
Clean Code
 
Clean code and Coding Standards
Clean code and Coding StandardsClean code and Coding Standards
Clean code and Coding Standards
 
A Brief Introduction to Test-Driven Development
A Brief Introduction to Test-Driven DevelopmentA Brief Introduction to Test-Driven Development
A Brief Introduction to Test-Driven Development
 
Single Responsibility Principle
Single Responsibility PrincipleSingle Responsibility Principle
Single Responsibility Principle
 
Behavior Driven Development
Behavior Driven Development Behavior Driven Development
Behavior Driven Development
 
Practical (J)Unit Testing (2009)
Practical (J)Unit Testing (2009)Practical (J)Unit Testing (2009)
Practical (J)Unit Testing (2009)
 
Automated Testing but like for PowerShell (April 2012)
Automated Testing but like for PowerShell (April 2012)Automated Testing but like for PowerShell (April 2012)
Automated Testing but like for PowerShell (April 2012)
 
obs-tdd-intro
obs-tdd-introobs-tdd-intro
obs-tdd-intro
 
An Introduction To Software Development - Test Driven Development, Part 1
An Introduction To Software Development - Test Driven Development, Part 1An Introduction To Software Development - Test Driven Development, Part 1
An Introduction To Software Development - Test Driven Development, Part 1
 
Adopting tdd in the workplace
Adopting tdd in the workplaceAdopting tdd in the workplace
Adopting tdd in the workplace
 
Dependency injection with Symfony 2
Dependency injection with Symfony 2Dependency injection with Symfony 2
Dependency injection with Symfony 2
 
Best coding practices
Best coding practicesBest coding practices
Best coding practices
 
The Good Code Review
The Good Code ReviewThe Good Code Review
The Good Code Review
 

Ähnlich wie Clean code

The View - Lotusscript coding best practices
The View - Lotusscript coding best practicesThe View - Lotusscript coding best practices
The View - Lotusscript coding best practices
Bill Buchan
 
Clean code, Feb 2012
Clean code, Feb 2012Clean code, Feb 2012
Clean code, Feb 2012
cobyst
 
Code reviews
Code reviewsCode reviews
Code reviews
Roger Xia
 
{10.0} Test Driven Development.pptx
{10.0} Test Driven Development.pptx{10.0} Test Driven Development.pptx
{10.0} Test Driven Development.pptx
AmalEldhose2
 

Ähnlich wie Clean code (20)

Writing Clean Code (Recommendations by Robert Martin)
Writing Clean Code (Recommendations by Robert Martin)Writing Clean Code (Recommendations by Robert Martin)
Writing Clean Code (Recommendations by Robert Martin)
 
Principled And Clean Coding
Principled And Clean CodingPrincipled And Clean Coding
Principled And Clean Coding
 
The View - Lotusscript coding best practices
The View - Lotusscript coding best practicesThe View - Lotusscript coding best practices
The View - Lotusscript coding best practices
 
Clean code presentation
Clean code presentationClean code presentation
Clean code presentation
 
TDD and the Legacy Code Black Hole
TDD and the Legacy Code Black HoleTDD and the Legacy Code Black Hole
TDD and the Legacy Code Black Hole
 
Clean Code - Part 2
Clean Code - Part 2Clean Code - Part 2
Clean Code - Part 2
 
Design p atterns
Design p atternsDesign p atterns
Design p atterns
 
Clean Code Talk (draft)
Clean Code Talk (draft)Clean Code Talk (draft)
Clean Code Talk (draft)
 
Clean code, Feb 2012
Clean code, Feb 2012Clean code, Feb 2012
Clean code, Feb 2012
 
Code reviews
Code reviewsCode reviews
Code reviews
 
Clean Code
Clean CodeClean Code
Clean Code
 
Clean Code (David Frame) - PHPBelfast Meetup 22/02/24
Clean Code (David Frame) - PHPBelfast Meetup 22/02/24Clean Code (David Frame) - PHPBelfast Meetup 22/02/24
Clean Code (David Frame) - PHPBelfast Meetup 22/02/24
 
YAGNI Principle and Clean Code
YAGNI Principle and Clean CodeYAGNI Principle and Clean Code
YAGNI Principle and Clean Code
 
Test Driven Development with Laravel
Test Driven Development with LaravelTest Driven Development with Laravel
Test Driven Development with Laravel
 
{10.0} Test Driven Development.pptx
{10.0} Test Driven Development.pptx{10.0} Test Driven Development.pptx
{10.0} Test Driven Development.pptx
 
Reading Notes : the practice of programming
Reading Notes : the practice of programmingReading Notes : the practice of programming
Reading Notes : the practice of programming
 
Improving the Quality of Existing Software
Improving the Quality of Existing SoftwareImproving the Quality of Existing Software
Improving the Quality of Existing Software
 
Improving Software Quality Using Object Oriented Design Principles
Improving Software Quality Using Object Oriented Design PrinciplesImproving Software Quality Using Object Oriented Design Principles
Improving Software Quality Using Object Oriented Design Principles
 
Improving The Quality of Existing Software
Improving The Quality of Existing SoftwareImproving The Quality of Existing Software
Improving The Quality of Existing Software
 
Writing Better Tests - Applying Clean-Code TDD at 99designs
Writing Better Tests - Applying Clean-Code TDD at 99designsWriting Better Tests - Applying Clean-Code TDD at 99designs
Writing Better Tests - Applying Clean-Code TDD at 99designs
 

Kürzlich hochgeladen

%+27788225528 love spells in Toronto Psychic Readings, Attraction spells,Brin...
%+27788225528 love spells in Toronto Psychic Readings, Attraction spells,Brin...%+27788225528 love spells in Toronto Psychic Readings, Attraction spells,Brin...
%+27788225528 love spells in Toronto Psychic Readings, Attraction spells,Brin...
masabamasaba
 
Large-scale Logging Made Easy: Meetup at Deutsche Bank 2024
Large-scale Logging Made Easy: Meetup at Deutsche Bank 2024Large-scale Logging Made Easy: Meetup at Deutsche Bank 2024
Large-scale Logging Made Easy: Meetup at Deutsche Bank 2024
VictoriaMetrics
 
%+27788225528 love spells in Boston Psychic Readings, Attraction spells,Bring...
%+27788225528 love spells in Boston Psychic Readings, Attraction spells,Bring...%+27788225528 love spells in Boston Psychic Readings, Attraction spells,Bring...
%+27788225528 love spells in Boston Psychic Readings, Attraction spells,Bring...
masabamasaba
 
Abortion Pill Prices Tembisa [(+27832195400*)] 🏥 Women's Abortion Clinic in T...
Abortion Pill Prices Tembisa [(+27832195400*)] 🏥 Women's Abortion Clinic in T...Abortion Pill Prices Tembisa [(+27832195400*)] 🏥 Women's Abortion Clinic in T...
Abortion Pill Prices Tembisa [(+27832195400*)] 🏥 Women's Abortion Clinic in T...
Medical / Health Care (+971588192166) Mifepristone and Misoprostol tablets 200mg
 

Kürzlich hochgeladen (20)

%in kempton park+277-882-255-28 abortion pills for sale in kempton park
%in kempton park+277-882-255-28 abortion pills for sale in kempton park %in kempton park+277-882-255-28 abortion pills for sale in kempton park
%in kempton park+277-882-255-28 abortion pills for sale in kempton park
 
%in tembisa+277-882-255-28 abortion pills for sale in tembisa
%in tembisa+277-882-255-28 abortion pills for sale in tembisa%in tembisa+277-882-255-28 abortion pills for sale in tembisa
%in tembisa+277-882-255-28 abortion pills for sale in tembisa
 
WSO2CON 2024 - Navigating API Complexity: REST, GraphQL, gRPC, Websocket, Web...
WSO2CON 2024 - Navigating API Complexity: REST, GraphQL, gRPC, Websocket, Web...WSO2CON 2024 - Navigating API Complexity: REST, GraphQL, gRPC, Websocket, Web...
WSO2CON 2024 - Navigating API Complexity: REST, GraphQL, gRPC, Websocket, Web...
 
%in Bahrain+277-882-255-28 abortion pills for sale in Bahrain
%in Bahrain+277-882-255-28 abortion pills for sale in Bahrain%in Bahrain+277-882-255-28 abortion pills for sale in Bahrain
%in Bahrain+277-882-255-28 abortion pills for sale in Bahrain
 
%in Stilfontein+277-882-255-28 abortion pills for sale in Stilfontein
%in Stilfontein+277-882-255-28 abortion pills for sale in Stilfontein%in Stilfontein+277-882-255-28 abortion pills for sale in Stilfontein
%in Stilfontein+277-882-255-28 abortion pills for sale in Stilfontein
 
tonesoftg
tonesoftgtonesoftg
tonesoftg
 
%+27788225528 love spells in Toronto Psychic Readings, Attraction spells,Brin...
%+27788225528 love spells in Toronto Psychic Readings, Attraction spells,Brin...%+27788225528 love spells in Toronto Psychic Readings, Attraction spells,Brin...
%+27788225528 love spells in Toronto Psychic Readings, Attraction spells,Brin...
 
%in tembisa+277-882-255-28 abortion pills for sale in tembisa
%in tembisa+277-882-255-28 abortion pills for sale in tembisa%in tembisa+277-882-255-28 abortion pills for sale in tembisa
%in tembisa+277-882-255-28 abortion pills for sale in tembisa
 
WSO2CON 2024 - Does Open Source Still Matter?
WSO2CON 2024 - Does Open Source Still Matter?WSO2CON 2024 - Does Open Source Still Matter?
WSO2CON 2024 - Does Open Source Still Matter?
 
Large-scale Logging Made Easy: Meetup at Deutsche Bank 2024
Large-scale Logging Made Easy: Meetup at Deutsche Bank 2024Large-scale Logging Made Easy: Meetup at Deutsche Bank 2024
Large-scale Logging Made Easy: Meetup at Deutsche Bank 2024
 
%in kaalfontein+277-882-255-28 abortion pills for sale in kaalfontein
%in kaalfontein+277-882-255-28 abortion pills for sale in kaalfontein%in kaalfontein+277-882-255-28 abortion pills for sale in kaalfontein
%in kaalfontein+277-882-255-28 abortion pills for sale in kaalfontein
 
Devoxx UK 2024 - Going serverless with Quarkus, GraalVM native images and AWS...
Devoxx UK 2024 - Going serverless with Quarkus, GraalVM native images and AWS...Devoxx UK 2024 - Going serverless with Quarkus, GraalVM native images and AWS...
Devoxx UK 2024 - Going serverless with Quarkus, GraalVM native images and AWS...
 
%+27788225528 love spells in Boston Psychic Readings, Attraction spells,Bring...
%+27788225528 love spells in Boston Psychic Readings, Attraction spells,Bring...%+27788225528 love spells in Boston Psychic Readings, Attraction spells,Bring...
%+27788225528 love spells in Boston Psychic Readings, Attraction spells,Bring...
 
WSO2CON 2024 Slides - Open Source to SaaS
WSO2CON 2024 Slides - Open Source to SaaSWSO2CON 2024 Slides - Open Source to SaaS
WSO2CON 2024 Slides - Open Source to SaaS
 
Abortion Pill Prices Tembisa [(+27832195400*)] 🏥 Women's Abortion Clinic in T...
Abortion Pill Prices Tembisa [(+27832195400*)] 🏥 Women's Abortion Clinic in T...Abortion Pill Prices Tembisa [(+27832195400*)] 🏥 Women's Abortion Clinic in T...
Abortion Pill Prices Tembisa [(+27832195400*)] 🏥 Women's Abortion Clinic in T...
 
%in Hazyview+277-882-255-28 abortion pills for sale in Hazyview
%in Hazyview+277-882-255-28 abortion pills for sale in Hazyview%in Hazyview+277-882-255-28 abortion pills for sale in Hazyview
%in Hazyview+277-882-255-28 abortion pills for sale in Hazyview
 
OpenChain - The Ramifications of ISO/IEC 5230 and ISO/IEC 18974 for Legal Pro...
OpenChain - The Ramifications of ISO/IEC 5230 and ISO/IEC 18974 for Legal Pro...OpenChain - The Ramifications of ISO/IEC 5230 and ISO/IEC 18974 for Legal Pro...
OpenChain - The Ramifications of ISO/IEC 5230 and ISO/IEC 18974 for Legal Pro...
 
WSO2CON 2024 - WSO2's Digital Transformation Journey with Choreo: A Platforml...
WSO2CON 2024 - WSO2's Digital Transformation Journey with Choreo: A Platforml...WSO2CON 2024 - WSO2's Digital Transformation Journey with Choreo: A Platforml...
WSO2CON 2024 - WSO2's Digital Transformation Journey with Choreo: A Platforml...
 
VTU technical seminar 8Th Sem on Scikit-learn
VTU technical seminar 8Th Sem on Scikit-learnVTU technical seminar 8Th Sem on Scikit-learn
VTU technical seminar 8Th Sem on Scikit-learn
 
What Goes Wrong with Language Definitions and How to Improve the Situation
What Goes Wrong with Language Definitions and How to Improve the SituationWhat Goes Wrong with Language Definitions and How to Improve the Situation
What Goes Wrong with Language Definitions and How to Improve the Situation
 

Clean code

  • 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?
  • 15. BURY THE STATEMENT IN A LOW-LEVEL CLASS
  • 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!