SlideShare ist ein Scribd-Unternehmen logo
1 von 85
Improving the Design of
Existing Software
Steve Smith
Founder, DevIQ
@ardalis | DevIQ.com
My Pluralsight Courses
Weekly DevTips
Podcast and Newsletter
• Ardalis.com/tips
• WeeklyDevTips.com
Software Rots
Technical Debt
• Low quality code and shortcuts in our applications
• Financial Debt
• Principal – Amount borrowed
• Interest – Additional cost of the debt
• Technical debt
• Principal – Amount of time required to code solution “properly”
• Interest – Additional time needed to work around improper code
http://deviq.com/technical-debt/
http://www.jimhighsmith.com/
A Well-Designed Application
is
Simple
to
Maintain and Extend
Technical Debt
is a
Design Decision
(or series of decisions)
Paying DownTechnical Debt
Improves
Application Design and Quality
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
 Commit the working code!
Commit the working code!
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
Brownfield / Legacy Development
Maximize Code Changes
Made to
New Classes
Why new classes?
• Nothing depends on them (yet)
• You can write them to be testable
• Even in an otherwise hard-to-test application
Add High-ValueTests to Legacy Apps
• Probably not writtenTest-First
• Trying to UnitTest Everything is likely cost-prohibitive
• Start by writing tests for bugs
• Verify the bug behavior with a test
• Make the test pass by fixing the bug
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
Pluralsight Course:
http://bit.ly/SOLID-OOP
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
• WeeklyDevTips.com
• Twitter: @ardalis
• Pluralsight:
• SOLID Principles of OO Design http://bit.ly/SOLID-OOP
• N-Tier Architecture in C# http://bit.ly/PS-NTier1
• Refactoring Fundamentals http://bit.ly/PS-Refactoring
• Domain-Driven Design Fundamentals http://bit.ly/ddd-fundamentals
• Design Pattern Library http://bit.ly/PS-design-patterns
• Pair Programming http://bit.ly/PS-PairProgramming
• 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
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

Weitere ähnliche Inhalte

Was ist angesagt?

Improving the Quality of Existing Software - DevIntersection April 2016
Improving the Quality of Existing Software - DevIntersection April 2016Improving the Quality of Existing Software - DevIntersection April 2016
Improving the Quality of Existing Software - DevIntersection April 2016Steven 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 2013Steven 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 2013Steven Smith
 
Scaling Indexing and Replication in Jira Data Center Apps
Scaling Indexing and Replication in Jira Data Center AppsScaling Indexing and Replication in Jira Data Center Apps
Scaling Indexing and Replication in Jira Data Center AppsAtlassian
 
Sling Component Filters in CQ5
Sling Component Filters in CQ5 Sling Component Filters in CQ5
Sling Component Filters in CQ5 connectwebex
 
Take Full Advantage of the Oracle PL/SQL Compiler
Take Full Advantage of the Oracle PL/SQL CompilerTake Full Advantage of the Oracle PL/SQL Compiler
Take Full Advantage of the Oracle PL/SQL CompilerSteven Feuerstein
 
Arquillian & Citrus
Arquillian & CitrusArquillian & Citrus
Arquillian & Citruschristophd
 
An introduction to unit testing
An introduction to unit testingAn introduction to unit testing
An introduction to unit testingAdam Stephensen
 
Unit Testing Oracle PL/SQL Code: utPLSQL, Excel and More
Unit Testing Oracle PL/SQL Code: utPLSQL, Excel and MoreUnit Testing Oracle PL/SQL Code: utPLSQL, Excel and More
Unit Testing Oracle PL/SQL Code: utPLSQL, Excel and MoreSteven Feuerstein
 
06 integrating extra features and looking forward
06   integrating extra features and looking forward06   integrating extra features and looking forward
06 integrating extra features and looking forwardМарина Босова
 
