SlideShare a Scribd company logo
Improving the Quality of
Existing Software
Steve Smith
Founder, DevIQ
@ardalis | ardalis.com
My Pluralsight Courses
Software Rots
Technical Debt
• Low quality code and shortcuts in our applications
• Technical debt, like real debt, has direct cost to pay off as well as interest
http://deviq.com/technical-debt/
http://www.jimhighsmith.com/
Preventive Maintenance
• Refactoring
• Eliminate Duplication
• Simplify Design
• AutomatedTests
• Verify correctness
• Avoid regressions
• Increase Confidence
When should you refactor?
• While delivering value
“
”
You don’t need permission to practice basic hygiene
when you write software.
http://ardalis.com/when-should-you-refactor/
Make cleaning up your code something you do as part of writing code.
Refactoring Should Not Change System
Behavior
The Refactoring Process
• Verify existing behavior
• Write CharacterizationTests if none exist
• Find test points
• Break dependencies
• Apply Refactoring
• Confirm existing behavior is preserved
CharacterizationTests
Process
1. Write a test you know will fail
2. Use the output of the failing test to determine the existing behavior to
assert
3. Update the test with the new value/behavior
4. Run the test again – it should now pass
S O L I DPrinciples
http://flickr.com/photos/kevinkemmerer/2772526725/
Principles of OO Design
0. Don’t RepeatYourself (DRY)
1. Single Responsibility
2. Open/Closed
3. Liskov Substitution
4. Interface Segregation
5. Dependency Inversion
Don’t Repeat
RepeatYourself
• Duplication in logic calls for abstraction
• Duplication in process calls for automation
Common Refactorings
• Replace Magic Number/String
• Parameterize Method
• Pull Up Field
• Pull Up Method
• Replace Conditional With Polymorphism
• Introduce Method
Common Source of Repetition: Role Checks
if(user.IsInRole(“Admins”)
{
// allow access to resource
}
// favor privileges over role checks
// ardalis.com/Favor-Privileges-over-Role-Checks
var priv = new ContentPrivilege(user, article);
if(priv.CanEdit())
{
// allow access
}
Visual Studio Code Clones
• Find similar blocks of code in your projects/solution
• Can detect matches that are similar but vary in small ways (like variable
names)
• Available inVS2015 Premium and Ultimate
Single Responsibility Principle
The Single Responsibility Principle states that every object should have a single
responsibility, and that responsibility should be entirely encapsulated by the
class.
Wikipedia
There should never be more than one reason for a class to change.
Robert C. “Uncle Bob” Martin
What is a responsibility?
“My CustomerManager class is only responsible for
anything to do with a Customer.That follows SRP, right?”
Examples of Responsibilities
• Persistence
• Validation
• Notification
• Error Handling
• Logging
• Class Selection / Construction
• Formatting
• Parsing
• Mapping
Dependency and Coupling
• Excessive coupling makes changing legacy software difficult
• Breaking apart responsibilities and dependencies is a large part of working
with existing code
Common Refactorings
• Extract Class
• Extract Method
• Move Method
Heuristics and Code Smells
• Visual Studio Metrics
Cyclomatic Complexity
https://en.wikipedia.org/wiki/Cyclomatic_complexity
Keep
Cyclomatic Complexity
under 10
for every method
Code Smell: Regions
More on Regions: http://ardalis.com/regional-differences
Open / Closed Principle
The Open / Closed Principle states that software entities (classes, modules,
functions, etc.) should be open for extension, but closed for modification.
Wikipedia
Open / Closed Principle
Open to Extension
New behavior can be added in the future
Closed to Modification
Changes to source or binary code are not required
Dr. Bertrand Meyer originated the OCP term in his 1988 book, ObjectOrientedSoftwareConstruction
Common Refactorings
• Extract Interface / Apply Strategy Pattern
• Parameterize Method
• FormTemplate Method
OCP Fail
OCP OK
OCP Fail
public bool IsSpecialCustomer(Customer c)
{
if(c.Country == “US” && c.Balance < 50) return false;
if(c.Country == “DE” && c.Balance < 25) return false;
if(c.Country == “UK” && c.Balance < 35) return false;
if(c.Country == “FR” && c.Balance < 27) return false;
if(c.Country == “BG” && c.Balance < 29) return false;
if(c.Age < 18 || c.Age > 65) return false;
if(c.Income < 50000 && c.Age < 30) return false;
return true;
}
OCP OK
private IEnumerable<ICustomerRule> _rules;
public bool IsSpecialCustomer(Customer customer)
{
foreach(var rule in _rules)
{
if(rule.Evaluate(customer) == false) return false;
}
return true;
}
Liskov Substitution Principle
The Liskov Substitution Principle states that Subtypes must be substitutable for
their base types.
Agile Principles, Patterns, and Practices in C#
Named for Barbara Liskov, who first described the principle in 1988.
Common Refactorings
• Collapse Hierarchy
• Pull Up / Push Down Field
• Pull Up / Push Down Method
Liskov Substitution Fail
foreach(var employee in employees)
{
if(employee is Manager)
{
Helpers.PrintManager(employee as Manager);
break;
}
Helpers.PrintEmployee(employee);
}
Liskov Substitution OK
foreach(var employee in employees)
{
employee.Print();
// or
Helpers.PrintEmployee(employee);
}
Nulls Break Polymorphism
foreach(var employee in employees)
{
if(employee == null)
{
// print not found message
break;
}
Helpers.PrintEmployee(employee);
} http://ardalis.com/nulls-break-polymorphism
Interface Segregation Principle
The Interface Segregation Principle states that Clients should not be
forced to depend on methods they do not use.
Agile Principles, Patterns, and Practices in C#
Corollary:
Prefer small, cohesive interfaces to “fat” interfaces
Common Refactorings
• Extract Interface
Keep Interfaces Small and Focused
Membership Provider
ISP Fail (sometimes)
public IRepository<T>
{
T GetById(int id);
IEnumerable<T> List();
void Create(T item);
void Update(T item);
void Delete(T item);
}
ISP OK (i.e. to support CQRS)
public IRepository<T> : IReadRepository<T>,
IWriteRepository<T>
{ }
public IReadRepository<T>
{
T GetById(int id);
IEnumerable<T> List();
}
public IWriteRepository<T>
void Create(T item);
void Update(T item);
void Delete(T item);
}
Existing implementations of
IRepository<T> are
unaffected by pulling out
smaller interfaces!
No existing code breaks!
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.
Agile Principles, Patterns, and Practices in C#
Dependency Inversion Principle
• Depend on Abstractions
• Interfaces, not concrete types
• Inject Dependencies into Classes
• Structure Solution so Dependencies FlowToward Core
• Onion Architecture (a.k.a. Ports and Adapters, a.k.a. Hexagonal Architecture)
DIP Architecture (aka Ports and Adapters)
Common Dependencies
• Framework
• Third Party Libraries
• Database
• File System
• Email
• Web Services
• System Resources (Clock)
• Configuration
• The new Keyword
• Static methods
• Thread.Sleep
• Random
See also responsibilities:
• Persistence
• Validation
• Notification
• Error Handling
• Logging
• Class Selection /
Construction
• Formatting
• Parsing
• Mapping
Common Refactorings
• Extract Class
• Extract Interface / Apply Strategy Pattern
• Extract Method
• Introduce Service Locator / Container
DIP Fail
Hidden Dependencies
• Checkout Depends on an available SMTP server, but the class doesn’t reflect
this
• Follow the Explicit Dependencies Principle
• http://deviq.com/explicit-dependencies-principle/
Some Improvement (Façade)
DIP OK (Strategy Pattern / DI)
DIP OK (Strategy Pattern / DI)
Improving Quality Across the Industry
Self-Improvement and Quality
• How fast can you produce:
• Code you believe to be of high quality
• Code that maybe gets the job done, but you believe to be of low quality
• Which one can you produce more quickly?
• Why?
• How can we develop our skills and our tools so that building quality is
natural and easier than not doing so?
0
2
4
6
8
10
12
14
16
Week 1 Week 2 Week 3 Week 4 Week 5 Week 6 Week 7 Week 8 Week 9
User Stories Completed
High Quality Low Quality
0
2
4
6
8
10
12
14
16
18
20
Week 1 Week 2 Week 3 Week 4 Week 5 Week 6 Week 7 Week 8 Week 9
User Stories Completed
High Quality Low Quality
Summary
•Maintain / Improve Application Code
•Follow DRY/SOLID Principles
•Use CharacterizationTests to “fix” behavior
•Apply Common Refactorings
•Re-runTestsAfter (and during) Refactorings
•Be Explicit About Class Dependencies
•Train and Practice toWrite Better Code Faster
Learn More
• DevIQ.com
• Ardalis.com
• Twitter: @ardalis
• Pluralsight:
• SOLID Principles of OO Design
• N-TierArchitecture in C#
• Refactoring Fundamentals
• Domain-Driven Design Fundamentals
• Design Pattern Library
• Pair Programming
• New Coworking Space in Hudson,Ohio
• Private offices / Flex desk spaces
• Fiber internet
• Complimentary coffee / tea / water
• Great development community
• @techhubhudson
• Website online soon
Tech Hub Hudson
• Includes images like the ones in this presentation
• Kickstarter Successful!
• Available November 2016
• Order now:
store.DevIQ.com
2017 Software Craftsmanship Calendar
Books
 Refactoring http://amzn.to/110tscA
 Refactoring to Patterns http://amzn.to/Vq5Rj2
 Working Effectively with Legacy Code http://amzn.to/VFFYbn
 Code Complete http://amzn.to/Vq5YLv
 Clean Code http://amzn.to/YjUDI0

