SlideShare a Scribd company logo
How to write clean code
using TDD
Srinivasa GV
srinivasa.gv@sap.com
SAP Labs India
Agenda
1. What is Clean Code ?
2. Some basics on Clean Code
3. What is TDD?
4. Fundamentals of TDD
5. Demo of TDD with Clean Code
3
Some definitions of Clean Code 1
Dave Thomas – godfather of the Eclipse
strategy: Clean code can be read, and
enhanced by a developer other than its
original author. It has unit and acceptance
tests. It has meaningful names.
1 Robert C. Martin Clean Code Prentice Hall
4
Thought leaders definition…
Grady Booch – author of OOAD with
applications: Clean code is simple and
direct. Clean code reads like well-written
prose and never obscures the designer’s
intent
5
Thought leaders definition…
Bjarne Stroustrup – inventor of C++:
Clean code does one thing well.
6
Why Clean Code ? – A story
Ram opens the project and enters the class.
He scrolls down to the method needing change.
He pauses, considering his options.
Oh, he’s scrolling up to the top of the function to check the initialization of a variable.
Now he scrolls back down and begins to type. Ooops, he’s erasing what he typed!
He types it again.
He erases it again!
He types half of something else but then erases that!
7
..
He scrolls down to another function that calls the function he’s changing to see
how it is called.
He scrolls back up and types the same code he just erased.
He pauses.
He erases that code again!
He pops up another window and looks at a subclass. Is that function
overridden?
Reading vs Writing ratio is > 10:1
8
Clean Codes
 Meaningful Names
 Functions
 Comments
 Formatting
 Classes
9
Meaningful Names
 Class Names
Classes and objects should have noun or noun phrase names
like Customer, WikiPage, Account, and AddressParser.
Avoid words likeManager, Processor, Data, or Info in the name of a class. A class name
should not be a verb.
 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.[4]
[4] http://java.sun.com/products/javabeans/docs/spec.html
10
Functions/Methods
 One level of abstraction per Function:
Functions should do one thing. They should do it well. They should do it only.
 Functions need to be short, well named and nicely organized.