Getting Reactive with Spring Framework 5.0’s GA release
Getting Reactive with Spring Framework 5.0’s GA releaseGetting Reactive with Spring Framework 5.0’s GA release
Getting Reactive with Spring Framework 5.0’s GA releaseVMware Tanzu
 
Spring boot 3g
Spring boot 3gSpring boot 3g
Spring boot 3gvasya10
 
FAST for SharePoint Deep Dive
FAST for SharePoint Deep DiveFAST for SharePoint Deep Dive
FAST for SharePoint Deep Diveneil_richards
 
Microsoft Fakes, Unit Testing the (almost) Untestable Code
Microsoft Fakes, Unit Testing the (almost) Untestable CodeMicrosoft Fakes, Unit Testing the (almost) Untestable Code
Microsoft Fakes, Unit Testing the (almost) Untestable CodeAleksandar Bozinovski
 
Polaris presentation ioc - code conference
Polaris presentation   ioc - code conferencePolaris presentation   ioc - code conference
Polaris presentation ioc - code conferenceSteven Contos
 

Was ist angesagt? (20)

Improving the Quality of Existing Software - DevIntersection April 2016
Improving the Quality of Existing Software - DevIntersection April 2016Improving the Quality of Existing Software - DevIntersection April 2016
Improving the Quality of Existing Software - DevIntersection April 2016
 
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 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
 
Scaling Indexing and Replication in Jira Data Center Apps
Scaling Indexing and Replication in Jira Data Center AppsScaling Indexing and Replication in Jira Data Center Apps
Scaling Indexing and Replication in Jira Data Center Apps
 
Sling Component Filters in CQ5
Sling Component Filters in CQ5 Sling Component Filters in CQ5
Sling Component Filters in CQ5
 
Take Full Advantage of the Oracle PL/SQL Compiler
Take Full Advantage of the Oracle PL/SQL CompilerTake Full Advantage of the Oracle PL/SQL Compiler
Take Full Advantage of the Oracle PL/SQL Compiler
 
Arquillian & Citrus
Arquillian & CitrusArquillian & Citrus
Arquillian & Citrus
 
An introduction to unit testing
An introduction to unit testingAn introduction to unit testing
An introduction to unit testing
 
Java Concurrent
Java ConcurrentJava Concurrent
Java Concurrent
 
Spring Boot Intro
Spring Boot IntroSpring Boot Intro
Spring Boot Intro
 
Unit Testing Oracle PL/SQL Code: utPLSQL, Excel and More
Unit Testing Oracle PL/SQL Code: utPLSQL, Excel and MoreUnit Testing Oracle PL/SQL Code: utPLSQL, Excel and More
Unit Testing Oracle PL/SQL Code: utPLSQL, Excel and More
 
06 integrating extra features and looking forward
06   integrating extra features and looking forward06   integrating extra features and looking forward
06 integrating extra features and looking forward
 
Background processing with hangfire
Background processing with hangfireBackground processing with hangfire
Background processing with hangfire
 
Spring AOP
Spring AOPSpring AOP
Spring AOP
 
Getting Reactive with Spring Framework 5.0’s GA release
Getting Reactive with Spring Framework 5.0’s GA releaseGetting Reactive with Spring Framework 5.0’s GA release
Getting Reactive with Spring Framework 5.0’s GA release
 
Spring boot 3g
Spring boot 3gSpring boot 3g
Spring boot 3g
 
Test Policy and Practices
Test Policy and PracticesTest Policy and Practices
Test Policy and Practices
 
FAST for SharePoint Deep Dive
FAST for SharePoint Deep DiveFAST for SharePoint Deep Dive
FAST for SharePoint Deep Dive
 
Microsoft Fakes, Unit Testing the (almost) Untestable Code
Microsoft Fakes, Unit Testing the (almost) Untestable CodeMicrosoft Fakes, Unit Testing the (almost) Untestable Code
Microsoft Fakes, Unit Testing the (almost) Untestable Code
 