More Related Content

What's hot

Selenium + Specflow
Selenium + SpecflowSelenium + Specflow
Selenium + Specflow
cromwellryan
 
Working Effectively With Legacy Code
Working Effectively With Legacy CodeWorking Effectively With Legacy Code
Working Effectively With Legacy Code
Excella
 
Power-Up Your Test Suite with OLE Automation by Joshua Russell
Power-Up Your Test Suite with OLE Automation by Joshua RussellPower-Up Your Test Suite with OLE Automation by Joshua Russell
Power-Up Your Test Suite with OLE Automation by Joshua Russell
QA or the Highway
 
Automated Acceptance Tests & Tool choice
Automated Acceptance Tests & Tool choiceAutomated Acceptance Tests & Tool choice
Automated Acceptance Tests & Tool choice
toddbr
 
Getting Ahead of Delivery Issues with Deep SDLC Analysis by Donald Belcham
Getting Ahead of Delivery Issues with Deep SDLC Analysis by Donald BelchamGetting Ahead of Delivery Issues with Deep SDLC Analysis by Donald Belcham
Getting Ahead of Delivery Issues with Deep SDLC Analysis by Donald Belcham
.NET Conf UY
 
Inside Behavior Driven Development
Inside Behavior Driven DevelopmentInside Behavior Driven Development
Inside Behavior Driven Development
Camille Bell
 
Selenium Frameworks
Selenium FrameworksSelenium Frameworks
Selenium Frameworks
Dave Haeffner
 
Tech io spa_angularjs_20130814_v0.9.5
Tech io spa_angularjs_20130814_v0.9.5Tech io spa_angularjs_20130814_v0.9.5
Tech io spa_angularjs_20130814_v0.9.5
Ganesh Kondal
 
Getting Started with Selenium
Getting Started with SeleniumGetting Started with Selenium
Getting Started with Selenium
Dave Haeffner
 
How To Use Selenium Successfully
How To Use Selenium SuccessfullyHow To Use Selenium Successfully
How To Use Selenium Successfully
Dave Haeffner
 
Promoting Agility with Running Tested Features - Lightening Talk
Promoting Agility with Running Tested Features - Lightening TalkPromoting Agility with Running Tested Features - Lightening Talk
Promoting Agility with Running Tested Features - Lightening Talk
Camille Bell
 
Testing for Agility: Bringing Testing into Everything
Testing for Agility: Bringing Testing into EverythingTesting for Agility: Bringing Testing into Everything
Testing for Agility: Bringing Testing into Everything
Camille Bell
 
Testable requirements
Testable requirementsTestable requirements
Testable requirements
Wyn B. Van Devanter
 
How To Use Selenium Successfully
How To Use Selenium SuccessfullyHow To Use Selenium Successfully
How To Use Selenium Successfully
Dave Haeffner
 
Growing Manual Testers into Automators
Growing Manual Testers into AutomatorsGrowing Manual Testers into Automators
Growing Manual Testers into Automators
Camille Bell
 
Acceptance Test Driven Development With Spec Flow And Friends
Acceptance Test Driven Development With Spec Flow And FriendsAcceptance Test Driven Development With Spec Flow And Friends
Acceptance Test Driven Development With Spec Flow And Friends
Christopher Bartling
 
Testing Java EE apps with Arquillian
Testing Java EE apps with ArquillianTesting Java EE apps with Arquillian
Testing Java EE apps with Arquillian
Ivan Ivanov
 
Test and Behaviour Driven Development (TDD/BDD)
Test and Behaviour Driven Development (TDD/BDD)Test and Behaviour Driven Development (TDD/BDD)
Test and Behaviour Driven Development (TDD/BDD)
Lars Thorup
 
Bdd and spec flow
Bdd and spec flowBdd and spec flow
Bdd and spec flow
Charles Nurse
 
Adapting Agility: Getting your Agile Transformation Unstuck
Adapting Agility: Getting your Agile Transformation UnstuckAdapting Agility: Getting your Agile Transformation Unstuck
Adapting Agility: Getting your Agile Transformation Unstuck
Camille Bell
 

What's hot (20)

Selenium + Specflow
Selenium + SpecflowSelenium + Specflow
Selenium + Specflow
 
Working Effectively With Legacy Code
Working Effectively With Legacy CodeWorking Effectively With Legacy Code
Working Effectively With Legacy Code
 
Power-Up Your Test Suite with OLE Automation by Joshua Russell
Power-Up Your Test Suite with OLE Automation by Joshua RussellPower-Up Your Test Suite with OLE Automation by Joshua Russell
Power-Up Your Test Suite with OLE Automation by Joshua Russell
 
Automated Acceptance Tests & Tool choice
Automated Acceptance Tests & Tool choiceAutomated Acceptance Tests & Tool choice
Automated Acceptance Tests & Tool choice
 
Getting Ahead of Delivery Issues with Deep SDLC Analysis by Donald Belcham
Getting Ahead of Delivery Issues with Deep SDLC Analysis by Donald BelchamGetting Ahead of Delivery Issues with Deep SDLC Analysis by Donald Belcham
Getting Ahead of Delivery Issues with Deep SDLC Analysis by Donald Belcham
 
Inside Behavior Driven Development
Inside Behavior Driven DevelopmentInside Behavior Driven Development
Inside Behavior Driven Development
 
Selenium Frameworks
Selenium FrameworksSelenium Frameworks
Selenium Frameworks
 
Tech io spa_angularjs_20130814_v0.9.5
Tech io spa_angularjs_20130814_v0.9.5Tech io spa_angularjs_20130814_v0.9.5
Tech io spa_angularjs_20130814_v0.9.5
 
