SlideShare ist ein Scribd-Unternehmen logo
1 von 54
Downloaden Sie, um offline zu lesen
Keeping Code Clean
Agile tools and practices for better code
Topics
● Pair Programming
● Automated Unit Testing
● Refactoring
● Test-Driven Development
● Agile Architecture
Pair Programming
Pair Programming
● Continuous Code Review
● Better Design w/ Less Code
● Faster Problem Solving
● More People Familiar w/ System
● Team Grows Closer
Pair Programming - Benefits
Pair Programming - Evidence
Pair Programming - Evidence
Williams 2000
● Efforts +15%, Schedule -43%
Baheti 2002
● Effort +2%, Schedule -49%
Ciokowlski 2002
● Effort +9%, Schedule -46%
Automated Unit Testing
What is Automated Unit Testing?
Use of special software to control the
execution of unit tests and the comparison of
actual outcomes with predicted outcomes.
To get full benefit run as part of the build
process and schedule to run automatically
once or twice a day.
Automated Unit Test Suite Benefits
● Unit tests find problems early in the development cycle
● Developers will be less afraid to change code
● Development process becomes more flexible
● Easier for a developer to take over code they are
unfamiliar with (improves “Truck Factor”)
● Reduces need for manual testing
● Software development becomes more testable and
repeatable
What is a Unit Test Case?
● A test for a single unit of functionality
● Each method tests a specific bit of
functionality
● Automated by the test-runner framework
AAA Test Structure
● Structure:
○ Arrange
○ Act
○ Assert
● Benefits:
○ Readable
○ Consistent
public class SalesTaxTest
{
private SalesTax unit;
@Test
public void TestCalculate()
{
unit = new SalesTax(); // ARRANGE
double tax = unit.Calculate(10); // ACT
Assert.assertEquals(tax, 0.9); // ASSERT
}
}
Unit Testing Best Practices
● Test simple stuff first
● Get it working - then test boundaries/exceptions
● Use assert
● Keep tests small & understandable
● Make test method names descriptive
● Keep tests independent of each other
● Avoid System.out messages
● Don’t repeat tests! Test once and trust it.
Test Doubles
● Stand in for a collaborating object e.g. database,
webservice
● Create test independence
● Make tests run faster
● Types of Doubles
○ Fakes: working implementation e.g.fake web service
○ Mocks: preprogrammed with expectations
○ Stubs: provide canned answers to the test’s calls
Refactoring
Refactoring
● What is refactoring?
● Why refactor?
● When to refactor?
What is Refactoring?
“A change to the system that leaves its behavior
unchanged, but enhances some non-functional quality -
simplicity, flexibility, understandability, performance”
-- Kent Beck, Extreme Programing Explained (p. 179)
“A change made to the internal structure of software to
make it easier to understand and cheaper to modify without
changing its observable behavior.”
-- Martin Fowler, Refactoring (p. 53)
Why Refactor the Code?
● Prevent “design decay”
● Clean up messes
● Simplify
● Increase readability / understandability
● Find bugs
● Reduce debugging time
● Build in what we learn about the application
● It’s part of the creative process
When to Refactor
● Code reviews / TDD cycle
● Rule of three
○ cut & paste. Third time copying? Now is the time to
generalize and move this to a new procedure.
● When you:
○ add functionality
○ learn something about the code
○ identify a code smell
What is a Code Smell?
● any symptom in the code that possibly
indicates a deeper problem.
● not bugs - but indicate weaknesses in design
that may be slowing down development or
increasing the risk of bugs or failures in the
future.
Code Smells (1/2)
● Duplicated code: near-identical code in multiple places
● Long method: a too large method/function/procedure
● Large class: a class that has grown too large.
● Too many parameters: decreases readability/quality.
● Identifier names are too short or excessively long
● Complex conditionals: branches that check lots of
unrelated conditions and edge cases that don't seem to
capture the meaning of a block of code.
Code Smells (2/2)
● Comments - refactor so these are no longer needed!
● Feature envy: excessive use of another class’ methods
● Inappropriate intimacy: a class that has dependencies
on implementation details of another class.
● Lazy class / Freeloader: a class that does too little.
● Contrived complexity: simpler design would suffice.
● Excessive use of literals (use named constants)
Why Developers Resist Refactoring
● Lack of understanding
● Short-term focus
● Not paid for overhead tasks like refactoring
● Fear of breaking current program
Use TDD to overcome this fear!
Test-Driven Development
TDD as a Design Approach
● Tests define up front what “works” means
● Programing by intention - write tests for what
code intends to do not what the code you just wrote
does.
● Focus on minimum set of required features
● Regular integration of small changes
● Evolutionary Design: Tests provide a safety
net for refactoring.
Red-Green-Refactor Cycle
How to Get to Green? Implement it!
Obvious
Implementation
code the real implementation, if
it's obvious and can quickly make
test pass, otherwise...
public int Sum(int x, int y)
{
return x + y;
}
How to Get to Green? Fake it
Fake it
hardcode constants to make test
pass, gradually generalize code
using variables
public int Fibonacci(int n)
{
if (n >= 1) return 1;
return 0;
}
How to Get to Green? Triangulate
Triangulate
figure out the behavior of an
algorithm by examining a couple
of test cases instead of just one.
public void TestSum()
{
Assert.AreEqual(4, Plus(3, 1));
Assert.AreEqual(7, Plus(4, 3));
}
Use TDD to Earn a Gift Card!
TDD is a great tool to use in solving the code challenges. E.g. Function takes a
Roman Numeral String and returns the Decimal value.
● Start with simple valid numbers I, III... up to more complex tests
● Incorporate tests for boundary conditions and invalid numbers
● With a set of tests you can easily refactor your solution.
VALID NUMBERS INVALID NUMBERS
I Boundary: Empty, 0, MMMM
III iii
IV IVIV, IIII, IIX, MXXXX
VI, XLIX, MMMDCCCLXXXVIII ABCDEF
A Great TDD Example!
● Bowling Kata - how to score a bowling
game.
● Eclipse and junit step-by-step presentation
on red - green - refactor to solve (butunclebob.
com/files/downloads/Bowling%20Game%20Kata.ppt)
Agile Architecture
● Collaborative Design
● Good coding Standards and Principles
Agile Architecture
Collaborative Design
● Emergent Design
○ Light Design Up Front (LDUF)
● Every team member contributes
● No command and control
Collaborative Design - payoff
http://martinfowler.com/bliki/DesignStaminaHypothesis.html
Standards and Principles
● Agree as a team
○ coding and naming conventions
○ toolset
■ Static Code Analysis, Test mocks, etc
○ best practices
● Avoid Technical Debt
● Follow well established principles and
patterns
Object Oriented Design Principles
S ingle Responsibilty
O pen/Closed
L iskov Substitution
I nterface Segregation
D ependency Inversion
The Single Responsibility Principle
● Every class should have a single responsibility, and that responsibility
should be entirely encapsulated by the class. All its services should be
narrowly aligned with that responsibility.
● Single Reason to Change
class Book {
function getTitle() {
return "A Great Book";
}
function getAuthor() {
return "John Doe";
}
function turnPage() {
// pointer to next page
}
function printCurrentPage() {
echo "current page content";
}
}
The Open/Closed Principle
● You should be able to extend a classes
behavior without modifying it
● Open for extension, but closed for
modification
public double Area(object[] shapes)
{
double area = 0;
foreach (var shape in shapes) {
if (shape is Rectangle) {
Rectangle rectangle = (Rectangle) shape;
area += rectangle.Width*rectangle.Height;
} else {
Circle circle = (Circle)shape;
area += circle.Radius * circle.Radius * Math.PI;
}
}
return area;
}
The Liskov Substitution Principle
● Derived classes must be substitutable for
their base classes
public class Rectangle {
private int width;
private int height;
// setters and getters
}
public class Square extends Rectangle {
public Square(int height, int width) {
setWidth(width);
setHeight(height);
}
}
The Interface Segregation Principle
● No client should be forced to depend on
methods it does not use
interface Worker {
void work();
void eat();
}
class HumanWorker implements Worker {
Public void work { /* do work stuff */ }
Public void eat { /* eat stuff */ }
}
class RobotWorker implements Worker {
Public void work { /* do work stuff */ }
Public void eat { /* ACK! I don't eat! */ }
}
interface Worker {
void work();
}
interface Eater {
void eat();
}
class HumanWorker implements Worker, Eater {
Public void work { /* do work stuff */ }
Public void eat { /* eat stuff */ }
}
class RobotWorker implements Worker {
Public void work { /* do work stuff */ }
}
The Dependency Inversion Principle
● High-level modules should not depend on
low-level modules. Both should depend on
abstractions.
● Abstractions should not depend on details.
Details should depend on abstractions.
class Worker {
private FileWriter fileWriter;
public Worker() {
fileWriter = new FileWriter();
}
}
class Worker {
private FileWriter fileWriter;
public Worker(FIleWriter writer) {
fileWriter = writer;
}
}
interface FileWriter {
// writer files or something
}
Object Orient Patterns
● Common Design Patterns
○ Strategy, Command, Decorator, Adapter, etc
● Enterprise Integration Patterns
Acknowledgements
Pair Programming:
● http://www.cs.pomona.edu/classes/cs121/supp/williams_prpgm.pdf
● http://collaboration.csc.ncsu.edu/laurie/Papers/ieeeSoftware.PDF
SOLID
● http://lostechies.com/derickbailey/2009/02/11/solid-development-principles-in-motivational-
pictures/
Content based on:
● SolutionsIQ CSD training slides
● http://en.wikipedia.org/wiki/Code_smell
● http://www.codeproject.com/Articles/5404/The-benefits-of-automated-unit-testing