Polaris presentation ioc - code conference
Polaris presentation   ioc - code conferencePolaris presentation   ioc - code conference
Polaris presentation ioc - code conference
 

Ähnlich wie Improving Software Design Through Refactoring and Testing

Improving the Quality of Existing Software
Improving the Quality of Existing SoftwareImproving the Quality of Existing Software
Improving the Quality of Existing SoftwareSteven Smith
 
Improving The Quality of Existing Software
Improving The Quality of Existing SoftwareImproving The Quality of Existing Software
Improving The Quality of Existing SoftwareSteven Smith
 
Refactoring Applications using SOLID Principles
Refactoring Applications using SOLID PrinciplesRefactoring Applications using SOLID Principles
Refactoring Applications using SOLID PrinciplesSteven 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 2018Rohan Rasane
 
STAQ Development Manual (Redacted)
STAQ Development Manual (Redacted)STAQ Development Manual (Redacted)
STAQ Development Manual (Redacted)Mike Subelsky
 
Object-oriented design principles
Object-oriented design principlesObject-oriented design principles
Object-oriented design principlesXiaoyan Chen
 
Cloud and Network Transformation using DevOps methodology : Cisco Live 2015
Cloud and Network Transformation using DevOps methodology : Cisco Live 2015Cloud and Network Transformation using DevOps methodology : Cisco Live 2015
Cloud and Network Transformation using DevOps methodology : Cisco Live 2015Vimal Suba
 
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 BeyondSteve Westgarth
 
Change Management in Hybrid landscapes 2017
Change Management in Hybrid landscapes 2017Change Management in Hybrid landscapes 2017
Change Management in Hybrid landscapes 2017Chris Kernaghan
 
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 appsPhil Leggetter
 
Lucas Gravley - HP - Self-Healing And Monitoring in a DevOps world
Lucas Gravley - HP - Self-Healing And Monitoring in a DevOps worldLucas Gravley - HP - Self-Healing And Monitoring in a DevOps world
Lucas Gravley - HP - Self-Healing And Monitoring in a DevOps worldDevOps Enterprise Summit
 
Start with passing tests (tdd for bugs) v0.5 (22 sep 2016)
Start with passing tests (tdd for bugs) v0.5 (22 sep 2016)Start with passing tests (tdd for bugs) v0.5 (22 sep 2016)
Start with passing tests (tdd for bugs) v0.5 (22 sep 2016)Dinis Cruz
 
5 Considerations When Adopting Automated Testing
5 Considerations When Adopting Automated Testing5 Considerations When Adopting Automated Testing
5 Considerations When Adopting Automated TestingBhupesh Dahal
 
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 ServerRobbie Minshall
 
Best Practices for Building WordPress Applications
Best Practices for Building WordPress ApplicationsBest Practices for Building WordPress Applications
Best Practices for Building WordPress ApplicationsTaylor Lovett
 

Ähnlich wie Improving Software Design Through Refactoring and Testing (20)

Improving the Quality of Existing Software
Improving the Quality of Existing SoftwareImproving the Quality of Existing Software
Improving the Quality of Existing Software
 
Improving The Quality of Existing Software
Improving The Quality of Existing SoftwareImproving The Quality of Existing Software
Improving The Quality 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
 
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
 
Object-oriented design principles
Object-oriented design principlesObject-oriented design principles
Object-oriented design principles
 
Cloud and Network Transformation using DevOps methodology : Cisco Live 2015
Cloud and Network Transformation using DevOps methodology : Cisco Live 2015Cloud and Network Transformation using DevOps methodology : Cisco Live 2015
Cloud and Network Transformation using DevOps methodology : Cisco Live 2015
 
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
 
Change Management in Hybrid landscapes 2017
Change Management in Hybrid landscapes 2017Change Management in Hybrid landscapes 2017
Change Management in Hybrid landscapes 2017
 
CNUG TDD June 2014
CNUG TDD June 2014CNUG TDD June 2014
CNUG TDD June 2014
 
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
 