Getting Started with Selenium
Getting Started with SeleniumGetting Started with Selenium
Getting Started with Selenium
 
How To Use Selenium Successfully
How To Use Selenium SuccessfullyHow To Use Selenium Successfully
How To Use Selenium Successfully
 
Promoting Agility with Running Tested Features - Lightening Talk
Promoting Agility with Running Tested Features - Lightening TalkPromoting Agility with Running Tested Features - Lightening Talk
Promoting Agility with Running Tested Features - Lightening Talk
 
Testing for Agility: Bringing Testing into Everything
Testing for Agility: Bringing Testing into EverythingTesting for Agility: Bringing Testing into Everything
Testing for Agility: Bringing Testing into Everything
 
Testable requirements
Testable requirementsTestable requirements
Testable requirements
 
How To Use Selenium Successfully
How To Use Selenium SuccessfullyHow To Use Selenium Successfully
How To Use Selenium Successfully
 
Growing Manual Testers into Automators
Growing Manual Testers into AutomatorsGrowing Manual Testers into Automators
Growing Manual Testers into Automators
 
Acceptance Test Driven Development With Spec Flow And Friends
Acceptance Test Driven Development With Spec Flow And FriendsAcceptance Test Driven Development With Spec Flow And Friends
Acceptance Test Driven Development With Spec Flow And Friends
 
Testing Java EE apps with Arquillian
Testing Java EE apps with ArquillianTesting Java EE apps with Arquillian
Testing Java EE apps with Arquillian
 
Test and Behaviour Driven Development (TDD/BDD)
Test and Behaviour Driven Development (TDD/BDD)Test and Behaviour Driven Development (TDD/BDD)
Test and Behaviour Driven Development (TDD/BDD)
 
Bdd and spec flow
Bdd and spec flowBdd and spec flow
Bdd and spec flow
 
Adapting Agility: Getting your Agile Transformation Unstuck
Adapting Agility: Getting your Agile Transformation UnstuckAdapting Agility: Getting your Agile Transformation Unstuck
Adapting Agility: Getting your Agile Transformation Unstuck
 

Viewers also liked

Folien sfps 4
Folien sfps 4Folien sfps 4
Common asp.net design patterns aspconf2012
Common asp.net design patterns aspconf2012Common asp.net design patterns aspconf2012
Common asp.net design patterns aspconf2012
Steven Smith
 
Introduction to MeteorJS
Introduction to MeteorJSIntroduction to MeteorJS
Introduction to MeteorJS
Weiming Chen
 
Onion Architecture with S#arp
Onion Architecture with S#arpOnion Architecture with S#arp
Onion Architecture with S#arp
Gary Pedretti
 
Query Handling System
Query Handling SystemQuery Handling System
Query Handling System
himabindu54
 
ASP.NET Session 1
ASP.NET Session 1ASP.NET Session 1
ASP.NET Session 1
Sisir Ghosh
 
50 ideas for using beacons
50 ideas for using beacons50 ideas for using beacons
50 ideas for using beacons
Sinergia Labs
 
Beacons: The Retail Revolution
Beacons: The Retail RevolutionBeacons: The Retail Revolution
Beacons: The Retail Revolution
kontakt.io
 
BEACON TECHNOLOGY OVERVIEW
BEACON TECHNOLOGY OVERVIEWBEACON TECHNOLOGY OVERVIEW
BEACON TECHNOLOGY OVERVIEW
Donnovan Andrews
 
In-Store Marketing via Micro-Location: Beacon
In-Store Marketing via Micro-Location: BeaconIn-Store Marketing via Micro-Location: Beacon
In-Store Marketing via Micro-Location: Beacon
DigitasLBi Paris
 

Viewers also liked (10)

Folien sfps 4
Folien sfps 4Folien sfps 4
Folien sfps 4
 
Common asp.net design patterns aspconf2012
Common asp.net design patterns aspconf2012Common asp.net design patterns aspconf2012
Common asp.net design patterns aspconf2012
 
Introduction to MeteorJS
Introduction to MeteorJSIntroduction to MeteorJS
Introduction to MeteorJS
 
Onion Architecture with S#arp
Onion Architecture with S#arpOnion Architecture with S#arp
Onion Architecture with S#arp
 
Query Handling System
Query Handling SystemQuery Handling System
Query Handling System
 
ASP.NET Session 1
ASP.NET Session 1ASP.NET Session 1
ASP.NET Session 1
 
50 ideas for using beacons
50 ideas for using beacons50 ideas for using beacons
50 ideas for using beacons
 
Beacons: The Retail Revolution
Beacons: The Retail RevolutionBeacons: The Retail Revolution
Beacons: The Retail Revolution
 
BEACON TECHNOLOGY OVERVIEW
BEACON TECHNOLOGY OVERVIEWBEACON TECHNOLOGY OVERVIEW
BEACON TECHNOLOGY OVERVIEW
 
In-Store Marketing via Micro-Location: Beacon
In-Store Marketing via Micro-Location: BeaconIn-Store Marketing via Micro-Location: Beacon
In-Store Marketing via Micro-Location: Beacon
 

Similar to Improving the Quality of Existing Software

Improving the Design of Existing Software
Improving the Design of Existing SoftwareImproving the Design of Existing Software
Improving the Design of Existing Software
Steven Smith
 
Refactoring Applications using SOLID Principles
Refactoring Applications using SOLID PrinciplesRefactoring Applications using SOLID Principles
Refactoring Applications using SOLID Principles
Steven Smith
 
Integration strategies best practices- Mulesoft meetup April 2018
Integration strategies   best practices- Mulesoft meetup April 2018Integration strategies   best practices- Mulesoft meetup April 2018
Integration strategies best practices- Mulesoft meetup April 2018
Rohan Rasane
 
Entity Framework: To the Unit of Work Design Pattern and Beyond
Entity Framework: To the Unit of Work Design Pattern and BeyondEntity Framework: To the Unit of Work Design Pattern and Beyond
Entity Framework: To the Unit of Work Design Pattern and Beyond
Steve Westgarth
 
STAQ Development Manual (Redacted)
STAQ Development Manual (Redacted)STAQ Development Manual (Redacted)
STAQ Development Manual (Redacted)
Mike Subelsky
 
Dev ops concept
Dev ops conceptDev ops concept
Dev ops concept
Professional Guru
 
Apex Enterprise Patterns Galore - Boston, MA dev group meeting 062719
Apex Enterprise Patterns Galore - Boston, MA dev group meeting 062719Apex Enterprise Patterns Galore - Boston, MA dev group meeting 062719
Apex Enterprise Patterns Galore - Boston, MA dev group meeting 062719
BingWang77
 
Enterprise Node - Code Quality
Enterprise Node - Code QualityEnterprise Node - Code Quality
Enterprise Node - Code Quality
Kurtis Kemple
 
Refactoring
RefactoringRefactoring
Refactoring
AngelLuisBlasco
 
Testing, a pragmatic approach
Testing, a pragmatic approachTesting, a pragmatic approach
Testing, a pragmatic approach
Enrico Da Ros
 
Continuous delivery @wcap 5-09-2013
Continuous delivery   @wcap 5-09-2013Continuous delivery   @wcap 5-09-2013
Continuous delivery @wcap 5-09-2013
David Funaro
 
The View - Lotusscript coding best practices
The View - Lotusscript coding best practicesThe View - Lotusscript coding best practices
The View - Lotusscript coding best practices
Bill Buchan
 
Clean code
Clean codeClean code
Clean code
Simon Sönnby
 
Patterns and practices for building enterprise-scale HTML5 apps
Patterns and practices for building enterprise-scale HTML5 appsPatterns and practices for building enterprise-scale HTML5 apps
Patterns and practices for building enterprise-scale HTML5 apps
Phil Leggetter
 