Weitere ähnliche Inhalte

Was ist angesagt?

Agile Test Driven Development
Agile Test Driven DevelopmentAgile Test Driven Development
Agile Test Driven DevelopmentViraf Karai
 
TDD and Simple Design Workshop - Session 1 - March 2019
TDD and Simple Design Workshop - Session 1 - March 2019TDD and Simple Design Workshop - Session 1 - March 2019
TDD and Simple Design Workshop - Session 1 - March 2019Paulo Clavijo
 
Introduction to TDD (Test Driven development) - Ahmed Shreef
Introduction to TDD (Test Driven development) - Ahmed ShreefIntroduction to TDD (Test Driven development) - Ahmed Shreef
Introduction to TDD (Test Driven development) - Ahmed ShreefAhmed Shreef
 
TDD done right - tests immutable to refactor
TDD done right - tests immutable to refactorTDD done right - tests immutable to refactor
TDD done right - tests immutable to refactorGrzegorz Miejski
 
Project Management: Burn-Down Chart / OrangeHRM Project MOD (eng)
Project Management: Burn-Down Chart / OrangeHRM Project MOD (eng)Project Management: Burn-Down Chart / OrangeHRM Project MOD (eng)
Project Management: Burn-Down Chart / OrangeHRM Project MOD (eng)Anatoliy Okhotnikov
 
