SlideShare a Scribd company logo
1 of 25
Download to read offline
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

What's hot

Refactoring Applications using SOLID Principles
Refactoring Applications using SOLID PrinciplesRefactoring Applications using SOLID Principles
Refactoring Applications using SOLID PrinciplesSteven Smith
 
Top 100 .Net Interview Questions and Answer
Top 100 .Net Interview Questions and AnswerTop 100 .Net Interview Questions and Answer
Top 100 .Net Interview Questions and AnswerVineet Kumar Saini
 
Refactoring 101
Refactoring 101Refactoring 101
Refactoring 101Adam Culp
 
Coding standard and coding guideline
Coding standard and coding guidelineCoding standard and coding guideline
Coding standard and coding guidelineDhananjaysinh Jhala
 
C#3.0 & Vb 9.0 New Features
C#3.0 & Vb 9.0 New FeaturesC#3.0 & Vb 9.0 New Features
C#3.0 & Vb 9.0 New Featurestechfreak
 
Software development best practices & coding guidelines
Software development best practices & coding guidelinesSoftware development best practices & coding guidelines
Software development best practices & coding guidelinesAnkur Goyal
 
Finding Help with Programming Errors: An Exploratory Study of Novice Software...
Finding Help with Programming Errors: An Exploratory Study of Novice Software...Finding Help with Programming Errors: An Exploratory Study of Novice Software...
Finding Help with Programming Errors: An Exploratory Study of Novice Software...Preetha Chatterjee
 
Bad Code Smells
Bad Code SmellsBad Code Smells
Bad Code Smellskim.mens
 
Object Oriented Programming Lab Manual
Object Oriented Programming Lab Manual Object Oriented Programming Lab Manual
Object Oriented Programming Lab Manual Abdul Hannan
 
[DevDay2018] Let’s all get along. Clean Code please! - By: Christophe K. Ngo,...
[DevDay2018] Let’s all get along. Clean Code please! - By: Christophe K. Ngo,...[DevDay2018] Let’s all get along. Clean Code please! - By: Christophe K. Ngo,...
[DevDay2018] Let’s all get along. Clean Code please! - By: Christophe K. Ngo,...DevDay.org
 
Extracting Archival-Quality Information from Software-Related Chats
Extracting Archival-Quality Information from Software-Related ChatsExtracting Archival-Quality Information from Software-Related Chats
Extracting Archival-Quality Information from Software-Related ChatsPreetha Chatterjee
 
Standard Coding, OOP Techniques and Code Reuse
Standard Coding, OOP Techniques and Code ReuseStandard Coding, OOP Techniques and Code Reuse
Standard Coding, OOP Techniques and Code ReuseRayhan Chowdhury
 
OCP Java (OCPJP) 8 Exam Quick Reference Card
OCP Java (OCPJP) 8 Exam Quick Reference CardOCP Java (OCPJP) 8 Exam Quick Reference Card
OCP Java (OCPJP) 8 Exam Quick Reference CardHari kiran G
 
C# interview-questions
C# interview-questionsC# interview-questions
C# interview-questionsnicolbiden
 
Top 20 c# interview Question and answers
Top 20 c# interview Question and answersTop 20 c# interview Question and answers
Top 20 c# interview Question and answersw3asp dotnet
 
Bt0074, oops with java
Bt0074, oops with javaBt0074, oops with java
Bt0074, oops with javasmumbahelp
 
Euro python 2015 writing quality code
Euro python 2015   writing quality codeEuro python 2015   writing quality code
Euro python 2015 writing quality coderadek_j
 

What's hot (20)

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

Viewers also liked

ABAP Code Qualität - Best Practices
ABAP Code Qualität - Best PracticesABAP Code Qualität - Best Practices
ABAP Code Qualität - Best PracticesVirtual Forge
 
ABAPCodeRetreat - ABAP PUSH CHANNELS and SAP FIORI
ABAPCodeRetreat -   ABAP PUSH CHANNELS and SAP FIORIABAPCodeRetreat -   ABAP PUSH CHANNELS and SAP FIORI
ABAPCodeRetreat - ABAP PUSH CHANNELS and SAP FIORIABAPCodeRetreat
 