Mvc
MvcMvc
Mvc
 
Lucas Gravley - HP - Self-Healing And Monitoring in a DevOps world
Lucas Gravley - HP - Self-Healing And Monitoring in a DevOps worldLucas Gravley - HP - Self-Healing And Monitoring in a DevOps world
Lucas Gravley - HP - Self-Healing And Monitoring in a DevOps world
 
Start with passing tests (tdd for bugs) v0.5 (22 sep 2016)
Start with passing tests (tdd for bugs) v0.5 (22 sep 2016)Start with passing tests (tdd for bugs) v0.5 (22 sep 2016)
Start with passing tests (tdd for bugs) v0.5 (22 sep 2016)
 
5 Considerations When Adopting Automated Testing
5 Considerations When Adopting Automated Testing5 Considerations When Adopting Automated Testing
5 Considerations When Adopting Automated Testing
 
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
 
what-is-devops.ppt
what-is-devops.pptwhat-is-devops.ppt
what-is-devops.ppt
 
Keeping up with PHP
Keeping up with PHPKeeping up with PHP
Keeping up with PHP
 
Best Practices for Building WordPress Applications
Best Practices for Building WordPress ApplicationsBest Practices for Building WordPress Applications
Best Practices for Building WordPress Applications
 

Mehr von 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 PatternsSteven Smith
 
Introducing Domain Driven Design - codemash
Introducing Domain Driven Design - codemashIntroducing Domain Driven Design - codemash
Introducing Domain Driven Design - codemashSteven Smith
 
Introducing ASP.NET Core 2.0
Introducing ASP.NET Core 2.0Introducing ASP.NET Core 2.0
Introducing ASP.NET Core 2.0Steven Smith
 
Decoupling with Domain Events
Decoupling with Domain EventsDecoupling with Domain Events
Decoupling with Domain EventsSteven 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 5Steven Smith
 
My Iraq Experience
My Iraq ExperienceMy Iraq Experience
My Iraq ExperienceSteven 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 MVCSteven Smith
 
Breaking Dependencies to Allow Unit Testing
Breaking Dependencies to Allow Unit TestingBreaking Dependencies to Allow Unit Testing
Breaking Dependencies to Allow Unit TestingSteven 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 aspconf2012
Common asp.net design patterns aspconf2012Common asp.net design patterns aspconf2012
Common asp.net design patterns aspconf2012Steven 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 ProgrammingSteven Smith
 
Cinci ug-january2011-anti-patterns
Cinci ug-january2011-anti-patternsCinci ug-january2011-anti-patterns
Cinci ug-january2011-anti-patternsSteven Smith
 

Mehr von Steven Smith (15)

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 - codemash
Introducing Domain Driven Design - codemashIntroducing Domain Driven Design - codemash
Introducing Domain Driven Design - codemash
 
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
 
Breaking Dependencies to Allow Unit Testing
Breaking Dependencies to Allow Unit TestingBreaking Dependencies to Allow Unit Testing
Breaking Dependencies to Allow Unit Testing
 
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 aspconf2012
Common asp.net design patterns aspconf2012Common asp.net design patterns aspconf2012
Common asp.net design patterns aspconf2012
 
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
 

Kürzlich hochgeladen

Integration and Automation in Practice: CI/CD in Mule Integration and Automat...
Integration and Automation in Practice: CI/CD in Mule Integration and Automat...Integration and Automation in Practice: CI/CD in Mule Integration and Automat...
Integration and Automation in Practice: CI/CD in Mule Integration and Automat...Patryk Bandurski
 
Vertex AI Gemini Prompt Engineering Tips
Vertex AI Gemini Prompt Engineering TipsVertex AI Gemini Prompt Engineering Tips
Vertex AI Gemini Prompt Engineering TipsMiki Katsuragi
 