Refactoring Tips by Martin Fowler
Refactoring Tips by Martin FowlerRefactoring Tips by Martin Fowler
Refactoring Tips by Martin FowlerIgor Crvenov
 
Android Test Driven Development & Android Unit Testing
Android Test Driven Development & Android Unit TestingAndroid Test Driven Development & Android Unit Testing
Android Test Driven Development & Android Unit Testingmahmoud ramadan
 
TDD - Designing with Expectations, not Implementations
TDD - Designing with Expectations, not ImplementationsTDD - Designing with Expectations, not Implementations
TDD - Designing with Expectations, not ImplementationsHarshith Shetty
 
Refactoring - An Introduction
Refactoring - An IntroductionRefactoring - An Introduction
Refactoring - An IntroductionGiorgio Vespucci
 
Test driven development - Zombie proof your code
Test driven development - Zombie proof your codeTest driven development - Zombie proof your code
Test driven development - Zombie proof your codePascal Larocque
 
Tdd practices
Tdd practicesTdd practices
Tdd practicesaxykim00
 

Was ist angesagt? (20)

Agile Test Driven Development
Agile Test Driven DevelopmentAgile Test Driven Development
Agile Test Driven Development
 
TDD
TDDTDD
TDD
 
TDD and Simple Design Workshop - Session 1 - March 2019
TDD and Simple Design Workshop - Session 1 - March 2019TDD and Simple Design Workshop - Session 1 - March 2019
TDD and Simple Design Workshop - Session 1 - March 2019
 
Introduction to TDD (Test Driven development) - Ahmed Shreef
Introduction to TDD (Test Driven development) - Ahmed ShreefIntroduction to TDD (Test Driven development) - Ahmed Shreef
Introduction to TDD (Test Driven development) - Ahmed Shreef
 
TDD done right - tests immutable to refactor
TDD done right - tests immutable to refactorTDD done right - tests immutable to refactor
TDD done right - tests immutable to refactor
 
Project Management: Burn-Down Chart / OrangeHRM Project MOD (eng)
Project Management: Burn-Down Chart / OrangeHRM Project MOD (eng)Project Management: Burn-Down Chart / OrangeHRM Project MOD (eng)
Project Management: Burn-Down Chart / OrangeHRM Project MOD (eng)
 
Refactoring Tips by Martin Fowler
Refactoring Tips by Martin FowlerRefactoring Tips by Martin Fowler
Refactoring Tips by Martin Fowler
 
Test driven development
Test driven developmentTest driven development
Test driven development
 
Test driven development(tdd)
Test driven development(tdd)Test driven development(tdd)
Test driven development(tdd)
 
User story workflow (eng)
User story workflow (eng)User story workflow (eng)
User story workflow (eng)
 
Tech talks#6: Code Refactoring
Tech talks#6: Code RefactoringTech talks#6: Code Refactoring
Tech talks#6: Code Refactoring
 
Android Test Driven Development & Android Unit Testing
Android Test Driven Development & Android Unit TestingAndroid Test Driven Development & Android Unit Testing
Android Test Driven Development & Android Unit Testing
 
Tdd
TddTdd
Tdd
 
TDD refresher
TDD refresherTDD refresher
TDD refresher
 
TDD - Designing with Expectations, not Implementations
TDD - Designing with Expectations, not ImplementationsTDD - Designing with Expectations, not Implementations
TDD - Designing with Expectations, not Implementations
 
Refactoring - An Introduction
Refactoring - An IntroductionRefactoring - An Introduction
Refactoring - An Introduction
 
Making Strongly-typed NETCONF Usable
Making Strongly-typed NETCONF UsableMaking Strongly-typed NETCONF Usable
Making Strongly-typed NETCONF Usable
 
Test driven development - Zombie proof your code
Test driven development - Zombie proof your codeTest driven development - Zombie proof your code
Test driven development - Zombie proof your code
 
Tdd practices
Tdd practicesTdd practices
Tdd practices
 
TDD with RSpec
TDD with RSpecTDD with RSpec
TDD with RSpec
 

Ähnlich wie Keeping code clean

Indy meetup#7 effective unit-testing-mule
Indy meetup#7 effective unit-testing-muleIndy meetup#7 effective unit-testing-mule
Indy meetup#7 effective unit-testing-muleikram_ahamed
 
Test-Driven Development.pptx
Test-Driven Development.pptxTest-Driven Development.pptx
Test-Driven Development.pptxTomas561914
 
Enter the mind of an Agile Developer
Enter the mind of an Agile DeveloperEnter the mind of an Agile Developer
Enter the mind of an Agile DeveloperBSGAfrica
 
A la découverte des google/test (aka gtest)
A la découverte des google/test (aka gtest)A la découverte des google/test (aka gtest)
A la découverte des google/test (aka gtest)Thierry Gayet
 
TDD and Related Techniques for Non Developers (2012)
TDD and Related Techniques for Non Developers (2012)TDD and Related Techniques for Non Developers (2012)
TDD and Related Techniques for Non Developers (2012)Peter Kofler
 