Test Driven Development #sitFRA
Test Driven Development #sitFRATest Driven Development #sitFRA
Test Driven Development #sitFRAChristian Drumm
 
TDD in the ABAP world - sitNL 2013 edition
TDD in the ABAP world - sitNL 2013 editionTDD in the ABAP world - sitNL 2013 edition
TDD in the ABAP world - sitNL 2013 editionHendrik Neumann
 
SAP Persistence - Creating Source Code Automatically
SAP Persistence - Creating Source Code AutomaticallySAP Persistence - Creating Source Code Automatically
SAP Persistence - Creating Source Code AutomaticallyBlackvard
 
ABAPCodeRetreat - TDD Intro by Damir Majer
ABAPCodeRetreat - TDD Intro by Damir MajerABAPCodeRetreat - TDD Intro by Damir Majer
ABAPCodeRetreat - TDD Intro by Damir MajerABAPCodeRetreat
 

Viewers also liked (7)

ABAP Code Qualität - Best Practices
ABAP Code Qualität - Best PracticesABAP Code Qualität - Best Practices
ABAP Code Qualität - Best Practices
 
ABAPCodeRetreat - ABAP PUSH CHANNELS and SAP FIORI
ABAPCodeRetreat -   ABAP PUSH CHANNELS and SAP FIORIABAPCodeRetreat -   ABAP PUSH CHANNELS and SAP FIORI
ABAPCodeRetreat - ABAP PUSH CHANNELS and SAP FIORI
 
Test Driven Development #sitFRA
Test Driven Development #sitFRATest Driven Development #sitFRA
Test Driven Development #sitFRA
 
TDD in the ABAP world - sitNL 2013 edition
TDD in the ABAP world - sitNL 2013 editionTDD in the ABAP world - sitNL 2013 edition
TDD in the ABAP world - sitNL 2013 edition
 
SAP Persistence - Creating Source Code Automatically
SAP Persistence - Creating Source Code AutomaticallySAP Persistence - Creating Source Code Automatically
SAP Persistence - Creating Source Code Automatically
 
ABAPCodeRetreat - TDD Intro by Damir Majer
ABAPCodeRetreat - TDD Intro by Damir MajerABAPCodeRetreat - TDD Intro by Damir Majer
ABAPCodeRetreat - TDD Intro by Damir Majer
 
ABAP Unit and TDD
ABAP Unit and TDDABAP Unit and TDD
ABAP Unit and TDD
 

Similar to Agile_goa_2013_clean_code_tdd

Introduction to Behavior Driven Development
Introduction to Behavior Driven Development Introduction to Behavior Driven Development
Introduction to Behavior Driven Development Robin O'Brien
 
Web performance
Web  performance Web  performance
Web performance Major Ye
 
Agile Development in .NET
Agile Development in .NETAgile Development in .NET
Agile Development in .NETdanhermes
 
CLEAN CODING AND DEVOPS Final.pptx
CLEAN CODING AND DEVOPS Final.pptxCLEAN CODING AND DEVOPS Final.pptx
CLEAN CODING AND DEVOPS Final.pptxJEEVANANTHAMG6
 
Automated Acceptance Tests & Tool choice
Automated Acceptance Tests & Tool choiceAutomated Acceptance Tests & Tool choice
Automated Acceptance Tests & Tool choicetoddbr
 
Linq To The Enterprise
Linq To The EnterpriseLinq To The Enterprise
Linq To The EnterpriseDaniel Egan
 
The Magic Of Application Lifecycle Management In Vs Public
The Magic Of Application Lifecycle Management In Vs PublicThe Magic Of Application Lifecycle Management In Vs Public
The Magic Of Application Lifecycle Management In Vs PublicDavid Solivan
 
Refactoring Tips by Martin Fowler
Refactoring Tips by Martin FowlerRefactoring Tips by Martin Fowler
Refactoring Tips by Martin FowlerIgor Crvenov
 