11
An example
Bad Code Good Code
HTMLUtil.java
public static String testableHtmlContent(
PageData pageData,
boolean includeSuiteSetup
) throws Exception {
WikiPage wikiPage = pageData.getWikiPage();
StringBuffer buffer = new StringBuffer();
if (pageData.hasAttribute("Test")) {
if (includeSuiteSetup) {
WikiPage suiteSetup =
PageCrawlerImpl.getInheritedPage(
SuiteResponder.SUITE_SETUP_NAME, wikiPage
);
if (suiteSetup != null) {
WikiPagePath pagePath =
suiteSetup.getPageCrawler().getFullPath(suiteSetup);
String pagePathName = PathParser.render(pagePath);
buffer.append("!include -setup .")
.append(pagePathName)
.append("n");
}
}
WikiPage setup =
PageCrawlerImpl.getInheritedPage("SetUp", wikiPage);
if (setup != null) {
WikiPagePath setupPath =
wikiPage.getPageCrawler().getFullPath(setup);
String setupPathName = PathParser.render(setupPath);
buffer.append("!include -setup .")
.append(setupPathName)
……
……....
………………………………..ANOTHER 40 more lines
HTMLUtil.java
public static String renderPageWithSetupsAndTeardowns(
PageData pageData, boolean isSuite
) throws Exception {
boolean isTestPage = pageData.hasAttribute("Test");
if (isTestPage) {
WikiPage testPage = pageData.getWikiPage();
StringBuffer newPageContent = new StringBuffer();
includeSetupPages(testPage, newPageContent, isSuite);
newPageContent.append(pageData.getContent());
includeTeardownPages(testPage, newPageContent, isSuite);
pageData.setContent(newPageContent.toString());
}
return pageData.getHtml();
}
ANOTHER 3 MORE FUNCTIONS
includeSetupPages,
newPageContnet,
includeTearDownPages
12
Comments
 Try to avoid comments except for absolute minimum required
 Explain Yourself in Code – write expressive code
// Check to see if the student is eligible for full marks
if ((student.flags & YEARLY_FLAG) &&
(student.attendance > 200))
if (student.isEligibleForFullMarks())
13
Formatting
Code formatting is important – it’s because code communicates
Vertical Formatting - The topmost parts of the source file should provide the high-
level concepts and algorithms (Vertical openness, Vertical Density, Vertical
Distance, Vertical Ordering)
Horizontal Formatting (Horizontal openness and Density, Indentation)
14
An example for vertical openness between concepts
Good Code Bad Code
package fitnesse.wikitext.widgets;
import java.util.regex.*;
public class BoldWidget extends ParentWidget {
public static final String REGEXP = "'''.+?'''";
private static final Pattern pattern = Pattern.compile("'''(.+?)'''",
Pattern.MULTILINE + Pattern.DOTALL
);
public BoldWidget(ParentWidget parent, String text) throws Exception {
super(parent);
Matcher match = pattern.matcher(text);
match.find();
addChildWidgets(match.group(1));
}
public String render() throws Exception {
StringBuffer html = new StringBuffer("<b>");
html.append(childHtml()).append("</b>");
return html.toString();
}
}
package fitnesse.wikitext.widgets;
import java.util.regex.*;
public class BoldWidget extends ParentWidget {
public static final String REGEXP = "'''.+?'''";
private static final Pattern pattern = Pattern.compile("'''(.+?)'''",
Pattern.MULTILINE + Pattern.DOTALL);
public BoldWidget(ParentWidget parent, String text) throws Exception {
super(parent);
Matcher match = pattern.matcher(text);
match.find();
addChildWidgets(match.group(1));}
public String render() throws Exception {
StringBuffer html = new StringBuffer("<b>");
html.append(childHtml()).append("</b>");
return html.toString();
}
}
15
Classes
 Classes Should Be Small
It’s not about the number of lines, but about the number of responsibilities
Classes should have one responsibility—one reason to change.
 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.
 Follow S.O.L.I.D principles (Single responsibility, Open/Closed, Liskov
Substitution, Interface Segregation, Dependency Injection)
16
An example for Single Responsiblity
Source:
http://www.globalnerdy.com
Test Driven Development
“Accountants practice Dual Entry Bookkeeping as part of the GAAP1
TDD is Dual Entry Bookkeeping for software”
Robert C Martin
Test First – Test Driven Development
TDD Cycle
1. Write a failing test
2. Write the code to pass the test
3. Clean up / Refactor
(either production or test code)
Start
Test
Code
Test
Refactor
Test Driven Development
Demo
Test Driven Development Demo
User Story:
Roman to Arabic Numerals Conversion
 As a user who imports external documents into the system I want the system to convert
Roman numerals into Arabic values (e.g. year numerals or list numbers) so that searching
and ordering is possible.
Additional Info:
 The system shall deal with roman numerals as described in wikipedia
 The system shall deal with the range from I (1) to MMM (3000)
Acceptance Criteria:
The system will convert MCMLXXXIV to 1984
TDD Benefits I
Focus on Essentials since
 tests codify requirements
 test drives feature implementation
 you build the simplest thing that is
needed right now
Confidence
 safety net
 encourages changes
 bug repellent
TDD Benefits II
Better Code Quality
 Consumable API
 Decoupling and testability
Living Technical Documentation
 Tests as executable specification
 Tests document usage of API
Which benefits did you observe?
Expected:
 Test driven development –
– tests and productive coding are created in parallel – in small steps ; steps are like how we analyze the problem
– 100% coverage by default
– TDD Cycle: Green – Red – Green – Refactor
– debugger wasn’t required
– Self validating tests
 Code Quality
– Easy to read
 Continuous Integration
– Software was executable all the time
 Refactoring
– Avoid Technical Debt
– The refactoring to get checks for invalid numbers was always secured by existing unit tests.
Thank you !
Contact: srinivasa.gv@sap.com / M: 9741594154
25
References
Test – Driven Development By example – Kent Beck
Clean Code A Handbook of Agile Software Craftsmanship – Robert C. Martin
Refactoring Improving the design of Existing Code – Martin Fowler

More Related Content

PPTX
Writing High Quality Code in C#
PPTX
C# coding standards, good programming principles & refactoring
PDF
Code Refactoring
PPT
Principles in Refactoring
PDF
Refactoring: Improve the design of existing code
PPTX
Improving Software Quality Using Object Oriented Design Principles
PPTX
Coding standards
PPT
Code Refactoring
Writing High Quality Code in C#
C# coding standards, good programming principles & refactoring
Code Refactoring
Principles in Refactoring
Refactoring: Improve the design of existing code
Improving Software Quality Using Object Oriented Design Principles
Coding standards
Code Refactoring

What's hot (20)

PPTX
Refactoring Applications using SOLID Principles
PDF
Top 100 .Net Interview Questions and Answer
PDF
Refactoring 101
PPTX
C# interview
PPTX
Coding standard and coding guideline
PPT
C#3.0 & Vb 9.0 New Features
PPTX
Software development best practices & coding guidelines
PPSX
Coding standard
PPTX
Finding Help with Programming Errors: An Exploratory Study of Novice Software...
PDF
Bad Code Smells
PDF
Object Oriented Programming Lab Manual
PDF
[DevDay2018] Let’s all get along. Clean Code please! - By: Christophe K. Ngo,...
PPTX
Java fundamentals
PPTX
Extracting Archival-Quality Information from Software-Related Chats
PDF
Standard Coding, OOP Techniques and Code Reuse
PPTX
OCP Java (OCPJP) 8 Exam Quick Reference Card
PDF
C# interview-questions
PPTX
Top 20 c# interview Question and answers
DOCX
Bt0074, oops with java
PDF
Euro python 2015 writing quality code
Refactoring Applications using SOLID Principles
Top 100 .Net Interview Questions and Answer
Refactoring 101
C# interview
Coding standard and coding guideline
C#3.0 & Vb 9.0 New Features
Software development best practices & coding guidelines
Coding standard
Finding Help with Programming Errors: An Exploratory Study of Novice Software...
Bad Code Smells
Object Oriented Programming Lab Manual
[DevDay2018] Let’s all get along. Clean Code please! - By: Christophe K. Ngo,...
Java fundamentals
Extracting Archival-Quality Information from Software-Related Chats
Standard Coding, OOP Techniques and Code Reuse
OCP Java (OCPJP) 8 Exam Quick Reference Card
C# interview-questions
Top 20 c# interview Question and answers
Bt0074, oops with java
Euro python 2015 writing quality code
Ad

Viewers also liked (7)

PDF
ABAP Code Qualität - Best Practices
PDF
ABAPCodeRetreat - ABAP PUSH CHANNELS and SAP FIORI
PPTX
Test Driven Development #sitFRA
PDF
TDD in the ABAP world - sitNL 2013 edition
PPTX
SAP Persistence - Creating Source Code Automatically
PDF
ABAPCodeRetreat - TDD Intro by Damir Majer
PDF
ABAP Unit and TDD
ABAP Code Qualität - Best Practices
ABAPCodeRetreat - ABAP PUSH CHANNELS and SAP FIORI
Test Driven Development #sitFRA
TDD in the ABAP world - sitNL 2013 edition
SAP Persistence - Creating Source Code Automatically
ABAPCodeRetreat - TDD Intro by Damir Majer
ABAP Unit and TDD
Ad

Similar to Agile_goa_2013_clean_code_tdd (20)

PPTX
Code review
PPT
Introduction to Behavior Driven Development
PDF
Google Interview Questions By Scholarhat
PPTX
Web performance
PPTX
Tech talks#6: Code Refactoring
PPTX
Agile Development in .NET
PPTX
CLEAN CODING AND DEVOPS Final.pptx
PPTX
Automated Acceptance Tests & Tool choice
PPT
Classes and objects object oriented programming
PPTX
Tango with django
PPT
Linq To The Enterprise
PDF
UNIT I cloud computing ppt cloud ccd all about the cloud computing
PDF
Cognizant Interview Questions By ScholarHat.pdf
PPT
The Magic Of Application Lifecycle Management In Vs Public
PPT
Refactoring Tips by Martin Fowler
PDF
How to do code review and use analysis tool in software development
DOCX
1 Project 2 Introduction - the SeaPort Project seri.docx
PPTX
C:\Fakepath\Combating Software Entropy 2
PPTX
C:\Fakepath\Combating Software Entropy 2
DOCX
Java interview questions and answers
Code review
Introduction to Behavior Driven Development
Google Interview Questions By Scholarhat
Web performance
Tech talks#6: Code Refactoring
Agile Development in .NET
CLEAN CODING AND DEVOPS Final.pptx
Automated Acceptance Tests & Tool choice
Classes and objects object oriented programming
Tango with django
Linq To The Enterprise
UNIT I cloud computing ppt cloud ccd all about the cloud computing
Cognizant Interview Questions By ScholarHat.pdf
The Magic Of Application Lifecycle Management In Vs Public
Refactoring Tips by Martin Fowler
How to do code review and use analysis tool in software development
1 Project 2 Introduction - the SeaPort Project seri.docx
C:\Fakepath\Combating Software Entropy 2
C:\Fakepath\Combating Software Entropy 2
Java interview questions and answers

Recently uploaded (20)

PDF
A contest of sentiment analysis: k-nearest neighbor versus neural network
PPTX
cloud_computing_Infrastucture_as_cloud_p
PPTX
MicrosoftCybserSecurityReferenceArchitecture-April-2025.pptx
PDF
Architecture types and enterprise applications.pdf
PDF
How ambidextrous entrepreneurial leaders react to the artificial intelligence...
PDF
2021 HotChips TSMC Packaging Technologies for Chiplets and 3D_0819 publish_pu...
PDF
Microsoft Solutions Partner Drive Digital Transformation with D365.pdf
PDF
Profit Center Accounting in SAP S/4HANA, S4F28 Col11
PDF
Hybrid model detection and classification of lung cancer
PDF
A comparative study of natural language inference in Swahili using monolingua...
PDF
Video forgery: An extensive analysis of inter-and intra-frame manipulation al...
PDF
Univ-Connecticut-ChatGPT-Presentaion.pdf
PDF
1 - Historical Antecedents, Social Consideration.pdf
PDF
DASA ADMISSION 2024_FirstRound_FirstRank_LastRank.pdf
PPTX
OMC Textile Division Presentation 2021.pptx
PDF
Transform Your ITIL® 4 & ITSM Strategy with AI in 2025.pdf
PPTX
Modernising the Digital Integration Hub
PPT
What is a Computer? Input Devices /output devices
PDF
Developing a website for English-speaking practice to English as a foreign la...
PPTX
O2C Customer Invoices to Receipt V15A.pptx
A contest of sentiment analysis: k-nearest neighbor versus neural network
cloud_computing_Infrastucture_as_cloud_p
MicrosoftCybserSecurityReferenceArchitecture-April-2025.pptx
Architecture types and enterprise applications.pdf
How ambidextrous entrepreneurial leaders react to the artificial intelligence...
2021 HotChips TSMC Packaging Technologies for Chiplets and 3D_0819 publish_pu...
Microsoft Solutions Partner Drive Digital Transformation with D365.pdf
Profit Center Accounting in SAP S/4HANA, S4F28 Col11
Hybrid model detection and classification of lung cancer
A comparative study of natural language inference in Swahili using monolingua...
Video forgery: An extensive analysis of inter-and intra-frame manipulation al...
Univ-Connecticut-ChatGPT-Presentaion.pdf
1 - Historical Antecedents, Social Consideration.pdf
DASA ADMISSION 2024_FirstRound_FirstRank_LastRank.pdf
OMC Textile Division Presentation 2021.pptx
Transform Your ITIL® 4 & ITSM Strategy with AI in 2025.pdf
Modernising the Digital Integration Hub
What is a Computer? Input Devices /output devices
Developing a website for English-speaking practice to English as a foreign la...
O2C Customer Invoices to Receipt V15A.pptx

Agile_goa_2013_clean_code_tdd

  • 1. How to write clean code using TDD Srinivasa GV srinivasa.gv@sap.com SAP Labs India
  • 2. Agenda 1. What is Clean Code ? 2. Some basics on Clean Code 3. What is TDD? 4. Fundamentals of TDD 5. Demo of TDD with Clean Code
  • 3. 3 Some definitions of Clean Code 1 Dave Thomas – godfather of the Eclipse strategy: Clean code can be read, and enhanced by a developer other than its original author. It has unit and acceptance tests. It has meaningful names. 1 Robert C. Martin Clean Code Prentice Hall
  • 4. 4 Thought leaders definition… Grady Booch – author of OOAD with applications: Clean code is simple and direct. Clean code reads like well-written prose and never obscures the designer’s intent
  • 5. 5 Thought leaders definition… Bjarne Stroustrup – inventor of C++: Clean code does one thing well.
  • 6. 6 Why Clean Code ? – A story Ram opens the project and enters the class. He scrolls down to the method needing change. He pauses, considering his options. Oh, he’s scrolling up to the top of the function to check the initialization of a variable. Now he scrolls back down and begins to type. Ooops, he’s erasing what he typed! He types it again. He erases it again! He types half of something else but then erases that!
  • 7. 7 .. He scrolls down to another function that calls the function he’s changing to see how it is called. He scrolls back up and types the same code he just erased. He pauses. He erases that code again! He pops up another window and looks at a subclass. Is that function overridden? Reading vs Writing ratio is > 10:1
  • 8. 8 Clean Codes  Meaningful Names  Functions  Comments  Formatting  Classes
  • 9. 9 Meaningful Names  Class Names Classes and objects should have noun or noun phrase names like Customer, WikiPage, Account, and AddressParser. Avoid words likeManager, Processor, Data, or Info in the name of a class. A class name should not be a verb.  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.[4] [4] http://java.sun.com/products/javabeans/docs/spec.html
  • 10. 10 Functions/Methods  One level of abstraction per Function: Functions should do one thing. They should do it well. They should do it only.  Functions need to be short, well named and nicely organized.
  • 11. 11 An example Bad Code Good Code HTMLUtil.java public static String testableHtmlContent( PageData pageData, boolean includeSuiteSetup ) throws Exception { WikiPage wikiPage = pageData.getWikiPage(); StringBuffer buffer = new StringBuffer(); if (pageData.hasAttribute("Test")) { if (includeSuiteSetup) { WikiPage suiteSetup = PageCrawlerImpl.getInheritedPage( SuiteResponder.SUITE_SETUP_NAME, wikiPage ); if (suiteSetup != null) { WikiPagePath pagePath = suiteSetup.getPageCrawler().getFullPath(suiteSetup); String pagePathName = PathParser.render(pagePath); buffer.append("!include -setup .") .append(pagePathName) .append("n"); } } WikiPage setup = PageCrawlerImpl.getInheritedPage("SetUp", wikiPage); if (setup != null) { WikiPagePath setupPath = wikiPage.getPageCrawler().getFullPath(setup); String setupPathName = PathParser.render(setupPath); buffer.append("!include -setup .") .append(setupPathName) …… …….... ………………………………..ANOTHER 40 more lines HTMLUtil.java public static String renderPageWithSetupsAndTeardowns( PageData pageData, boolean isSuite ) throws Exception { boolean isTestPage = pageData.hasAttribute("Test"); if (isTestPage) { WikiPage testPage = pageData.getWikiPage(); StringBuffer newPageContent = new StringBuffer(); includeSetupPages(testPage, newPageContent, isSuite); newPageContent.append(pageData.getContent()); includeTeardownPages(testPage, newPageContent, isSuite); pageData.setContent(newPageContent.toString()); } return pageData.getHtml(); } ANOTHER 3 MORE FUNCTIONS includeSetupPages, newPageContnet, includeTearDownPages
  • 12. 12 Comments  Try to avoid comments except for absolute minimum required  Explain Yourself in Code – write expressive code // Check to see if the student is eligible for full marks if ((student.flags & YEARLY_FLAG) && (student.attendance > 200)) if (student.isEligibleForFullMarks())
  • 13. 13 Formatting Code formatting is important – it’s because code communicates Vertical Formatting - The topmost parts of the source file should provide the high- level concepts and algorithms (Vertical openness, Vertical Density, Vertical Distance, Vertical Ordering) Horizontal Formatting (Horizontal openness and Density, Indentation)
  • 14. 14 An example for vertical openness between concepts Good Code Bad Code package fitnesse.wikitext.widgets; import java.util.regex.*; public class BoldWidget extends ParentWidget { public static final String REGEXP = "'''.+?'''"; private static final Pattern pattern = Pattern.compile("'''(.+?)'''", Pattern.MULTILINE + Pattern.DOTALL ); public BoldWidget(ParentWidget parent, String text) throws Exception { super(parent); Matcher match = pattern.matcher(text); match.find(); addChildWidgets(match.group(1)); } public String render() throws Exception { StringBuffer html = new StringBuffer("<b>"); html.append(childHtml()).append("</b>"); return html.toString(); } } package fitnesse.wikitext.widgets; import java.util.regex.*; public class BoldWidget extends ParentWidget { public static final String REGEXP = "'''.+?'''"; private static final Pattern pattern = Pattern.compile("'''(.+?)'''", Pattern.MULTILINE + Pattern.DOTALL); public BoldWidget(ParentWidget parent, String text) throws Exception { super(parent); Matcher match = pattern.matcher(text); match.find(); addChildWidgets(match.group(1));} public String render() throws Exception { StringBuffer html = new StringBuffer("<b>"); html.append(childHtml()).append("</b>"); return html.toString(); } }
  • 15. 15 Classes  Classes Should Be Small It’s not about the number of lines, but about the number of responsibilities Classes should have one responsibility—one reason to change.  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.  Follow S.O.L.I.D principles (Single responsibility, Open/Closed, Liskov Substitution, Interface Segregation, Dependency Injection)
  • 16. 16 An example for Single Responsiblity Source: http://www.globalnerdy.com
  • 17. Test Driven Development “Accountants practice Dual Entry Bookkeeping as part of the GAAP1 TDD is Dual Entry Bookkeeping for software” Robert C Martin
  • 18. Test First – Test Driven Development TDD Cycle 1. Write a failing test 2. Write the code to pass the test 3. Clean up / Refactor (either production or test code) Start Test Code Test Refactor
  • 20. Test Driven Development Demo User Story: Roman to Arabic Numerals Conversion  As a user who imports external documents into the system I want the system to convert Roman numerals into Arabic values (e.g. year numerals or list numbers) so that searching and ordering is possible. Additional Info:  The system shall deal with roman numerals as described in wikipedia  The system shall deal with the range from I (1) to MMM (3000) Acceptance Criteria: The system will convert MCMLXXXIV to 1984
  • 21. TDD Benefits I Focus on Essentials since  tests codify requirements  test drives feature implementation  you build the simplest thing that is needed right now Confidence  safety net  encourages changes  bug repellent
  • 22. TDD Benefits II Better Code Quality  Consumable API  Decoupling and testability Living Technical Documentation  Tests as executable specification  Tests document usage of API
  • 23. Which benefits did you observe? Expected:  Test driven development – – tests and productive coding are created in parallel – in small steps ; steps are like how we analyze the problem – 100% coverage by default – TDD Cycle: Green – Red – Green – Refactor – debugger wasn’t required – Self validating tests  Code Quality – Easy to read  Continuous Integration – Software was executable all the time  Refactoring – Avoid Technical Debt – The refactoring to get checks for invalid numbers was always secured by existing unit tests.
  • 24. Thank you ! Contact: srinivasa.gv@sap.com / M: 9741594154
  • 25. 25 References Test – Driven Development By example – Kent Beck Clean Code A Handbook of Agile Software Craftsmanship – Robert C. Martin Refactoring Improving the design of Existing Code – Martin Fowler