Critical Capabilities to Shifting Left the Right Way
Critical Capabilities to Shifting Left the Right WayCritical Capabilities to Shifting Left the Right Way
Critical Capabilities to Shifting Left the Right Way
SmartBear
 
King Tut Architecture
King Tut ArchitectureKing Tut Architecture
King Tut Architecture
Gary Pedretti
 
Test automation lessons from WebSphere Application Server
Test automation lessons from WebSphere Application ServerTest automation lessons from WebSphere Application Server
Test automation lessons from WebSphere Application Server
Robbie Minshall
 
Grails Services
Grails ServicesGrails Services
Grails Services
NexThoughts Technologies
 
Best Practices for Building WordPress Applications
Best Practices for Building WordPress ApplicationsBest Practices for Building WordPress Applications
Best Practices for Building WordPress Applications
Taylor Lovett
 
Five Enterprise Best Practices That EVERY Salesforce Org Can Use (DF15 Session)
Five Enterprise Best Practices That EVERY Salesforce Org Can Use (DF15 Session)Five Enterprise Best Practices That EVERY Salesforce Org Can Use (DF15 Session)
Five Enterprise Best Practices That EVERY Salesforce Org Can Use (DF15 Session)
Vivek Chawla
 

Similar to Improving the Quality of Existing Software (20)

Improving the Design of Existing Software
Improving the Design of Existing SoftwareImproving the Design of Existing Software
Improving the Design of Existing Software
 
Refactoring Applications using SOLID Principles
Refactoring Applications using SOLID PrinciplesRefactoring Applications using SOLID Principles
Refactoring Applications using SOLID Principles
 
Integration strategies best practices- Mulesoft meetup April 2018
Integration strategies   best practices- Mulesoft meetup April 2018Integration strategies   best practices- Mulesoft meetup April 2018
Integration strategies best practices- Mulesoft meetup April 2018
 
Entity Framework: To the Unit of Work Design Pattern and Beyond
Entity Framework: To the Unit of Work Design Pattern and BeyondEntity Framework: To the Unit of Work Design Pattern and Beyond
Entity Framework: To the Unit of Work Design Pattern and Beyond
 
STAQ Development Manual (Redacted)
STAQ Development Manual (Redacted)STAQ Development Manual (Redacted)
STAQ Development Manual (Redacted)
 
Dev ops concept
Dev ops conceptDev ops concept
Dev ops concept
 
Apex Enterprise Patterns Galore - Boston, MA dev group meeting 062719
Apex Enterprise Patterns Galore - Boston, MA dev group meeting 062719Apex Enterprise Patterns Galore - Boston, MA dev group meeting 062719
Apex Enterprise Patterns Galore - Boston, MA dev group meeting 062719
 
Enterprise Node - Code Quality
Enterprise Node - Code QualityEnterprise Node - Code Quality
Enterprise Node - Code Quality
 
Refactoring
RefactoringRefactoring
Refactoring
 
Testing, a pragmatic approach
Testing, a pragmatic approachTesting, a pragmatic approach
Testing, a pragmatic approach
 
Continuous delivery @wcap 5-09-2013
Continuous delivery   @wcap 5-09-2013Continuous delivery   @wcap 5-09-2013
Continuous delivery @wcap 5-09-2013
 
The View - Lotusscript coding best practices
The View - Lotusscript coding best practicesThe View - Lotusscript coding best practices
The View - Lotusscript coding best practices
 
Clean code
Clean codeClean code
Clean code
 
Patterns and practices for building enterprise-scale HTML5 apps
Patterns and practices for building enterprise-scale HTML5 appsPatterns and practices for building enterprise-scale HTML5 apps
Patterns and practices for building enterprise-scale HTML5 apps
 
Critical Capabilities to Shifting Left the Right Way
Critical Capabilities to Shifting Left the Right WayCritical Capabilities to Shifting Left the Right Way
Critical Capabilities to Shifting Left the Right Way
 
King Tut Architecture
King Tut ArchitectureKing Tut Architecture
King Tut Architecture
 
Test automation lessons from WebSphere Application Server
Test automation lessons from WebSphere Application ServerTest automation lessons from WebSphere Application Server
Test automation lessons from WebSphere Application Server
 
Grails Services
Grails ServicesGrails Services
Grails Services
 
Best Practices for Building WordPress Applications
Best Practices for Building WordPress ApplicationsBest Practices for Building WordPress Applications
Best Practices for Building WordPress Applications
 
Five Enterprise Best Practices That EVERY Salesforce Org Can Use (DF15 Session)
Five Enterprise Best Practices That EVERY Salesforce Org Can Use (DF15 Session)Five Enterprise Best Practices That EVERY Salesforce Org Can Use (DF15 Session)
Five Enterprise Best Practices That EVERY Salesforce Org Can Use (DF15 Session)
 

More from Steven Smith

Clean architecture with asp.net core by Ardalis
Clean architecture with asp.net core by ArdalisClean architecture with asp.net core by Ardalis
Clean architecture with asp.net core by Ardalis
Steven Smith
 
Finding Patterns in the Clouds - Cloud Design Patterns
Finding Patterns in the Clouds - Cloud Design PatternsFinding Patterns in the Clouds - Cloud Design Patterns
Finding Patterns in the Clouds - Cloud Design Patterns
Steven Smith
 
Introducing domain driven design - dogfood con 2018
Introducing domain driven design - dogfood con 2018Introducing domain driven design - dogfood con 2018
Introducing domain driven design - dogfood con 2018
Steven Smith
 
Design Pattern Mastery - Momentum Dev Con 19 Apr 2018
Design Pattern Mastery - Momentum Dev Con 19 Apr 2018Design Pattern Mastery - Momentum Dev Con 19 Apr 2018
Design Pattern Mastery - Momentum Dev Con 19 Apr 2018
Steven Smith
 
Introducing Domain Driven Design - codemash
Introducing Domain Driven Design - codemashIntroducing Domain Driven Design - codemash
Introducing Domain Driven Design - codemash
Steven Smith
 
Most Useful Design Patterns
Most Useful Design PatternsMost Useful Design Patterns
Most Useful Design Patterns
Steven Smith
 
Introducing ASP.NET Core 2.0
Introducing ASP.NET Core 2.0Introducing ASP.NET Core 2.0
Introducing ASP.NET Core 2.0
Steven Smith
 
Decoupling with Domain Events
Decoupling with Domain EventsDecoupling with Domain Events
Decoupling with Domain Events
Steven Smith
 
A Whirldwind Tour of ASP.NET 5
A Whirldwind Tour of ASP.NET 5A Whirldwind Tour of ASP.NET 5
A Whirldwind Tour of ASP.NET 5
Steven Smith
 
Domain events
Domain eventsDomain events
Domain events
Steven Smith
 
My Iraq Experience
My Iraq ExperienceMy Iraq Experience
My Iraq Experience
Steven Smith
 
Add Some DDD to Your ASP.NET MVC, OK?
Add Some DDD to Your ASP.NET MVC, OK?Add Some DDD to Your ASP.NET MVC, OK?
Add Some DDD to Your ASP.NET MVC, OK?
Steven Smith
 
Domain-Driven Design with ASP.NET MVC
Domain-Driven Design with ASP.NET MVCDomain-Driven Design with ASP.NET MVC
Domain-Driven Design with ASP.NET MVC
Steven Smith
 
Refactoring with SOLID Principles (FalafelCon 2013)
Refactoring with SOLID Principles (FalafelCon 2013)Refactoring with SOLID Principles (FalafelCon 2013)
Refactoring with SOLID Principles (FalafelCon 2013)
Steven Smith
 