How to do code review and use analysis tool in software development
How to do code review and use analysis tool in software developmentHow to do code review and use analysis tool in software development
How to do code review and use analysis tool in software developmentMitosis Technology
 
1 Project 2 Introduction - the SeaPort Project seri.docx
1  Project 2 Introduction - the SeaPort Project seri.docx1  Project 2 Introduction - the SeaPort Project seri.docx
1 Project 2 Introduction - the SeaPort Project seri.docxhoney725342
 
C:\Fakepath\Combating Software Entropy 2
C:\Fakepath\Combating Software Entropy 2C:\Fakepath\Combating Software Entropy 2
C:\Fakepath\Combating Software Entropy 2Hammad Rajjoub
 
C:\Fakepath\Combating Software Entropy 2
C:\Fakepath\Combating Software Entropy 2C:\Fakepath\Combating Software Entropy 2
C:\Fakepath\Combating Software Entropy 2Hammad Rajjoub
 
Java interview questions and answers
Java interview questions and answersJava interview questions and answers
Java interview questions and answersKrishnaov
 
SPCA2013 - Test-driven Development with SharePoint 2013 and Visual Studio
SPCA2013 - Test-driven Development with SharePoint 2013 and Visual StudioSPCA2013 - Test-driven Development with SharePoint 2013 and Visual Studio
SPCA2013 - Test-driven Development with SharePoint 2013 and Visual StudioNCCOMMS
 
Best practices in enterprise applications
Best practices in enterprise applicationsBest practices in enterprise applications
Best practices in enterprise applicationsChandra Sekhar Saripaka
 
TDD And Refactoring
TDD And RefactoringTDD And Refactoring
TDD And RefactoringNaresh Jain
 
Large scale agile development practices
Large scale agile development practicesLarge scale agile development practices
Large scale agile development practicesSkills Matter
 

Similar to Agile_goa_2013_clean_code_tdd (20)

Code review
Code reviewCode review
Code review
 
Introduction to Behavior Driven Development
Introduction to Behavior Driven Development Introduction to Behavior Driven Development
Introduction to Behavior Driven Development
 
Web performance
Web  performance Web  performance
Web performance
 
Tech talks#6: Code Refactoring
Tech talks#6: Code RefactoringTech talks#6: Code Refactoring
Tech talks#6: Code Refactoring
 
Agile Development in .NET
Agile Development in .NETAgile Development in .NET
Agile Development in .NET
 
CLEAN CODING AND DEVOPS Final.pptx
CLEAN CODING AND DEVOPS Final.pptxCLEAN CODING AND DEVOPS Final.pptx
CLEAN CODING AND DEVOPS Final.pptx
 
Automated Acceptance Tests & Tool choice
Automated Acceptance Tests & Tool choiceAutomated Acceptance Tests & Tool choice
Automated Acceptance Tests & Tool choice
 
Tango with django
Tango with djangoTango with django
Tango with django
 
Linq To The Enterprise
Linq To The EnterpriseLinq To The Enterprise
Linq To The Enterprise
 
The Magic Of Application Lifecycle Management In Vs Public
The Magic Of Application Lifecycle Management In Vs PublicThe Magic Of Application Lifecycle Management In Vs Public
The Magic Of Application Lifecycle Management In Vs Public
 
Refactoring Tips by Martin Fowler
Refactoring Tips by Martin FowlerRefactoring Tips by Martin Fowler
Refactoring Tips by Martin Fowler
 
How to do code review and use analysis tool in software development
How to do code review and use analysis tool in software developmentHow to do code review and use analysis tool in software development
How to do code review and use analysis tool in software development
 
1 Project 2 Introduction - the SeaPort Project seri.docx
1  Project 2 Introduction - the SeaPort Project seri.docx1  Project 2 Introduction - the SeaPort Project seri.docx
1 Project 2 Introduction - the SeaPort Project seri.docx
 
C:\Fakepath\Combating Software Entropy 2
C:\Fakepath\Combating Software Entropy 2C:\Fakepath\Combating Software Entropy 2
C:\Fakepath\Combating Software Entropy 2
 