VT.NET 20160411: An Intro to Test Driven Development (TDD)
VT.NET 20160411: An Intro to Test Driven Development (TDD)VT.NET 20160411: An Intro to Test Driven Development (TDD)
VT.NET 20160411: An Intro to Test Driven Development (TDD)Rob Hale
 
Working With Legacy Code
Working With Legacy CodeWorking With Legacy Code
Working With Legacy CodeAndrea Polci
 
Test Driven Development
Test Driven DevelopmentTest Driven Development
Test Driven Developmentnikhil sreeni
 
Test Driven Development Methodology and Philosophy
Test Driven Development Methodology and Philosophy Test Driven Development Methodology and Philosophy
Test Driven Development Methodology and Philosophy Vijay Kumbhar
 
Prashant technical practices-tdd for xebia event
Prashant   technical practices-tdd for xebia eventPrashant   technical practices-tdd for xebia event
Prashant technical practices-tdd for xebia eventXebia India
 
Test driven development v1.0
Test driven development v1.0Test driven development v1.0
Test driven development v1.0Ganesh Kondal
 
'Effective node.js development' by Viktor Turskyi at OdessaJS'2020
'Effective node.js development' by Viktor Turskyi at OdessaJS'2020'Effective node.js development' by Viktor Turskyi at OdessaJS'2020
'Effective node.js development' by Viktor Turskyi at OdessaJS'2020OdessaJS Conf
 
Mixing d ps building architecture on the cross cutting example
Mixing d ps building architecture on the cross cutting exampleMixing d ps building architecture on the cross cutting example
Mixing d ps building architecture on the cross cutting examplecorehard_by
 
QA Strategies for Testing Legacy Web Apps
QA Strategies for Testing Legacy Web AppsQA Strategies for Testing Legacy Web Apps
QA Strategies for Testing Legacy Web AppsRainforest QA
 
Software Design Principles and Best Practices - Satyajit Dey
Software Design Principles and Best Practices - Satyajit DeySoftware Design Principles and Best Practices - Satyajit Dey
Software Design Principles and Best Practices - Satyajit DeyCefalo
 

Ähnlich wie Keeping code clean (20)

Indy meetup#7 effective unit-testing-mule
Indy meetup#7 effective unit-testing-muleIndy meetup#7 effective unit-testing-mule
Indy meetup#7 effective unit-testing-mule
 
Usable Software Design
Usable Software DesignUsable Software Design
Usable Software Design
 
Test-Driven Development.pptx
Test-Driven Development.pptxTest-Driven Development.pptx
Test-Driven Development.pptx
 
Enter the mind of an Agile Developer
Enter the mind of an Agile DeveloperEnter the mind of an Agile Developer
Enter the mind of an Agile Developer
 
A la découverte des google/test (aka gtest)
A la découverte des google/test (aka gtest)A la découverte des google/test (aka gtest)
A la découverte des google/test (aka gtest)
 
Agile
AgileAgile
Agile
 
TDD and Related Techniques for Non Developers (2012)
TDD and Related Techniques for Non Developers (2012)TDD and Related Techniques for Non Developers (2012)
TDD and Related Techniques for Non Developers (2012)
 
VT.NET 20160411: An Intro to Test Driven Development (TDD)
VT.NET 20160411: An Intro to Test Driven Development (TDD)VT.NET 20160411: An Intro to Test Driven Development (TDD)
VT.NET 20160411: An Intro to Test Driven Development (TDD)
 
Working With Legacy Code
Working With Legacy CodeWorking With Legacy Code
Working With Legacy Code
 
Extreme programming (xp)
Extreme programming (xp)Extreme programming (xp)
Extreme programming (xp)
 
Test Driven Development
Test Driven DevelopmentTest Driven Development
Test Driven Development
 
Test Driven Development Methodology and Philosophy
Test Driven Development Methodology and Philosophy Test Driven Development Methodology and Philosophy
Test Driven Development Methodology and Philosophy
 
Introduction to Unit Tests and TDD
Introduction to Unit Tests and TDDIntroduction to Unit Tests and TDD
Introduction to Unit Tests and TDD
 
Prashant technical practices-tdd for xebia event
Prashant   technical practices-tdd for xebia eventPrashant   technical practices-tdd for xebia event
Prashant technical practices-tdd for xebia event
 
Ian Cooper webinar for DDD Iran: Kent beck style tdd seven years after
Ian Cooper webinar for DDD Iran: Kent beck style tdd   seven years afterIan Cooper webinar for DDD Iran: Kent beck style tdd   seven years after
Ian Cooper webinar for DDD Iran: Kent beck style tdd seven years after
 
Test driven development v1.0
Test driven development v1.0Test driven development v1.0
Test driven development v1.0
 
'Effective node.js development' by Viktor Turskyi at OdessaJS'2020
'Effective node.js development' by Viktor Turskyi at OdessaJS'2020'Effective node.js development' by Viktor Turskyi at OdessaJS'2020
'Effective node.js development' by Viktor Turskyi at OdessaJS'2020
 
Mixing d ps building architecture on the cross cutting example
Mixing d ps building architecture on the cross cutting exampleMixing d ps building architecture on the cross cutting example
Mixing d ps building architecture on the cross cutting example
 
QA Strategies for Testing Legacy Web Apps
QA Strategies for Testing Legacy Web AppsQA Strategies for Testing Legacy Web Apps
QA Strategies for Testing Legacy Web Apps
 