My INSURER PTE LTD - Insurtech Innovation Award 2024
My INSURER PTE LTD - Insurtech Innovation Award 2024My INSURER PTE LTD - Insurtech Innovation Award 2024
My INSURER PTE LTD - Insurtech Innovation Award 2024The Digital Insurer
 
Anypoint Exchange: It’s Not Just a Repo!
Anypoint Exchange: It’s Not Just a Repo!Anypoint Exchange: It’s Not Just a Repo!
Anypoint Exchange: It’s Not Just a Repo!Manik S Magar
 
WordPress Websites for Engineers: Elevate Your Brand
WordPress Websites for Engineers: Elevate Your BrandWordPress Websites for Engineers: Elevate Your Brand
WordPress Websites for Engineers: Elevate Your Brandgvaughan
 
Human Factors of XR: Using Human Factors to Design XR Systems
Human Factors of XR: Using Human Factors to Design XR SystemsHuman Factors of XR: Using Human Factors to Design XR Systems
Human Factors of XR: Using Human Factors to Design XR SystemsMark Billinghurst
 
My Hashitalk Indonesia April 2024 Presentation
My Hashitalk Indonesia April 2024 PresentationMy Hashitalk Indonesia April 2024 Presentation
My Hashitalk Indonesia April 2024 PresentationRidwan Fadjar
 
Bun (KitWorks Team Study 노별마루 발표 2024.4.22)
Bun (KitWorks Team Study 노별마루 발표 2024.4.22)Bun (KitWorks Team Study 노별마루 발표 2024.4.22)
Bun (KitWorks Team Study 노별마루 발표 2024.4.22)Wonjun Hwang
 
Designing IA for AI - Information Architecture Conference 2024
Designing IA for AI - Information Architecture Conference 2024Designing IA for AI - Information Architecture Conference 2024
Designing IA for AI - Information Architecture Conference 2024Enterprise Knowledge
 
Artificial intelligence in cctv survelliance.pptx
Artificial intelligence in cctv survelliance.pptxArtificial intelligence in cctv survelliance.pptx
Artificial intelligence in cctv survelliance.pptxhariprasad279825
 
CloudStudio User manual (basic edition):
CloudStudio User manual (basic edition):CloudStudio User manual (basic edition):
CloudStudio User manual (basic edition):comworks
 
DevEX - reference for building teams, processes, and platforms
DevEX - reference for building teams, processes, and platformsDevEX - reference for building teams, processes, and platforms
DevEX - reference for building teams, processes, and platformsSergiu Bodiu
 
"Debugging python applications inside k8s environment", Andrii Soldatenko
"Debugging python applications inside k8s environment", Andrii Soldatenko"Debugging python applications inside k8s environment", Andrii Soldatenko
"Debugging python applications inside k8s environment", Andrii SoldatenkoFwdays
 
Unleash Your Potential - Namagunga Girls Coding Club
Unleash Your Potential - Namagunga Girls Coding ClubUnleash Your Potential - Namagunga Girls Coding Club
Unleash Your Potential - Namagunga Girls Coding ClubKalema Edgar
 
Powerpoint exploring the locations used in television show Time Clash
Powerpoint exploring the locations used in television show Time ClashPowerpoint exploring the locations used in television show Time Clash
Powerpoint exploring the locations used in television show Time Clashcharlottematthew16
 
Streamlining Python Development: A Guide to a Modern Project Setup
Streamlining Python Development: A Guide to a Modern Project SetupStreamlining Python Development: A Guide to a Modern Project Setup
Streamlining Python Development: A Guide to a Modern Project SetupFlorian Wilhelm
 
Vector Databases 101 - An introduction to the world of Vector Databases
Vector Databases 101 - An introduction to the world of Vector DatabasesVector Databases 101 - An introduction to the world of Vector Databases
Vector Databases 101 - An introduction to the world of Vector DatabasesZilliz
 