C:\Fakepath\Combating Software Entropy 2
C:\Fakepath\Combating Software Entropy 2C:\Fakepath\Combating Software Entropy 2
C:\Fakepath\Combating Software Entropy 2
 
Java interview questions and answers
Java interview questions and answersJava interview questions and answers
Java interview questions and answers
 
SPCA2013 - Test-driven Development with SharePoint 2013 and Visual Studio
SPCA2013 - Test-driven Development with SharePoint 2013 and Visual StudioSPCA2013 - Test-driven Development with SharePoint 2013 and Visual Studio
SPCA2013 - Test-driven Development with SharePoint 2013 and Visual Studio
 
Best practices in enterprise applications
Best practices in enterprise applicationsBest practices in enterprise applications
Best practices in enterprise applications
 
TDD And Refactoring
TDD And RefactoringTDD And Refactoring
TDD And Refactoring
 
Large scale agile development practices
Large scale agile development practicesLarge scale agile development practices
Large scale agile development practices
 

Recently uploaded

Exploring the Future Potential of AI-Enabled Smartphone Processors
Exploring the Future Potential of AI-Enabled Smartphone ProcessorsExploring the Future Potential of AI-Enabled Smartphone Processors
Exploring the Future Potential of AI-Enabled Smartphone Processorsdebabhi2
 
Why Teams call analytics are critical to your entire business
Why Teams call analytics are critical to your entire businessWhy Teams call analytics are critical to your entire business
Why Teams call analytics are critical to your entire businesspanagenda
 
Emergent Methods: Multi-lingual narrative tracking in the news - real-time ex...
Emergent Methods: Multi-lingual narrative tracking in the news - real-time ex...Emergent Methods: Multi-lingual narrative tracking in the news - real-time ex...
Emergent Methods: Multi-lingual narrative tracking in the news - real-time ex...Zilliz
 
Artificial Intelligence Chap.5 : Uncertainty
Artificial Intelligence Chap.5 : UncertaintyArtificial Intelligence Chap.5 : Uncertainty
Artificial Intelligence Chap.5 : UncertaintyKhushali Kathiriya
 
Apidays New York 2024 - Accelerating FinTech Innovation by Vasa Krishnan, Fin...
Apidays New York 2024 - Accelerating FinTech Innovation by Vasa Krishnan, Fin...Apidays New York 2024 - Accelerating FinTech Innovation by Vasa Krishnan, Fin...
Apidays New York 2024 - Accelerating FinTech Innovation by Vasa Krishnan, Fin...apidays
 
Strategize a Smooth Tenant-to-tenant Migration and Copilot Takeoff
Strategize a Smooth Tenant-to-tenant Migration and Copilot TakeoffStrategize a Smooth Tenant-to-tenant Migration and Copilot Takeoff
Strategize a Smooth Tenant-to-tenant Migration and Copilot Takeoffsammart93
 
Apidays New York 2024 - Passkeys: Developing APIs to enable passwordless auth...
Apidays New York 2024 - Passkeys: Developing APIs to enable passwordless auth...Apidays New York 2024 - Passkeys: Developing APIs to enable passwordless auth...
Apidays New York 2024 - Passkeys: Developing APIs to enable passwordless auth...apidays
 
MINDCTI Revenue Release Quarter One 2024
MINDCTI Revenue Release Quarter One 2024MINDCTI Revenue Release Quarter One 2024
MINDCTI Revenue Release Quarter One 2024MIND CTI
 
How to Troubleshoot Apps for the Modern Connected Worker
How to Troubleshoot Apps for the Modern Connected WorkerHow to Troubleshoot Apps for the Modern Connected Worker
How to Troubleshoot Apps for the Modern Connected WorkerThousandEyes
 
AXA XL - Insurer Innovation Award Americas 2024
AXA XL - Insurer Innovation Award Americas 2024AXA XL - Insurer Innovation Award Americas 2024
AXA XL - Insurer Innovation Award Americas 2024The Digital Insurer
 