Software Design Principles and Best Practices - Satyajit Dey
Software Design Principles and Best Practices - Satyajit DeySoftware Design Principles and Best Practices - Satyajit Dey
Software Design Principles and Best Practices - Satyajit Dey
 

Kürzlich hochgeladen

Odoo 14 - eLearning Module In Odoo 14 Enterprise
Odoo 14 - eLearning Module In Odoo 14 EnterpriseOdoo 14 - eLearning Module In Odoo 14 Enterprise
Odoo 14 - eLearning Module In Odoo 14 Enterprisepreethippts
 
MYjobs Presentation Django-based project
MYjobs Presentation Django-based projectMYjobs Presentation Django-based project
MYjobs Presentation Django-based projectAnoyGreter
 
Software Project Health Check: Best Practices and Techniques for Your Product...
Software Project Health Check: Best Practices and Techniques for Your Product...Software Project Health Check: Best Practices and Techniques for Your Product...
Software Project Health Check: Best Practices and Techniques for Your Product...Velvetech LLC
 
Intelligent Home Wi-Fi Solutions | ThinkPalm
Intelligent Home Wi-Fi Solutions | ThinkPalmIntelligent Home Wi-Fi Solutions | ThinkPalm
Intelligent Home Wi-Fi Solutions | ThinkPalmSujith Sukumaran
 
Call Us🔝>༒+91-9711147426⇛Call In girls karol bagh (Delhi)
Call Us🔝>༒+91-9711147426⇛Call In girls karol bagh (Delhi)Call Us🔝>༒+91-9711147426⇛Call In girls karol bagh (Delhi)
Call Us🔝>༒+91-9711147426⇛Call In girls karol bagh (Delhi)jennyeacort
 
Balasore Best It Company|| Top 10 IT Company || Balasore Software company Odisha
Balasore Best It Company|| Top 10 IT Company || Balasore Software company OdishaBalasore Best It Company|| Top 10 IT Company || Balasore Software company Odisha
Balasore Best It Company|| Top 10 IT Company || Balasore Software company Odishasmiwainfosol
 
Global Identity Enrolment and Verification Pro Solution - Cizo Technology Ser...
Global Identity Enrolment and Verification Pro Solution - Cizo Technology Ser...Global Identity Enrolment and Verification Pro Solution - Cizo Technology Ser...
Global Identity Enrolment and Verification Pro Solution - Cizo Technology Ser...Cizo Technology Services
 
EY_Graph Database Powered Sustainability
EY_Graph Database Powered SustainabilityEY_Graph Database Powered Sustainability
EY_Graph Database Powered SustainabilityNeo4j
 
Ahmed Motair CV April 2024 (Senior SW Developer)
Ahmed Motair CV April 2024 (Senior SW Developer)Ahmed Motair CV April 2024 (Senior SW Developer)
Ahmed Motair CV April 2024 (Senior SW Developer)Ahmed Mater
 
Building a General PDE Solving Framework with Symbolic-Numeric Scientific Mac...
Building a General PDE Solving Framework with Symbolic-Numeric Scientific Mac...Building a General PDE Solving Framework with Symbolic-Numeric Scientific Mac...
Building a General PDE Solving Framework with Symbolic-Numeric Scientific Mac...stazi3110
 
React Server Component in Next.js by Hanief Utama
React Server Component in Next.js by Hanief UtamaReact Server Component in Next.js by Hanief Utama
React Server Component in Next.js by Hanief UtamaHanief Utama
 
SpotFlow: Tracking Method Calls and States at Runtime
SpotFlow: Tracking Method Calls and States at RuntimeSpotFlow: Tracking Method Calls and States at Runtime
SpotFlow: Tracking Method Calls and States at Runtimeandrehoraa
 
What are the key points to focus on before starting to learn ETL Development....
What are the key points to focus on before starting to learn ETL Development....What are the key points to focus on before starting to learn ETL Development....
What are the key points to focus on before starting to learn ETL Development....kzayra69
 
Buds n Tech IT Solutions: Top-Notch Web Services in Noida
Buds n Tech IT Solutions: Top-Notch Web Services in NoidaBuds n Tech IT Solutions: Top-Notch Web Services in Noida
Buds n Tech IT Solutions: Top-Notch Web Services in Noidabntitsolutionsrishis
 
BATTLEFIELD ORM: TIPS, TACTICS AND STRATEGIES FOR CONQUERING YOUR DATABASE
BATTLEFIELD ORM: TIPS, TACTICS AND STRATEGIES FOR CONQUERING YOUR DATABASEBATTLEFIELD ORM: TIPS, TACTICS AND STRATEGIES FOR CONQUERING YOUR DATABASE
BATTLEFIELD ORM: TIPS, TACTICS AND STRATEGIES FOR CONQUERING YOUR DATABASEOrtus Solutions, Corp
 
Cloud Data Center Network Construction - IEEE
Cloud Data Center Network Construction - IEEECloud Data Center Network Construction - IEEE
Cloud Data Center Network Construction - IEEEVICTOR MAESTRE RAMIREZ
 
Automate your Kamailio Test Calls - Kamailio World 2024
Automate your Kamailio Test Calls - Kamailio World 2024Automate your Kamailio Test Calls - Kamailio World 2024
Automate your Kamailio Test Calls - Kamailio World 2024Andreas Granig
 