Tampa BSides - Chef's Tour of Microsoft Security Adoption Framework (SAF)
Tampa BSides - Chef's Tour of Microsoft Security Adoption Framework (SAF)Tampa BSides - Chef's Tour of Microsoft Security Adoption Framework (SAF)
Tampa BSides - Chef's Tour of Microsoft Security Adoption Framework (SAF)Mark Simos
 
Install Stable Diffusion in windows machine
Install Stable Diffusion in windows machineInstall Stable Diffusion in windows machine
Install Stable Diffusion in windows machinePadma Pradeep
 

Kürzlich hochgeladen (20)

Integration and Automation in Practice: CI/CD in Mule Integration and Automat...
Integration and Automation in Practice: CI/CD in Mule Integration and Automat...Integration and Automation in Practice: CI/CD in Mule Integration and Automat...
Integration and Automation in Practice: CI/CD in Mule Integration and Automat...
 
Vertex AI Gemini Prompt Engineering Tips
Vertex AI Gemini Prompt Engineering TipsVertex AI Gemini Prompt Engineering Tips
Vertex AI Gemini Prompt Engineering Tips
 
My INSURER PTE LTD - Insurtech Innovation Award 2024
My INSURER PTE LTD - Insurtech Innovation Award 2024My INSURER PTE LTD - Insurtech Innovation Award 2024
My INSURER PTE LTD - Insurtech Innovation Award 2024
 
Anypoint Exchange: It’s Not Just a Repo!
Anypoint Exchange: It’s Not Just a Repo!Anypoint Exchange: It’s Not Just a Repo!
Anypoint Exchange: It’s Not Just a Repo!
 
WordPress Websites for Engineers: Elevate Your Brand
WordPress Websites for Engineers: Elevate Your BrandWordPress Websites for Engineers: Elevate Your Brand
WordPress Websites for Engineers: Elevate Your Brand
 
Human Factors of XR: Using Human Factors to Design XR Systems
Human Factors of XR: Using Human Factors to Design XR SystemsHuman Factors of XR: Using Human Factors to Design XR Systems
Human Factors of XR: Using Human Factors to Design XR Systems
 
My Hashitalk Indonesia April 2024 Presentation
My Hashitalk Indonesia April 2024 PresentationMy Hashitalk Indonesia April 2024 Presentation
My Hashitalk Indonesia April 2024 Presentation
 
Bun (KitWorks Team Study 노별마루 발표 2024.4.22)
Bun (KitWorks Team Study 노별마루 발표 2024.4.22)Bun (KitWorks Team Study 노별마루 발표 2024.4.22)
Bun (KitWorks Team Study 노별마루 발표 2024.4.22)
 
Designing IA for AI - Information Architecture Conference 2024
Designing IA for AI - Information Architecture Conference 2024Designing IA for AI - Information Architecture Conference 2024
Designing IA for AI - Information Architecture Conference 2024
 
Artificial intelligence in cctv survelliance.pptx
Artificial intelligence in cctv survelliance.pptxArtificial intelligence in cctv survelliance.pptx
Artificial intelligence in cctv survelliance.pptx
 
CloudStudio User manual (basic edition):
CloudStudio User manual (basic edition):CloudStudio User manual (basic edition):
CloudStudio User manual (basic edition):
 
DevEX - reference for building teams, processes, and platforms
DevEX - reference for building teams, processes, and platformsDevEX - reference for building teams, processes, and platforms
DevEX - reference for building teams, processes, and platforms
 
"Debugging python applications inside k8s environment", Andrii Soldatenko
"Debugging python applications inside k8s environment", Andrii Soldatenko"Debugging python applications inside k8s environment", Andrii Soldatenko
"Debugging python applications inside k8s environment", Andrii Soldatenko
 
Unleash Your Potential - Namagunga Girls Coding Club
Unleash Your Potential - Namagunga Girls Coding ClubUnleash Your Potential - Namagunga Girls Coding Club
Unleash Your Potential - Namagunga Girls Coding Club
 