Common ASP.NET Design Patterns - Telerik India DevCon 2013
Common ASP.NET Design Patterns - Telerik India DevCon 2013Common ASP.NET Design Patterns - Telerik India DevCon 2013
Common ASP.NET Design Patterns - Telerik India DevCon 2013
Steven Smith
 
Refactoring with SOLID - Telerik India DevCon 2013
Refactoring with SOLID - Telerik India DevCon 2013Refactoring with SOLID - Telerik India DevCon 2013
Refactoring with SOLID - Telerik India DevCon 2013
Steven Smith
 
Common design patterns (migang 16 May 2012)
Common design patterns (migang 16 May 2012)Common design patterns (migang 16 May 2012)
Common design patterns (migang 16 May 2012)
Steven Smith
 
Introducing Pair Programming
Introducing Pair ProgrammingIntroducing Pair Programming
Introducing Pair Programming
Steven Smith
 
Cinci ug-january2011-anti-patterns
Cinci ug-january2011-anti-patternsCinci ug-january2011-anti-patterns
Cinci ug-january2011-anti-patterns
Steven Smith
 

More from Steven Smith (19)

Clean architecture with asp.net core by Ardalis
Clean architecture with asp.net core by ArdalisClean architecture with asp.net core by Ardalis
Clean architecture with asp.net core by Ardalis
 
Finding Patterns in the Clouds - Cloud Design Patterns
Finding Patterns in the Clouds - Cloud Design PatternsFinding Patterns in the Clouds - Cloud Design Patterns
Finding Patterns in the Clouds - Cloud Design Patterns
 
Introducing domain driven design - dogfood con 2018
Introducing domain driven design - dogfood con 2018Introducing domain driven design - dogfood con 2018
Introducing domain driven design - dogfood con 2018
 
Design Pattern Mastery - Momentum Dev Con 19 Apr 2018
Design Pattern Mastery - Momentum Dev Con 19 Apr 2018Design Pattern Mastery - Momentum Dev Con 19 Apr 2018
Design Pattern Mastery - Momentum Dev Con 19 Apr 2018
 
Introducing Domain Driven Design - codemash
Introducing Domain Driven Design - codemashIntroducing Domain Driven Design - codemash
Introducing Domain Driven Design - codemash
 
Most Useful Design Patterns
Most Useful Design PatternsMost Useful Design Patterns
Most Useful Design Patterns
 
Introducing ASP.NET Core 2.0
Introducing ASP.NET Core 2.0Introducing ASP.NET Core 2.0
Introducing ASP.NET Core 2.0
 
Decoupling with Domain Events
Decoupling with Domain EventsDecoupling with Domain Events
Decoupling with Domain Events
 
A Whirldwind Tour of ASP.NET 5
A Whirldwind Tour of ASP.NET 5A Whirldwind Tour of ASP.NET 5
A Whirldwind Tour of ASP.NET 5
 
Domain events
Domain eventsDomain events
Domain events
 
My Iraq Experience
My Iraq ExperienceMy Iraq Experience
My Iraq Experience
 
Add Some DDD to Your ASP.NET MVC, OK?
Add Some DDD to Your ASP.NET MVC, OK?Add Some DDD to Your ASP.NET MVC, OK?
Add Some DDD to Your ASP.NET MVC, OK?
 
Domain-Driven Design with ASP.NET MVC
Domain-Driven Design with ASP.NET MVCDomain-Driven Design with ASP.NET MVC
Domain-Driven Design with ASP.NET MVC
 
Refactoring with SOLID Principles (FalafelCon 2013)
Refactoring with SOLID Principles (FalafelCon 2013)Refactoring with SOLID Principles (FalafelCon 2013)
Refactoring with SOLID Principles (FalafelCon 2013)
 
Common ASP.NET Design Patterns - Telerik India DevCon 2013
Common ASP.NET Design Patterns - Telerik India DevCon 2013Common ASP.NET Design Patterns - Telerik India DevCon 2013
Common ASP.NET Design Patterns - Telerik India DevCon 2013
 
Refactoring with SOLID - Telerik India DevCon 2013
Refactoring with SOLID - Telerik India DevCon 2013Refactoring with SOLID - Telerik India DevCon 2013
Refactoring with SOLID - Telerik India DevCon 2013
 
Common design patterns (migang 16 May 2012)
Common design patterns (migang 16 May 2012)Common design patterns (migang 16 May 2012)
Common design patterns (migang 16 May 2012)
 
Introducing Pair Programming
Introducing Pair ProgrammingIntroducing Pair Programming
Introducing Pair Programming
 
Cinci ug-january2011-anti-patterns
Cinci ug-january2011-anti-patternsCinci ug-january2011-anti-patterns
Cinci ug-january2011-anti-patterns
 

Recently uploaded

TMU毕业证书精仿办理
TMU毕业证书精仿办理TMU毕业证书精仿办理
TMU毕业证书精仿办理
aeeva
 
Baha Majid WCA4Z IBM Z Customer Council Boston June 2024.pdf
Baha Majid WCA4Z IBM Z Customer Council Boston June 2024.pdfBaha Majid WCA4Z IBM Z Customer Council Boston June 2024.pdf
Baha Majid WCA4Z IBM Z Customer Council Boston June 2024.pdf
Baha Majid
 
14 th Edition of International conference on computer vision
14 th Edition of International conference on computer vision14 th Edition of International conference on computer vision
14 th Edition of International conference on computer vision
ShulagnaSarkar2
 
Kubernetes at Scale: Going Multi-Cluster with Istio
Kubernetes at Scale:  Going Multi-Cluster  with IstioKubernetes at Scale:  Going Multi-Cluster  with Istio
Kubernetes at Scale: Going Multi-Cluster with Istio
Severalnines
 
如何办理(hull学位证书)英国赫尔大学毕业证硕士文凭原版一模一样
如何办理(hull学位证书)英国赫尔大学毕业证硕士文凭原版一模一样如何办理(hull学位证书)英国赫尔大学毕业证硕士文凭原版一模一样
如何办理(hull学位证书)英国赫尔大学毕业证硕士文凭原版一模一样
gapen1
 
All you need to know about Spring Boot and GraalVM
All you need to know about Spring Boot and GraalVMAll you need to know about Spring Boot and GraalVM
All you need to know about Spring Boot and GraalVM
Alina Yurenko
 
一比一原版(UMN毕业证)明尼苏达大学毕业证如何办理
一比一原版(UMN毕业证)明尼苏达大学毕业证如何办理一比一原版(UMN毕业证)明尼苏达大学毕业证如何办理
一比一原版(UMN毕业证)明尼苏达大学毕业证如何办理
dakas1
 
Enums On Steroids - let's look at sealed classes !
Enums On Steroids - let's look at sealed classes !Enums On Steroids - let's look at sealed classes !
Enums On Steroids - let's look at sealed classes !
Marcin Chrost
 
Orca: Nocode Graphical Editor for Container Orchestration
Orca: Nocode Graphical Editor for Container OrchestrationOrca: Nocode Graphical Editor for Container Orchestration
Orca: Nocode Graphical Editor for Container Orchestration
Pedro J. Molina
 
Migration From CH 1.0 to CH 2.0 and Mule 4.6 & Java 17 Upgrade.pptx
Migration From CH 1.0 to CH 2.0 and  Mule 4.6 & Java 17 Upgrade.pptxMigration From CH 1.0 to CH 2.0 and  Mule 4.6 & Java 17 Upgrade.pptx
Migration From CH 1.0 to CH 2.0 and Mule 4.6 & Java 17 Upgrade.pptx
ervikas4
 