Tech Tuesday - Mastering Time Management Unlock the Power of OnePlan's Timesh...
Tech Tuesday - Mastering Time Management Unlock the Power of OnePlan's Timesh...Tech Tuesday - Mastering Time Management Unlock the Power of OnePlan's Timesh...
Tech Tuesday - Mastering Time Management Unlock the Power of OnePlan's Timesh...OnePlan Solutions
 
Alluxio Monthly Webinar | Cloud-Native Model Training on Distributed Data
Alluxio Monthly Webinar | Cloud-Native Model Training on Distributed DataAlluxio Monthly Webinar | Cloud-Native Model Training on Distributed Data
Alluxio Monthly Webinar | Cloud-Native Model Training on Distributed DataAlluxio, Inc.
 
Recruitment Management Software Benefits (Infographic)
Recruitment Management Software Benefits (Infographic)Recruitment Management Software Benefits (Infographic)
Recruitment Management Software Benefits (Infographic)Hr365.us smith
 

Kürzlich hochgeladen (20)

Odoo 14 - eLearning Module In Odoo 14 Enterprise
Odoo 14 - eLearning Module In Odoo 14 EnterpriseOdoo 14 - eLearning Module In Odoo 14 Enterprise
Odoo 14 - eLearning Module In Odoo 14 Enterprise
 
MYjobs Presentation Django-based project
MYjobs Presentation Django-based projectMYjobs Presentation Django-based project
MYjobs Presentation Django-based project
 
Software Project Health Check: Best Practices and Techniques for Your Product...
Software Project Health Check: Best Practices and Techniques for Your Product...Software Project Health Check: Best Practices and Techniques for Your Product...
Software Project Health Check: Best Practices and Techniques for Your Product...
 
Intelligent Home Wi-Fi Solutions | ThinkPalm
Intelligent Home Wi-Fi Solutions | ThinkPalmIntelligent Home Wi-Fi Solutions | ThinkPalm
Intelligent Home Wi-Fi Solutions | ThinkPalm
 
Call Us🔝>༒+91-9711147426⇛Call In girls karol bagh (Delhi)
Call Us🔝>༒+91-9711147426⇛Call In girls karol bagh (Delhi)Call Us🔝>༒+91-9711147426⇛Call In girls karol bagh (Delhi)
Call Us🔝>༒+91-9711147426⇛Call In girls karol bagh (Delhi)
 
Balasore Best It Company|| Top 10 IT Company || Balasore Software company Odisha
Balasore Best It Company|| Top 10 IT Company || Balasore Software company OdishaBalasore Best It Company|| Top 10 IT Company || Balasore Software company Odisha
Balasore Best It Company|| Top 10 IT Company || Balasore Software company Odisha
 
Global Identity Enrolment and Verification Pro Solution - Cizo Technology Ser...
Global Identity Enrolment and Verification Pro Solution - Cizo Technology Ser...Global Identity Enrolment and Verification Pro Solution - Cizo Technology Ser...
Global Identity Enrolment and Verification Pro Solution - Cizo Technology Ser...
 
EY_Graph Database Powered Sustainability
EY_Graph Database Powered SustainabilityEY_Graph Database Powered Sustainability
EY_Graph Database Powered Sustainability
 
Ahmed Motair CV April 2024 (Senior SW Developer)
Ahmed Motair CV April 2024 (Senior SW Developer)Ahmed Motair CV April 2024 (Senior SW Developer)
Ahmed Motair CV April 2024 (Senior SW Developer)
 
Building a General PDE Solving Framework with Symbolic-Numeric Scientific Mac...
Building a General PDE Solving Framework with Symbolic-Numeric Scientific Mac...Building a General PDE Solving Framework with Symbolic-Numeric Scientific Mac...
Building a General PDE Solving Framework with Symbolic-Numeric Scientific Mac...
 
React Server Component in Next.js by Hanief Utama
React Server Component in Next.js by Hanief UtamaReact Server Component in Next.js by Hanief Utama
React Server Component in Next.js by Hanief Utama
 
SpotFlow: Tracking Method Calls and States at Runtime
SpotFlow: Tracking Method Calls and States at RuntimeSpotFlow: Tracking Method Calls and States at Runtime
SpotFlow: Tracking Method Calls and States at Runtime
 
What are the key points to focus on before starting to learn ETL Development....
What are the key points to focus on before starting to learn ETL Development....What are the key points to focus on before starting to learn ETL Development....
What are the key points to focus on before starting to learn ETL Development....
 
Buds n Tech IT Solutions: Top-Notch Web Services in Noida
Buds n Tech IT Solutions: Top-Notch Web Services in NoidaBuds n Tech IT Solutions: Top-Notch Web Services in Noida
Buds n Tech IT Solutions: Top-Notch Web Services in Noida
 
BATTLEFIELD ORM: TIPS, TACTICS AND STRATEGIES FOR CONQUERING YOUR DATABASE
BATTLEFIELD ORM: TIPS, TACTICS AND STRATEGIES FOR CONQUERING YOUR DATABASEBATTLEFIELD ORM: TIPS, TACTICS AND STRATEGIES FOR CONQUERING YOUR DATABASE
BATTLEFIELD ORM: TIPS, TACTICS AND STRATEGIES FOR CONQUERING YOUR DATABASE
 
Cloud Data Center Network Construction - IEEE
Cloud Data Center Network Construction - IEEECloud Data Center Network Construction - IEEE
Cloud Data Center Network Construction - IEEE
 