2024: Domino Containers - The Next Step. News from the Domino Container commu...
2024: Domino Containers - The Next Step. News from the Domino Container commu...2024: Domino Containers - The Next Step. News from the Domino Container commu...
2024: Domino Containers - The Next Step. News from the Domino Container commu...Martijn de Jong
 
MS Copilot expands with MS Graph connectors
MS Copilot expands with MS Graph connectorsMS Copilot expands with MS Graph connectors
MS Copilot expands with MS Graph connectorsNanddeep Nachan
 
Finding Java's Hidden Performance Traps @ DevoxxUK 2024
Finding Java's Hidden Performance Traps @ DevoxxUK 2024Finding Java's Hidden Performance Traps @ DevoxxUK 2024
Finding Java's Hidden Performance Traps @ DevoxxUK 2024Victor Rentea
 
Rising Above_ Dubai Floods and the Fortitude of Dubai International Airport.pdf
Rising Above_ Dubai Floods and the Fortitude of Dubai International Airport.pdfRising Above_ Dubai Floods and the Fortitude of Dubai International Airport.pdf
Rising Above_ Dubai Floods and the Fortitude of Dubai International Airport.pdfOrbitshub
 
Strategies for Landing an Oracle DBA Job as a Fresher
Strategies for Landing an Oracle DBA Job as a FresherStrategies for Landing an Oracle DBA Job as a Fresher
Strategies for Landing an Oracle DBA Job as a FresherRemote DBA Services
 
Cloud Frontiers: A Deep Dive into Serverless Spatial Data and FME
Cloud Frontiers:  A Deep Dive into Serverless Spatial Data and FMECloud Frontiers:  A Deep Dive into Serverless Spatial Data and FME
Cloud Frontiers: A Deep Dive into Serverless Spatial Data and FMESafe Software
 
CNIC Information System with Pakdata Cf In Pakistan
CNIC Information System with Pakdata Cf In PakistanCNIC Information System with Pakdata Cf In Pakistan
CNIC Information System with Pakdata Cf In Pakistandanishmna97
 
ProductAnonymous-April2024-WinProductDiscovery-MelissaKlemke
ProductAnonymous-April2024-WinProductDiscovery-MelissaKlemkeProductAnonymous-April2024-WinProductDiscovery-MelissaKlemke
ProductAnonymous-April2024-WinProductDiscovery-MelissaKlemkeProduct Anonymous
 
Corporate and higher education May webinar.pptx
Corporate and higher education May webinar.pptxCorporate and higher education May webinar.pptx
Corporate and higher education May webinar.pptxRustici Software
 
Exploring Multimodal Embeddings with Milvus
Exploring Multimodal Embeddings with MilvusExploring Multimodal Embeddings with Milvus
Exploring Multimodal Embeddings with MilvusZilliz
 

Recently uploaded (20)

Exploring the Future Potential of AI-Enabled Smartphone Processors
Exploring the Future Potential of AI-Enabled Smartphone ProcessorsExploring the Future Potential of AI-Enabled Smartphone Processors
Exploring the Future Potential of AI-Enabled Smartphone Processors
 
Why Teams call analytics are critical to your entire business
Why Teams call analytics are critical to your entire businessWhy Teams call analytics are critical to your entire business
Why Teams call analytics are critical to your entire business
 
Emergent Methods: Multi-lingual narrative tracking in the news - real-time ex...
Emergent Methods: Multi-lingual narrative tracking in the news - real-time ex...Emergent Methods: Multi-lingual narrative tracking in the news - real-time ex...
Emergent Methods: Multi-lingual narrative tracking in the news - real-time ex...
 
Artificial Intelligence Chap.5 : Uncertainty
Artificial Intelligence Chap.5 : UncertaintyArtificial Intelligence Chap.5 : Uncertainty
Artificial Intelligence Chap.5 : Uncertainty
 
Apidays New York 2024 - Accelerating FinTech Innovation by Vasa Krishnan, Fin...
Apidays New York 2024 - Accelerating FinTech Innovation by Vasa Krishnan, Fin...Apidays New York 2024 - Accelerating FinTech Innovation by Vasa Krishnan, Fin...
Apidays New York 2024 - Accelerating FinTech Innovation by Vasa Krishnan, Fin...
 