🏎️Tech Transformation: DevOps Insights from the Experts 👩‍💻
🏎️Tech Transformation: DevOps Insights from the Experts 👩‍💻🏎️Tech Transformation: DevOps Insights from the Experts 👩‍💻
🏎️Tech Transformation: DevOps Insights from the Experts 👩‍💻
campbellclarkson
 
Alluxio Webinar | 10x Faster Trino Queries on Your Data Platform
Alluxio Webinar | 10x Faster Trino Queries on Your Data PlatformAlluxio Webinar | 10x Faster Trino Queries on Your Data Platform
Alluxio Webinar | 10x Faster Trino Queries on Your Data Platform
Alluxio, Inc.
 
The Power of Visual Regression Testing_ Why It Is Critical for Enterprise App...
The Power of Visual Regression Testing_ Why It Is Critical for Enterprise App...The Power of Visual Regression Testing_ Why It Is Critical for Enterprise App...
The Power of Visual Regression Testing_ Why It Is Critical for Enterprise App...
kalichargn70th171
 
The Comprehensive Guide to Validating Audio-Visual Performances.pdf
The Comprehensive Guide to Validating Audio-Visual Performances.pdfThe Comprehensive Guide to Validating Audio-Visual Performances.pdf
The Comprehensive Guide to Validating Audio-Visual Performances.pdf
kalichargn70th171
 
Liberarsi dai framework con i Web Component.pptx
Liberarsi dai framework con i Web Component.pptxLiberarsi dai framework con i Web Component.pptx
Liberarsi dai framework con i Web Component.pptx
Massimo Artizzu
 
Unlock the Secrets to Effortless Video Creation with Invideo: Your Ultimate G...
Unlock the Secrets to Effortless Video Creation with Invideo: Your Ultimate G...Unlock the Secrets to Effortless Video Creation with Invideo: Your Ultimate G...
Unlock the Secrets to Effortless Video Creation with Invideo: Your Ultimate G...
The Third Creative Media
 
Superpower Your Apache Kafka Applications Development with Complementary Open...
Superpower Your Apache Kafka Applications Development with Complementary Open...Superpower Your Apache Kafka Applications Development with Complementary Open...
Superpower Your Apache Kafka Applications Development with Complementary Open...
Paul Brebner
 
ACE - Team 24 Wrapup event at ahmedabad.
ACE - Team 24 Wrapup event at ahmedabad.ACE - Team 24 Wrapup event at ahmedabad.
ACE - Team 24 Wrapup event at ahmedabad.
Maitrey Patel
 
Photoshop Tutorial for Beginners (2024 Edition)
Photoshop Tutorial for Beginners (2024 Edition)Photoshop Tutorial for Beginners (2024 Edition)
Photoshop Tutorial for Beginners (2024 Edition)
alowpalsadig
 
DECODING JAVA THREAD DUMPS: MASTER THE ART OF ANALYSIS
DECODING JAVA THREAD DUMPS: MASTER THE ART OF ANALYSISDECODING JAVA THREAD DUMPS: MASTER THE ART OF ANALYSIS
DECODING JAVA THREAD DUMPS: MASTER THE ART OF ANALYSIS
Tier1 app
 

Recently uploaded (20)

TMU毕业证书精仿办理
TMU毕业证书精仿办理TMU毕业证书精仿办理
TMU毕业证书精仿办理
 
Baha Majid WCA4Z IBM Z Customer Council Boston June 2024.pdf
Baha Majid WCA4Z IBM Z Customer Council Boston June 2024.pdfBaha Majid WCA4Z IBM Z Customer Council Boston June 2024.pdf
Baha Majid WCA4Z IBM Z Customer Council Boston June 2024.pdf
 
14 th Edition of International conference on computer vision
14 th Edition of International conference on computer vision14 th Edition of International conference on computer vision
14 th Edition of International conference on computer vision
 
Kubernetes at Scale: Going Multi-Cluster with Istio
Kubernetes at Scale:  Going Multi-Cluster  with IstioKubernetes at Scale:  Going Multi-Cluster  with Istio
Kubernetes at Scale: Going Multi-Cluster with Istio
 
如何办理(hull学位证书)英国赫尔大学毕业证硕士文凭原版一模一样
如何办理(hull学位证书)英国赫尔大学毕业证硕士文凭原版一模一样如何办理(hull学位证书)英国赫尔大学毕业证硕士文凭原版一模一样
如何办理(hull学位证书)英国赫尔大学毕业证硕士文凭原版一模一样
 
All you need to know about Spring Boot and GraalVM
All you need to know about Spring Boot and GraalVMAll you need to know about Spring Boot and GraalVM
All you need to know about Spring Boot and GraalVM
 
一比一原版(UMN毕业证)明尼苏达大学毕业证如何办理
一比一原版(UMN毕业证)明尼苏达大学毕业证如何办理一比一原版(UMN毕业证)明尼苏达大学毕业证如何办理
一比一原版(UMN毕业证)明尼苏达大学毕业证如何办理
 
Enums On Steroids - let's look at sealed classes !
Enums On Steroids - let's look at sealed classes !Enums On Steroids - let's look at sealed classes !
Enums On Steroids - let's look at sealed classes !
 
Orca: Nocode Graphical Editor for Container Orchestration
Orca: Nocode Graphical Editor for Container OrchestrationOrca: Nocode Graphical Editor for Container Orchestration
Orca: Nocode Graphical Editor for Container Orchestration
 
Migration From CH 1.0 to CH 2.0 and Mule 4.6 & Java 17 Upgrade.pptx
Migration From CH 1.0 to CH 2.0 and  Mule 4.6 & Java 17 Upgrade.pptxMigration From CH 1.0 to CH 2.0 and  Mule 4.6 & Java 17 Upgrade.pptx
Migration From CH 1.0 to CH 2.0 and Mule 4.6 & Java 17 Upgrade.pptx
 
🏎️Tech Transformation: DevOps Insights from the Experts 👩‍💻
🏎️Tech Transformation: DevOps Insights from the Experts 👩‍💻🏎️Tech Transformation: DevOps Insights from the Experts 👩‍💻
🏎️Tech Transformation: DevOps Insights from the Experts 👩‍💻
 
Alluxio Webinar | 10x Faster Trino Queries on Your Data Platform
Alluxio Webinar | 10x Faster Trino Queries on Your Data PlatformAlluxio Webinar | 10x Faster Trino Queries on Your Data Platform
Alluxio Webinar | 10x Faster Trino Queries on Your Data Platform
 
The Power of Visual Regression Testing_ Why It Is Critical for Enterprise App...
The Power of Visual Regression Testing_ Why It Is Critical for Enterprise App...The Power of Visual Regression Testing_ Why It Is Critical for Enterprise App...
The Power of Visual Regression Testing_ Why It Is Critical for Enterprise App...
 
The Comprehensive Guide to Validating Audio-Visual Performances.pdf
The Comprehensive Guide to Validating Audio-Visual Performances.pdfThe Comprehensive Guide to Validating Audio-Visual Performances.pdf
The Comprehensive Guide to Validating Audio-Visual Performances.pdf
 
Liberarsi dai framework con i Web Component.pptx
Liberarsi dai framework con i Web Component.pptxLiberarsi dai framework con i Web Component.pptx
Liberarsi dai framework con i Web Component.pptx
 
Unlock the Secrets to Effortless Video Creation with Invideo: Your Ultimate G...
Unlock the Secrets to Effortless Video Creation with Invideo: Your Ultimate G...Unlock the Secrets to Effortless Video Creation with Invideo: Your Ultimate G...
Unlock the Secrets to Effortless Video Creation with Invideo: Your Ultimate G...
 