Automate your Kamailio Test Calls - Kamailio World 2024
Automate your Kamailio Test Calls - Kamailio World 2024Automate your Kamailio Test Calls - Kamailio World 2024
Automate your Kamailio Test Calls - Kamailio World 2024
 
Tech Tuesday - Mastering Time Management Unlock the Power of OnePlan's Timesh...
Tech Tuesday - Mastering Time Management Unlock the Power of OnePlan's Timesh...Tech Tuesday - Mastering Time Management Unlock the Power of OnePlan's Timesh...
Tech Tuesday - Mastering Time Management Unlock the Power of OnePlan's Timesh...
 
Alluxio Monthly Webinar | Cloud-Native Model Training on Distributed Data
Alluxio Monthly Webinar | Cloud-Native Model Training on Distributed DataAlluxio Monthly Webinar | Cloud-Native Model Training on Distributed Data
Alluxio Monthly Webinar | Cloud-Native Model Training on Distributed Data
 
Recruitment Management Software Benefits (Infographic)
Recruitment Management Software Benefits (Infographic)Recruitment Management Software Benefits (Infographic)
Recruitment Management Software Benefits (Infographic)
 

Keeping code clean

  • 1. Keeping Code Clean Agile tools and practices for better code
  • 2. Topics ● Pair Programming ● Automated Unit Testing ● Refactoring ● Test-Driven Development ● Agile Architecture
  • 5. ● Continuous Code Review ● Better Design w/ Less Code ● Faster Problem Solving ● More People Familiar w/ System ● Team Grows Closer Pair Programming - Benefits
  • 7. Pair Programming - Evidence Williams 2000 ● Efforts +15%, Schedule -43% Baheti 2002 ● Effort +2%, Schedule -49% Ciokowlski 2002 ● Effort +9%, Schedule -46%
  • 9. What is Automated Unit Testing? Use of special software to control the execution of unit tests and the comparison of actual outcomes with predicted outcomes. To get full benefit run as part of the build process and schedule to run automatically once or twice a day.
  • 10. Automated Unit Test Suite Benefits ● Unit tests find problems early in the development cycle ● Developers will be less afraid to change code ● Development process becomes more flexible ● Easier for a developer to take over code they are unfamiliar with (improves “Truck Factor”) ● Reduces need for manual testing ● Software development becomes more testable and repeatable
  • 11. What is a Unit Test Case? ● A test for a single unit of functionality ● Each method tests a specific bit of functionality ● Automated by the test-runner framework
  • 12. AAA Test Structure ● Structure: ○ Arrange ○ Act ○ Assert ● Benefits: ○ Readable ○ Consistent public class SalesTaxTest { private SalesTax unit; @Test public void TestCalculate() { unit = new SalesTax(); // ARRANGE double tax = unit.Calculate(10); // ACT Assert.assertEquals(tax, 0.9); // ASSERT } }
  • 13. Unit Testing Best Practices ● Test simple stuff first ● Get it working - then test boundaries/exceptions ● Use assert ● Keep tests small & understandable ● Make test method names descriptive ● Keep tests independent of each other ● Avoid System.out messages ● Don’t repeat tests! Test once and trust it.
  • 14. Test Doubles ● Stand in for a collaborating object e.g. database, webservice ● Create test independence ● Make tests run faster ● Types of Doubles ○ Fakes: working implementation e.g.fake web service ○ Mocks: preprogrammed with expectations ○ Stubs: provide canned answers to the test’s calls
  • 16. Refactoring ● What is refactoring? ● Why refactor? ● When to refactor?
  • 17. What is Refactoring? “A change to the system that leaves its behavior unchanged, but enhances some non-functional quality - simplicity, flexibility, understandability, performance” -- Kent Beck, Extreme Programing Explained (p. 179) “A change made to the internal structure of software to make it easier to understand and cheaper to modify without changing its observable behavior.” -- Martin Fowler, Refactoring (p. 53)
  • 18. Why Refactor the Code? ● Prevent “design decay” ● Clean up messes ● Simplify ● Increase readability / understandability ● Find bugs ● Reduce debugging time ● Build in what we learn about the application ● It’s part of the creative process
  • 19. When to Refactor ● Code reviews / TDD cycle ● Rule of three ○ cut & paste. Third time copying? Now is the time to generalize and move this to a new procedure. ● When you: ○ add functionality ○ learn something about the code ○ identify a code smell
  • 20. What is a Code Smell? ● any symptom in the code that possibly indicates a deeper problem. ● not bugs - but indicate weaknesses in design that may be slowing down development or increasing the risk of bugs or failures in the future.
  • 21. Code Smells (1/2) ● Duplicated code: near-identical code in multiple places ● Long method: a too large method/function/procedure ● Large class: a class that has grown too large. ● Too many parameters: decreases readability/quality. ● Identifier names are too short or excessively long ● Complex conditionals: branches that check lots of unrelated conditions and edge cases that don't seem to capture the meaning of a block of code.
  • 22. Code Smells (2/2) ● Comments - refactor so these are no longer needed! ● Feature envy: excessive use of another class’ methods ● Inappropriate intimacy: a class that has dependencies on implementation details of another class. ● Lazy class / Freeloader: a class that does too little. ● Contrived complexity: simpler design would suffice. ● Excessive use of literals (use named constants)
  • 23. Why Developers Resist Refactoring ● Lack of understanding ● Short-term focus ● Not paid for overhead tasks like refactoring ● Fear of breaking current program Use TDD to overcome this fear!
  • 25. TDD as a Design Approach ● Tests define up front what “works” means ● Programing by intention - write tests for what code intends to do not what the code you just wrote does. ● Focus on minimum set of required features ● Regular integration of small changes ● Evolutionary Design: Tests provide a safety net for refactoring.
  • 27. How to Get to Green? Implement it! Obvious Implementation code the real implementation, if it's obvious and can quickly make test pass, otherwise... public int Sum(int x, int y) { return x + y; }
  • 28. How to Get to Green? Fake it Fake it hardcode constants to make test pass, gradually generalize code using variables public int Fibonacci(int n) { if (n >= 1) return 1; return 0; }
  • 29. How to Get to Green? Triangulate Triangulate figure out the behavior of an algorithm by examining a couple of test cases instead of just one. public void TestSum() { Assert.AreEqual(4, Plus(3, 1)); Assert.AreEqual(7, Plus(4, 3)); }
  • 30. Use TDD to Earn a Gift Card! TDD is a great tool to use in solving the code challenges. E.g. Function takes a Roman Numeral String and returns the Decimal value. ● Start with simple valid numbers I, III... up to more complex tests ● Incorporate tests for boundary conditions and invalid numbers ● With a set of tests you can easily refactor your solution. VALID NUMBERS INVALID NUMBERS I Boundary: Empty, 0, MMMM III iii IV IVIV, IIII, IIX, MXXXX VI, XLIX, MMMDCCCLXXXVIII ABCDEF
  • 31. A Great TDD Example! ● Bowling Kata - how to score a bowling game. ● Eclipse and junit step-by-step presentation on red - green - refactor to solve (butunclebob. com/files/downloads/Bowling%20Game%20Kata.ppt)
  • 33. ● Collaborative Design ● Good coding Standards and Principles Agile Architecture
  • 34. Collaborative Design ● Emergent Design ○ Light Design Up Front (LDUF) ● Every team member contributes ● No command and control
  • 35. Collaborative Design - payoff http://martinfowler.com/bliki/DesignStaminaHypothesis.html
  • 36. Standards and Principles ● Agree as a team ○ coding and naming conventions ○ toolset ■ Static Code Analysis, Test mocks, etc ○ best practices ● Avoid Technical Debt ● Follow well established principles and patterns
  • 37. Object Oriented Design Principles S ingle Responsibilty O pen/Closed L iskov Substitution I nterface Segregation D ependency Inversion
  • 38.
  • 39. The Single Responsibility Principle ● Every class should have a single responsibility, and that responsibility should be entirely encapsulated by the class. All its services should be narrowly aligned with that responsibility. ● Single Reason to Change
  • 40. class Book { function getTitle() { return "A Great Book"; } function getAuthor() { return "John Doe"; } function turnPage() { // pointer to next page } function printCurrentPage() { echo "current page content"; } }
  • 41.
  • 42. The Open/Closed Principle ● You should be able to extend a classes behavior without modifying it ● Open for extension, but closed for modification
  • 43. public double Area(object[] shapes) { double area = 0; foreach (var shape in shapes) { if (shape is Rectangle) { Rectangle rectangle = (Rectangle) shape; area += rectangle.Width*rectangle.Height; } else { Circle circle = (Circle)shape; area += circle.Radius * circle.Radius * Math.PI; } } return area; }
  • 44.
  • 45. The Liskov Substitution Principle ● Derived classes must be substitutable for their base classes
  • 46. public class Rectangle { private int width; private int height; // setters and getters } public class Square extends Rectangle { public Square(int height, int width) { setWidth(width); setHeight(height); } }
  • 47.
  • 48. The Interface Segregation Principle ● No client should be forced to depend on methods it does not use
  • 49. interface Worker { void work(); void eat(); } class HumanWorker implements Worker { Public void work { /* do work stuff */ } Public void eat { /* eat stuff */ } } class RobotWorker implements Worker { Public void work { /* do work stuff */ } Public void eat { /* ACK! I don't eat! */ } } interface Worker { void work(); } interface Eater { void eat(); } class HumanWorker implements Worker, Eater { Public void work { /* do work stuff */ } Public void eat { /* eat stuff */ } } class RobotWorker implements Worker { Public void work { /* do work stuff */ } }
  • 50.
  • 51. The Dependency Inversion Principle ● High-level modules should not depend on low-level modules. Both should depend on abstractions. ● Abstractions should not depend on details. Details should depend on abstractions.
  • 52. class Worker { private FileWriter fileWriter; public Worker() { fileWriter = new FileWriter(); } } class Worker { private FileWriter fileWriter; public Worker(FIleWriter writer) { fileWriter = writer; } } interface FileWriter { // writer files or something }
  • 53. Object Orient Patterns ● Common Design Patterns ○ Strategy, Command, Decorator, Adapter, etc ● Enterprise Integration Patterns
  • 54. Acknowledgements Pair Programming: ● http://www.cs.pomona.edu/classes/cs121/supp/williams_prpgm.pdf ● http://collaboration.csc.ncsu.edu/laurie/Papers/ieeeSoftware.PDF SOLID ● http://lostechies.com/derickbailey/2009/02/11/solid-development-principles-in-motivational- pictures/ Content based on: ● SolutionsIQ CSD training slides ● http://en.wikipedia.org/wiki/Code_smell ● http://www.codeproject.com/Articles/5404/The-benefits-of-automated-unit-testing