Powerpoint exploring the locations used in television show Time Clash
Powerpoint exploring the locations used in television show Time ClashPowerpoint exploring the locations used in television show Time Clash
Powerpoint exploring the locations used in television show Time Clash
 
Streamlining Python Development: A Guide to a Modern Project Setup
Streamlining Python Development: A Guide to a Modern Project SetupStreamlining Python Development: A Guide to a Modern Project Setup
Streamlining Python Development: A Guide to a Modern Project Setup
 
Vector Databases 101 - An introduction to the world of Vector Databases
Vector Databases 101 - An introduction to the world of Vector DatabasesVector Databases 101 - An introduction to the world of Vector Databases
Vector Databases 101 - An introduction to the world of Vector Databases
 
Tampa BSides - Chef's Tour of Microsoft Security Adoption Framework (SAF)
Tampa BSides - Chef's Tour of Microsoft Security Adoption Framework (SAF)Tampa BSides - Chef's Tour of Microsoft Security Adoption Framework (SAF)
Tampa BSides - Chef's Tour of Microsoft Security Adoption Framework (SAF)
 
Install Stable Diffusion in windows machine
Install Stable Diffusion in windows machineInstall Stable Diffusion in windows machine
Install Stable Diffusion in windows machine
 
E-Vehicle_Hacking_by_Parul Sharma_null_owasp.pptx
E-Vehicle_Hacking_by_Parul Sharma_null_owasp.pptxE-Vehicle_Hacking_by_Parul Sharma_null_owasp.pptx
E-Vehicle_Hacking_by_Parul Sharma_null_owasp.pptx
 