Superpower Your Apache Kafka Applications Development with Complementary Open...
Superpower Your Apache Kafka Applications Development with Complementary Open...Superpower Your Apache Kafka Applications Development with Complementary Open...
Superpower Your Apache Kafka Applications Development with Complementary Open...
 
ACE - Team 24 Wrapup event at ahmedabad.
ACE - Team 24 Wrapup event at ahmedabad.ACE - Team 24 Wrapup event at ahmedabad.
ACE - Team 24 Wrapup event at ahmedabad.
 
Photoshop Tutorial for Beginners (2024 Edition)
Photoshop Tutorial for Beginners (2024 Edition)Photoshop Tutorial for Beginners (2024 Edition)
Photoshop Tutorial for Beginners (2024 Edition)
 
DECODING JAVA THREAD DUMPS: MASTER THE ART OF ANALYSIS
DECODING JAVA THREAD DUMPS: MASTER THE ART OF ANALYSISDECODING JAVA THREAD DUMPS: MASTER THE ART OF ANALYSIS
DECODING JAVA THREAD DUMPS: MASTER THE ART OF ANALYSIS
 

Improving the Quality of Existing Software

  • 1. Improving the Quality of Existing Software Steve Smith Founder, DevIQ @ardalis | ardalis.com
  • 4.
  • 5. Technical Debt • Low quality code and shortcuts in our applications • Technical debt, like real debt, has direct cost to pay off as well as interest http://deviq.com/technical-debt/
  • 7.
  • 8. Preventive Maintenance • Refactoring • Eliminate Duplication • Simplify Design • AutomatedTests • Verify correctness • Avoid regressions • Increase Confidence
  • 9. When should you refactor? • While delivering value
  • 10. “ ” You don’t need permission to practice basic hygiene when you write software. http://ardalis.com/when-should-you-refactor/ Make cleaning up your code something you do as part of writing code.
  • 11.
  • 12. Refactoring Should Not Change System Behavior
  • 13. The Refactoring Process • Verify existing behavior • Write CharacterizationTests if none exist • Find test points • Break dependencies • Apply Refactoring • Confirm existing behavior is preserved
  • 14. CharacterizationTests Process 1. Write a test you know will fail 2. Use the output of the failing test to determine the existing behavior to assert 3. Update the test with the new value/behavior 4. Run the test again – it should now pass
  • 15.
  • 16. S O L I DPrinciples http://flickr.com/photos/kevinkemmerer/2772526725/
  • 17. Principles of OO Design 0. Don’t RepeatYourself (DRY) 1. Single Responsibility 2. Open/Closed 3. Liskov Substitution 4. Interface Segregation 5. Dependency Inversion
  • 18.
  • 19.
  • 20. Don’t Repeat RepeatYourself • Duplication in logic calls for abstraction • Duplication in process calls for automation
  • 21. Common Refactorings • Replace Magic Number/String • Parameterize Method • Pull Up Field • Pull Up Method • Replace Conditional With Polymorphism • Introduce Method
  • 22. Common Source of Repetition: Role Checks if(user.IsInRole(“Admins”) { // allow access to resource } // favor privileges over role checks // ardalis.com/Favor-Privileges-over-Role-Checks var priv = new ContentPrivilege(user, article); if(priv.CanEdit()) { // allow access }
  • 23. Visual Studio Code Clones • Find similar blocks of code in your projects/solution • Can detect matches that are similar but vary in small ways (like variable names) • Available inVS2015 Premium and Ultimate
  • 24.
  • 25. Single Responsibility Principle The Single Responsibility Principle states that every object should have a single responsibility, and that responsibility should be entirely encapsulated by the class. Wikipedia There should never be more than one reason for a class to change. Robert C. “Uncle Bob” Martin
  • 26. What is a responsibility? “My CustomerManager class is only responsible for anything to do with a Customer.That follows SRP, right?”
  • 27. Examples of Responsibilities • Persistence • Validation • Notification • Error Handling • Logging • Class Selection / Construction • Formatting • Parsing • Mapping
  • 28. Dependency and Coupling • Excessive coupling makes changing legacy software difficult • Breaking apart responsibilities and dependencies is a large part of working with existing code
  • 29. Common Refactorings • Extract Class • Extract Method • Move Method
  • 30. Heuristics and Code Smells • Visual Studio Metrics
  • 33.
  • 34. Code Smell: Regions More on Regions: http://ardalis.com/regional-differences
  • 35.
  • 36. Open / Closed Principle The Open / Closed Principle states that software entities (classes, modules, functions, etc.) should be open for extension, but closed for modification. Wikipedia
  • 37. Open / Closed Principle Open to Extension New behavior can be added in the future Closed to Modification Changes to source or binary code are not required Dr. Bertrand Meyer originated the OCP term in his 1988 book, ObjectOrientedSoftwareConstruction
  • 38. Common Refactorings • Extract Interface / Apply Strategy Pattern • Parameterize Method • FormTemplate Method
  • 41. OCP Fail public bool IsSpecialCustomer(Customer c) { if(c.Country == “US” && c.Balance < 50) return false; if(c.Country == “DE” && c.Balance < 25) return false; if(c.Country == “UK” && c.Balance < 35) return false; if(c.Country == “FR” && c.Balance < 27) return false; if(c.Country == “BG” && c.Balance < 29) return false; if(c.Age < 18 || c.Age > 65) return false; if(c.Income < 50000 && c.Age < 30) return false; return true; }
  • 42. OCP OK private IEnumerable<ICustomerRule> _rules; public bool IsSpecialCustomer(Customer customer) { foreach(var rule in _rules) { if(rule.Evaluate(customer) == false) return false; } return true; }
  • 43.
  • 44. Liskov Substitution Principle The Liskov Substitution Principle states that Subtypes must be substitutable for their base types. Agile Principles, Patterns, and Practices in C# Named for Barbara Liskov, who first described the principle in 1988.
  • 45. Common Refactorings • Collapse Hierarchy • Pull Up / Push Down Field • Pull Up / Push Down Method
  • 46. Liskov Substitution Fail foreach(var employee in employees) { if(employee is Manager) { Helpers.PrintManager(employee as Manager); break; } Helpers.PrintEmployee(employee); }
  • 47. Liskov Substitution OK foreach(var employee in employees) { employee.Print(); // or Helpers.PrintEmployee(employee); }
  • 48. Nulls Break Polymorphism foreach(var employee in employees) { if(employee == null) { // print not found message break; } Helpers.PrintEmployee(employee); } http://ardalis.com/nulls-break-polymorphism
  • 49.
  • 50. Interface Segregation Principle The Interface Segregation Principle states that Clients should not be forced to depend on methods they do not use. Agile Principles, Patterns, and Practices in C# Corollary: Prefer small, cohesive interfaces to “fat” interfaces
  • 52. Keep Interfaces Small and Focused
  • 54. ISP Fail (sometimes) public IRepository<T> { T GetById(int id); IEnumerable<T> List(); void Create(T item); void Update(T item); void Delete(T item); }
  • 55. ISP OK (i.e. to support CQRS) public IRepository<T> : IReadRepository<T>, IWriteRepository<T> { } public IReadRepository<T> { T GetById(int id); IEnumerable<T> List(); } public IWriteRepository<T> void Create(T item); void Update(T item); void Delete(T item); } Existing implementations of IRepository<T> are unaffected by pulling out smaller interfaces! No existing code breaks!
  • 56.
  • 57. 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. Agile Principles, Patterns, and Practices in C#
  • 58. Dependency Inversion Principle • Depend on Abstractions • Interfaces, not concrete types • Inject Dependencies into Classes • Structure Solution so Dependencies FlowToward Core • Onion Architecture (a.k.a. Ports and Adapters, a.k.a. Hexagonal Architecture)
  • 59. DIP Architecture (aka Ports and Adapters)
  • 60. Common Dependencies • Framework • Third Party Libraries • Database • File System • Email • Web Services • System Resources (Clock) • Configuration • The new Keyword • Static methods • Thread.Sleep • Random See also responsibilities: • Persistence • Validation • Notification • Error Handling • Logging • Class Selection / Construction • Formatting • Parsing • Mapping
  • 61. Common Refactorings • Extract Class • Extract Interface / Apply Strategy Pattern • Extract Method • Introduce Service Locator / Container
  • 63. Hidden Dependencies • Checkout Depends on an available SMTP server, but the class doesn’t reflect this • Follow the Explicit Dependencies Principle • http://deviq.com/explicit-dependencies-principle/
  • 65. DIP OK (Strategy Pattern / DI)
  • 66. DIP OK (Strategy Pattern / DI)
  • 67. Improving Quality Across the Industry
  • 68.
  • 69. Self-Improvement and Quality • How fast can you produce: • Code you believe to be of high quality • Code that maybe gets the job done, but you believe to be of low quality • Which one can you produce more quickly? • Why? • How can we develop our skills and our tools so that building quality is natural and easier than not doing so?
  • 70. 0 2 4 6 8 10 12 14 16 Week 1 Week 2 Week 3 Week 4 Week 5 Week 6 Week 7 Week 8 Week 9 User Stories Completed High Quality Low Quality
  • 71. 0 2 4 6 8 10 12 14 16 18 20 Week 1 Week 2 Week 3 Week 4 Week 5 Week 6 Week 7 Week 8 Week 9 User Stories Completed High Quality Low Quality
  • 72. Summary •Maintain / Improve Application Code •Follow DRY/SOLID Principles •Use CharacterizationTests to “fix” behavior •Apply Common Refactorings •Re-runTestsAfter (and during) Refactorings •Be Explicit About Class Dependencies •Train and Practice toWrite Better Code Faster
  • 73. Learn More • DevIQ.com • Ardalis.com • Twitter: @ardalis • Pluralsight: • SOLID Principles of OO Design • N-TierArchitecture in C# • Refactoring Fundamentals • Domain-Driven Design Fundamentals • Design Pattern Library • Pair Programming
  • 74. • New Coworking Space in Hudson,Ohio • Private offices / Flex desk spaces • Fiber internet • Complimentary coffee / tea / water • Great development community • @techhubhudson • Website online soon Tech Hub Hudson
  • 75. • Includes images like the ones in this presentation • Kickstarter Successful! • Available November 2016 • Order now: store.DevIQ.com 2017 Software Craftsmanship Calendar
  • 76. Books  Refactoring http://amzn.to/110tscA  Refactoring to Patterns http://amzn.to/Vq5Rj2  Working Effectively with Legacy Code http://amzn.to/VFFYbn  Code Complete http://amzn.to/Vq5YLv  Clean Code http://amzn.to/YjUDI0

Editor's Notes

  1. ONE HOUR
  2. How? Duplication Excess Coupling Quick Fixes Hacks
  3. Over time, neglect can turn software from well-oiled machinery into heaps of useless junk.
  4. Typically the low quality code was left because of the need to meet deadlines, but once in place, the justification for having put it there no longer matters. Whenever you are forced to work around the hacks, bad code, etc, in your application, the decrease in your productivity represents interest on technical debt. If you spend time refactoring the code to improve its quality, you are paying down the principal of the technical debt (and thus reducing future interest costs).
  5. Accidental vs. Deliberate decision to incur the debt. Reckless vs. Prudent kinds of debt incurred.
  6. Should we spend an iteration or a month just trying to improve the quality of the system, and pay down technical debt? What would you think if you went to your favorite restaurant, only to find that it was closed for a month, with a sign explaining that it needed to clean up things that had gotten out of hand due to neglect. Would you feel as confident about eating the product of that kitchen, knowing it had let things go so wrong that it now needed a month without producing food just to clean up the mess it had created. How do you think our customers should feel if we request time to clean up our code instead of fixing bugs or delivering new features?
  7. By definition, refactoring attempts to improve the quality of a software application without changing its behavior. If you’re changing behavior, you’re not refactoring, you’re fixing a bug or adding a feature (hopefully – or adding a bug).
  8. Only refactor code while your tests are passing. Make sure they still pass when you are done. Break large refactorings into small steps and test after each step.
  9. Note that characterization tests, though they should be automated, are often not what we would think of as unit tests, or perhaps even integration tests. For instance, you could dump a log file showing the relevant state of the application, and then use that as the basis for your characterization test by comparing against it after your changes.
  10. Avoid creating a big ball of mud system, where tracing through your code and its dependencies is like trying to unwind a tangled mess of spaghetti.
  11. Principles provide guidance for refactoring. They provide a consistent target to aim toward.
  12. A very common source of repetition of code is role checks. These often describe different scenarios in different circumstances. For instance, maybe administrators can do anything, but managers can access resources within their division, etc. Encapsulating the logic of CanView, CanCreate, CanEdit, etc. in privilege objects makes these rules explicit, easier to test, and gives them a single location to live in the application.
  13. Visual Studio can quickly analyze a project and show statistics for the classes and methods in the project. The maintainability index, cyclomatic complexity, and lines of code are all great metrics to pay attention to. The ideal maintainability index is 100, but don’t expect to hit that with any code that’s doing real work. However, you should certainly able to keep it above 50. Demo GildedRose.
  14. Using Excel
  15. I’m not a fan of regions. They mainly exist because at one time they were a reasonable means of hiding generated code, before we had support for partial classes and other language features to deal with this. The worst offense with regions is when they’re used within a method, like this: (click) They’re also bad when used at the class level for “standard” formatting of code, making it impossible to actually see what the code does, like this: (click) Can someone tell me what this class does? (click) I have a whole article devoted to why using regions is a bad habit, anti-pattern, code smell, whatever you prefer. It includes some survey results on the most common ways people use them as well. (click)
  16. Open-Closed Principle
  17. Software can only be open to extension in a few different axes, and each additional bit of flexibility adds complexity to the software. Thus, this flexibility should be added only when needed, not simply anticipated.
  18. What happens when we need to add another country? What happens when we must add another rule? How can we refactor this so this method no longer needs to change?
  19. Define a type to describe a rule. Move each rule into its own type. Create a collection of rules to apply and apply them. Pass the set of rules into the IsSpecialCustomer() method’s class (or even the method itself).
  20. Any time you find that you need to check the type of an object within a polymorphic block of code (such as a foreach), this is a sign that you are breaking LSP.
  21. Nulls break polymorphism and violate LSP just as much as other subtypes that aren’t substitutable! Try to avoid the possibility of dealing with nulls in polymorphic code like foreach loops – consider using Null Object Pattern to address.
  22. This is an extemely common example of the Repository design pattern. In fact, I use this exact pattern in quite a few production applications today. There’s nothing inherently wrong with this implementation on its own. However, sometimes it does violate ISP if you need to separate Commands from Queries
  23. You can create small interfaces and compose the larger interfaces from the smaller ones if you control all of the code and you can’t simply do away with the larger interfaces. In this case, the separation of interfaces would allow us to do something like implement caching only on the read operations, and implement delayed writes using some kind of queue or message bus for the write operations.
  24. “Legacy” N-Tier Logical Architecture
  25. Hidden Dependencies
  26. Extract interface Implement interface with tightly coupled original code
  27. Mention Explicit Dependencies Principle
  28. Water break
  29. Get them excited.