Strategize a Smooth Tenant-to-tenant Migration and Copilot Takeoff
Strategize a Smooth Tenant-to-tenant Migration and Copilot TakeoffStrategize a Smooth Tenant-to-tenant Migration and Copilot Takeoff
Strategize a Smooth Tenant-to-tenant Migration and Copilot Takeoff
 
Apidays New York 2024 - Passkeys: Developing APIs to enable passwordless auth...
Apidays New York 2024 - Passkeys: Developing APIs to enable passwordless auth...Apidays New York 2024 - Passkeys: Developing APIs to enable passwordless auth...
Apidays New York 2024 - Passkeys: Developing APIs to enable passwordless auth...
 
MINDCTI Revenue Release Quarter One 2024
MINDCTI Revenue Release Quarter One 2024MINDCTI Revenue Release Quarter One 2024
MINDCTI Revenue Release Quarter One 2024
 
How to Troubleshoot Apps for the Modern Connected Worker
How to Troubleshoot Apps for the Modern Connected WorkerHow to Troubleshoot Apps for the Modern Connected Worker
How to Troubleshoot Apps for the Modern Connected Worker
 
AXA XL - Insurer Innovation Award Americas 2024
AXA XL - Insurer Innovation Award Americas 2024AXA XL - Insurer Innovation Award Americas 2024
AXA XL - Insurer Innovation Award Americas 2024
 
2024: Domino Containers - The Next Step. News from the Domino Container commu...
2024: Domino Containers - The Next Step. News from the Domino Container commu...2024: Domino Containers - The Next Step. News from the Domino Container commu...
2024: Domino Containers - The Next Step. News from the Domino Container commu...
 
MS Copilot expands with MS Graph connectors
MS Copilot expands with MS Graph connectorsMS Copilot expands with MS Graph connectors
MS Copilot expands with MS Graph connectors
 
Finding Java's Hidden Performance Traps @ DevoxxUK 2024
Finding Java's Hidden Performance Traps @ DevoxxUK 2024Finding Java's Hidden Performance Traps @ DevoxxUK 2024
Finding Java's Hidden Performance Traps @ DevoxxUK 2024
 
Rising Above_ Dubai Floods and the Fortitude of Dubai International Airport.pdf
Rising Above_ Dubai Floods and the Fortitude of Dubai International Airport.pdfRising Above_ Dubai Floods and the Fortitude of Dubai International Airport.pdf
Rising Above_ Dubai Floods and the Fortitude of Dubai International Airport.pdf
 
Strategies for Landing an Oracle DBA Job as a Fresher
Strategies for Landing an Oracle DBA Job as a FresherStrategies for Landing an Oracle DBA Job as a Fresher
Strategies for Landing an Oracle DBA Job as a Fresher
 
Cloud Frontiers: A Deep Dive into Serverless Spatial Data and FME
Cloud Frontiers:  A Deep Dive into Serverless Spatial Data and FMECloud Frontiers:  A Deep Dive into Serverless Spatial Data and FME
Cloud Frontiers: A Deep Dive into Serverless Spatial Data and FME
 
CNIC Information System with Pakdata Cf In Pakistan
CNIC Information System with Pakdata Cf In PakistanCNIC Information System with Pakdata Cf In Pakistan
CNIC Information System with Pakdata Cf In Pakistan
 
ProductAnonymous-April2024-WinProductDiscovery-MelissaKlemke
ProductAnonymous-April2024-WinProductDiscovery-MelissaKlemkeProductAnonymous-April2024-WinProductDiscovery-MelissaKlemke
ProductAnonymous-April2024-WinProductDiscovery-MelissaKlemke
 
Corporate and higher education May webinar.pptx
Corporate and higher education May webinar.pptxCorporate and higher education May webinar.pptx
Corporate and higher education May webinar.pptx
 
Exploring Multimodal Embeddings with Milvus
Exploring Multimodal Embeddings with MilvusExploring Multimodal Embeddings with Milvus
Exploring Multimodal Embeddings with Milvus
 

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