Improving Software Design Through Refactoring and Testing

  • 1. Improving the Design of Existing Software Steve Smith Founder, DevIQ @ardalis | DevIQ.com
  • 3. Weekly DevTips Podcast and Newsletter • Ardalis.com/tips • WeeklyDevTips.com
  • 5.
  • 6.
  • 7. Technical Debt • Low quality code and shortcuts in our applications • Financial Debt • Principal – Amount borrowed • Interest – Additional cost of the debt • Technical debt • Principal – Amount of time required to code solution “properly” • Interest – Additional time needed to work around improper code http://deviq.com/technical-debt/
  • 9.
  • 11. Technical Debt is a Design Decision (or series of decisions)
  • 13.
  • 14. Preventive Maintenance • Refactoring • Eliminate Duplication • Simplify Design • AutomatedTests • Verify correctness • Avoid regressions • Increase Confidence
  • 15. When should you refactor? • While delivering value
  • 16. “ ” 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.
  • 17.
  • 18. Refactoring Should Not Change System Behavior
  • 19. The Refactoring Process • Verify existing behavior • Write CharacterizationTests if none exist • Find test points • Break dependencies • Apply Refactoring • Confirm existing behavior is preserved  Commit the working code! Commit the working code!
  • 20. 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
  • 21.
  • 22. Brownfield / Legacy Development
  • 23. Maximize Code Changes Made to New Classes
  • 24. Why new classes? • Nothing depends on them (yet) • You can write them to be testable • Even in an otherwise hard-to-test application
  • 25. Add High-ValueTests to Legacy Apps • Probably not writtenTest-First • Trying to UnitTest Everything is likely cost-prohibitive • Start by writing tests for bugs • Verify the bug behavior with a test • Make the test pass by fixing the bug
  • 26. S O L I DPrinciples http://flickr.com/photos/kevinkemmerer/2772526725/
  • 27. Principles of OO Design 0. Don’t RepeatYourself (DRY) 1. Single Responsibility 2. Open/Closed 3. Liskov Substitution 4. Interface Segregation 5. Dependency Inversion Pluralsight Course: http://bit.ly/SOLID-OOP
  • 28.
  • 29.
  • 30. Don’t Repeat RepeatYourself •Duplication in logic calls for abstraction •Duplication in process calls for automation
  • 31. Common Refactorings • Replace Magic Number/String • Parameterize Method • Pull Up Field • Pull Up Method • Replace Conditional With Polymorphism • Introduce Method
  • 32. 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 }
  • 33. 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
  • 34.
  • 35. 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
  • 36. What is a responsibility? “My CustomerManager class is only responsible for anything to do with a Customer.That follows SRP, right?”
  • 37. Examples of Responsibilities • Persistence • Validation • Notification • Error Handling • Logging • Class Selection / Construction • Formatting • Parsing • Mapping
  • 38. Dependency and Coupling • Excessive coupling makes changing legacy software difficult • Breaking apart responsibilities and dependencies is a large part of working with existing code
  • 39. Common Refactorings • Extract Class • Extract Method • Move Method
  • 40. Heuristics and Code Smells • Visual Studio Metrics
  • 43.
  • 44. Code Smell: Regions More on Regions: http://ardalis.com/regional-differences
  • 45.
  • 46. 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
  • 47. 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
  • 48. Common Refactorings • Extract Interface / Apply Strategy Pattern • Parameterize Method • FormTemplate Method
  • 51. 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; }
  • 52. 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; }
  • 53.
  • 54. 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.
  • 55. Common Refactorings • Collapse Hierarchy • Pull Up / Push Down Field • Pull Up / Push Down Method
  • 56. Liskov Substitution Fail foreach(var employee in employees) { if(employee is Manager) { Helpers.PrintManager(employee as Manager); break; } Helpers.PrintEmployee(employee); }
  • 57. Liskov Substitution OK foreach(var employee in employees) { employee.Print(); // or Helpers.PrintEmployee(employee); }
  • 58. 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
  • 59.
  • 60. 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
  • 62. Keep Interfaces Small and Focused
  • 64. 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); }
  • 65. 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!
  • 66.
  • 67. 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#
  • 68. 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)
  • 69. DIP Architecture (aka Ports and Adapters)
  • 70. 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
  • 71. Common Refactorings • Extract Class • Extract Interface / Apply Strategy Pattern • Extract Method • Introduce Service Locator / Container
  • 73. 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/
  • 75. DIP OK (Strategy Pattern / DI)
  • 76. DIP OK (Strategy Pattern / DI)
  • 77. Improving Quality Across the Industry
  • 78.
  • 79. 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?
  • 80. 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
  • 81. 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
  • 82. 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
  • 83. Learn More • DevIQ.com • Ardalis.com • WeeklyDevTips.com • Twitter: @ardalis • Pluralsight: • SOLID Principles of OO Design http://bit.ly/SOLID-OOP • N-Tier Architecture in C# http://bit.ly/PS-NTier1 • Refactoring Fundamentals http://bit.ly/PS-Refactoring • Domain-Driven Design Fundamentals http://bit.ly/ddd-fundamentals • Design Pattern Library http://bit.ly/PS-design-patterns • Pair Programming http://bit.ly/PS-PairProgramming
  • 84. • 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
  • 85. 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

Hinweis der Redaktion

  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). Sometimes principal of technical debt can grow, as when a lot of code is built on top of debt-ridden code. There isn’t a perfect metaphor for this that I’m aware of.
  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. Building in quality becomes a habit. Working with well-crafted code is more enjoyable. Create a virtuous cycle. Help yourself and your team fall into the pit of success that is clean code.
  8. 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).
  9. 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.
  10. 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.
  11. 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.
  12. Principles provide guidance for refactoring. They provide a consistent target to aim toward.
  13. 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.
  14. 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.
  15. Using Excel
  16. 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)
  17. Open-Closed Principle
  18. 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.
  19. 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?
  20. 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).
  21. 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.
  22. 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.
  23. 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
  24. 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.
  25. “Legacy” N-Tier Logical Architecture
  26. Hidden Dependencies
  27. Extract interface Implement interface with tightly coupled original code
  28. Mention Explicit Dependencies Principle
  29. Water break
  30. Get them excited.