SlideShare a Scribd company logo
1 of 75
Design for testability as a way to good coding Simone ChiarettaArchitect, Council of the EU http://codeclimber.net.nz Twitter: @simonech December 9th, 2010
Who the hell am I? Simone Chiaretta Microsoft MVP ASP.NET ASP Insider Blogger – http://codeclimber.net.nz ItalianALT.NET UG Founder OpenSource developer Climber All Around Nice Guy Disclaimer:"The viewsexpressed are purelythose of the speaker and may not in anycircumstancesberegarded as stating an official position of the Council"
What are we going to talk about? What is “Good Design”? Testability requirements? What is Design for Testability? What is Dependency Injection? What is Inversion of Control? How to do IoC via DI using Ninject? How to do IoC via DI using Unity? References
What is Good Design?
What is Good Design High Cohesion Low Coupling Good Encapsulation
What is Good Design
Solid: Single Responsibility Principle (SRP) A class should have one, and only one, reason to change.
Solid: SingleResponsibilityPrinciple (SRP) “If a class has more then one responsibility, then the responsibilities become coupled. Changes to one responsibility may impair or inhibit the class’ ability to meet the others. This kind of coupling leads to fragile designs that break in unexpected ways when changed.” ,[object Object],[object Object]
sOlid: Open Closed Principle (OCP) You should be able to extend a classes behavior, without modifying it.
sOlid: OpenClosedPrinciple (OCP) “Modules that conform to the open-closed principle have two primary attributes. They are “Open For Extension”. This means that the behavior of the module can be extended. That we can make the module behave in new and different ways as the requirements of the application change, or to meet the needs of new applications. They are “Closed for Modification”.The source code of such a module is inviolate. No one is allowed to make source code changes to it.” - Robert C. Martin
sOlid: OpenClosedPrinciple (OCP) Email Sender FileReader Service IFileFormat Reader Flat File XML File
soLid: Liskov Substitution Principle (LSP) Derived classes must be substitutable for their base classes.
soLid: LiskovSubstitutionPrinciple (LSP) “If for each object o1 of type S there is an object o2 of type T such that for all programs P defined in terms of T, the behavior of P is unchanged when o1 is substituted for o2 then S is a subtype of T.” 	- Barbara Liskov
soLid: LiskovSubstitutionPrinciple (LSP) Email Sender FileReader Service Database IFileFormat Reader Flat File XML File Database Connection File
soLid: LiskovSubstitutionPrinciple (LSP) Database Database Reader Service Email Sender Flat File IFileFormat Reader FileReader Service XML File
solId: Interface Segregation Principle (ISP) Clientsshouldnotbeforcedtodependuponinterfacestheydon’t use
solId: InterfaceSegregationPrinciple (ISP) “This principle deals with the disadvantages of ‘fat’ interfaces. Classes that have ‘fat’ interfaces are classes whose interfaces are not cohesive. In other words, the interfaces of the class can be broken up into groups of member functions. Each group serves a different set of clients. Thus some clients use one group of member functions, and other clients use the other groups.” 	- Robert Martin
solId: InterfaceSegregationPrinciple (ISP) EmailSender EmailSender Database Reader Service FileReader Service ,[object Object]
ReadFile
ReadFromDb
SendEmail
GetMessageBody
GetMessageBody,[object Object]
soliD: DependencyInversionPrinciple (DIP) “What is it that makes a design rigid, fragile and immobile? It is the interdependence of the modules within that design. A design is rigid if it cannot be easily changed. Such rigidity is due to the fact that a single change to heavily interdependent software begins a cascade of changes in dependent modules.” 	- Robert Martin
soliD: DependencyInversionPrinciple (DIP) Flat File Reader Xml File Reader Email Sender Database Reader Service IMessageInfoRetriever IEmailService ProcessingService IFileFormat Reader File Reader Service
Before and After IMessageInfo Retriever IEmailSender EmailProcessingService Email Sending App Database Database Reader Service Flat File IMessage Info Retriever XML File IFileFormat Reader FileReader Service File IEmail Service EmailService Before After
How to test for “good design”? You can’t Actually you can  Clear?
Testability Requirements
Testability Actors System Under Test Depended On Component Mock/Fake/Stub
Testability Concepts Test just one feature Indipendency from environment Indipendency from dependencies Fast
Design for Testability
Design for Testability = Good Design Good design is difficult to measure Easily testable = Good Design
What is Dependency Injection
Bad Code Demo: Hard-Coded Dependencies 1-2
The problem of strong coupling Rigid – Must change the Climber code to change the Tools he uses Fragile – Changes to the Tools can affect the Climbers Not Testable – Cannot replace the Tools with a stub/fake when I want to test the Climber in isolation
Better Code Demo: Hard-Coded Dependencies with Interface 3
Still problems We have lower coupling but still Climber has to be changed to change tools
Slightly Better Code Demo: Hard-Coded Dependencies with Service Locator 4
Still problems Still Climber depends on the Locator Just moving the problem inside another module
Introducing Dependency Injection Demo: Dependency Injection by Hand 5
Good, isn’t it? Climber is always the same, and doesn’t know how to “get” the tools The Climber is given the tools he has to use
Dependency Injection Are we done? NOT YET!
Introducing Dependency Injection Demo: Dependency Injection by Hand (more complex) 6
Needs Improvements Host must know how to assemble dependencies Weloose encapsulation
What is Inversion of Control
Inversion of Control Demo: Inversion of Control 7
What we achieved Still have DIP Got encapsulation back Dependencies are handled by external component
How to configure XML Attributes Fluent API all of them
Many IoCC …
Ninject
The Kernel Factory Method on Steroids Hold the configuration Returns objects IKernel kernel = new StandardKernel( 					new ClimbingModule()); var climber = kernel.Get<Climber>();
Modules Modules hold specific configurations Configuration through Fluent API Bind<Climber>().ToSelf(); Bind<IClimbingTools>().To<QuickDraws>();
Inversion of Control Demo: Inversion of Control (complex) 8
Different kinds of Injection Constructor Injection Property Injection Method Injection Through Factory Method
Attributes Are used to help discriminate injection patterns [Inject] public IClimbingTools tools {get; set;} [Inject] public void GetReady(IClimbingTools tools)
Inversion of Control Demo: Attributes Injection Patterns 9
Behaviours Singleton (Default) Transient Per Thread Per Request BYO Bind<Climber>().ToSelf().InTransientScope(); Bind<Climber>().ToSelf().InSingletonScope();
Inversion of Control Demo: Activation Behaviours 10
But there is more... Constructor Parameters Contextual Binding Named Binding Bind<IClimbingTools>().To<IceScrews>() 	.WithConstructorArgument("brand", 					"Black Diamond"); Bind<IClimbingTools>().To<QuickDraws>() 	.WhenInjectedInto(typeof(SportClimber)); Bind<Climber>().To<SportClimber>() 					.Named("Simone"); climber = kernel.Get<Climber>("Simone");
Inversion of Control Demo: Advanced Features 11
Finally Some Testing No need to use IoC any more (and you should not) MockTools tools = new MockTools(); Climber climber = new Climber(tools); climber.Climb(); Assert.IsTrue(tools.Placed);
Finally some Testing Demo: Testing 12
P&P Unity
Unity Microsoft IoC container Configured via code Configured through XML myContainer     .RegisterType<IClimbingTools, QuickDraws>(); <unity> <typeAliases>   <typeAlias alias="IClimbingTools” type="ClimbDemoIoCUnity.IClimbingTools, ClimbDemoIoCUnity" />   <typeAlias alias="QuickDraws” type="ClimbDemoIoCUnity.Tools.QuickDraws, ClimbDemoIoCUnity" /> </typeAliases> <containers>   <container> 	<types> 	  <type type="IClimbingTools" mapTo="IceScrews" /> 	</types>   </container> </containers> </unity>
Unity Demo: Unity 13
Bonus section: Func
Func By Daniel Cazzulino (of Moq fame) The fastestIoCavailable Doesn’t usereflection Alwayswrite factory method container.Register<IClimbingTools>( 				c => newQuickDraws()); container.Register( 		c => newClimber( c.Resolve<IClimbingTools>()));
Bonus section: Func Demo: Func 14
IoC inside other hosts
IoC in other hosts IoC shines when activation is already delegated to factories ASP.NET MVC WCF Requires changes in the default “object factory” ControllerFactory ServiceHostFactory
IoC in other hosts Demo: ASP.NET MVC 15
Conclusions
Call for Actions Think about a project you worked on Think about any maintainabily/change issue you had: Most likely they would have been solved with DI/IoC Think how DI/IoC could have helped
Main takeaways DI/IoC helps building service oriented applications DI/IoC helps managing dependencies DI/IoC helps bulding highly cohese, loose coupled code while maintaling encapsulation
References Uncle Bob’s Principle Of Object Oriented Development: http://butunclebob.com/ArticleS.UncleBob.PrinciplesOfOod OO Design Principles:http://www.oodesign.com/design-principles.html Complete SOLID slides and demo (Derick Bailey):http://www.lostechies.com/media/p/5415.aspx Ninject:http://ninject.org/  - v2http://github.com/enkari/ninject/  - v2.2 beta p&p Unity:http://unity.codeplex.com/ - v2 (part of EntLib5) Funq:http://funq.codeplex.com/

More Related Content

What's hot

An Introduction to Test Driven Development
An Introduction to Test Driven Development An Introduction to Test Driven Development
An Introduction to Test Driven Development CodeOps Technologies LLP
 
Test Driven Development
Test Driven DevelopmentTest Driven Development
Test Driven Developmentguestc8093a6
 
Test-Driven Development
Test-Driven DevelopmentTest-Driven Development
Test-Driven DevelopmentJohn Blum
 
2016 10-04: tdd++: tdd made easier
2016 10-04: tdd++: tdd made easier2016 10-04: tdd++: tdd made easier
2016 10-04: tdd++: tdd made easierChristian Hujer
 
A Not-So-Serious Introduction to Test Driven Development (TDD)
A Not-So-Serious Introduction to Test Driven Development (TDD) A Not-So-Serious Introduction to Test Driven Development (TDD)
A Not-So-Serious Introduction to Test Driven Development (TDD) CodeOps Technologies LLP
 
Unit testing & TDD concepts with best practice guidelines.
Unit testing & TDD concepts with best practice guidelines.Unit testing & TDD concepts with best practice guidelines.
Unit testing & TDD concepts with best practice guidelines.Mohamed Taman
 
Getting started with Test Driven Development
Getting started with Test Driven DevelopmentGetting started with Test Driven Development
Getting started with Test Driven DevelopmentFerdous Mahmud Shaon
 
Test-Driven Development In Action
Test-Driven Development In ActionTest-Driven Development In Action
Test-Driven Development In ActionJon Kruger
 
TDD And Refactoring
TDD And RefactoringTDD And Refactoring
TDD And RefactoringNaresh Jain
 
Dependency Injection in iOS
Dependency Injection in iOSDependency Injection in iOS
Dependency Injection in iOSPablo Villar
 
Test Driven Development
Test Driven DevelopmentTest Driven Development
Test Driven DevelopmentMireia Sangalo
 
Agile Programming Systems # TDD intro
Agile Programming Systems # TDD introAgile Programming Systems # TDD intro
Agile Programming Systems # TDD introVitaliy Kulikov
 
Test Driven Development
Test Driven DevelopmentTest Driven Development
Test Driven DevelopmentDhaval Dalal
 
Test-Driven Development (TDD)
Test-Driven Development (TDD)Test-Driven Development (TDD)
Test-Driven Development (TDD)Brian Rasmussen
 
The WHY behind TDD/BDD and the HOW with RSpec
The WHY behind TDD/BDD and the HOW with RSpecThe WHY behind TDD/BDD and the HOW with RSpec
The WHY behind TDD/BDD and the HOW with RSpecBen Mabey
 

What's hot (18)

An Introduction to Test Driven Development
An Introduction to Test Driven Development An Introduction to Test Driven Development
An Introduction to Test Driven Development
 
Test Driven Development
Test Driven DevelopmentTest Driven Development
Test Driven Development
 
Testing 101
Testing 101Testing 101
Testing 101
 
Test Driven Development
Test Driven DevelopmentTest Driven Development
Test Driven Development
 
Test-Driven Development
Test-Driven DevelopmentTest-Driven Development
Test-Driven Development
 
2016 10-04: tdd++: tdd made easier
2016 10-04: tdd++: tdd made easier2016 10-04: tdd++: tdd made easier
2016 10-04: tdd++: tdd made easier
 
A Not-So-Serious Introduction to Test Driven Development (TDD)
A Not-So-Serious Introduction to Test Driven Development (TDD) A Not-So-Serious Introduction to Test Driven Development (TDD)
A Not-So-Serious Introduction to Test Driven Development (TDD)
 
Unit testing & TDD concepts with best practice guidelines.
Unit testing & TDD concepts with best practice guidelines.Unit testing & TDD concepts with best practice guidelines.
Unit testing & TDD concepts with best practice guidelines.
 
Getting started with Test Driven Development
Getting started with Test Driven DevelopmentGetting started with Test Driven Development
Getting started with Test Driven Development
 
Test-Driven Development In Action
Test-Driven Development In ActionTest-Driven Development In Action
Test-Driven Development In Action
 
TDD And Refactoring
TDD And RefactoringTDD And Refactoring
TDD And Refactoring
 
Dependency Injection in iOS
Dependency Injection in iOSDependency Injection in iOS
Dependency Injection in iOS
 
Test Driven Development
Test Driven DevelopmentTest Driven Development
Test Driven Development
 
Kl assertions 081705
Kl assertions 081705Kl assertions 081705
Kl assertions 081705
 
Agile Programming Systems # TDD intro
Agile Programming Systems # TDD introAgile Programming Systems # TDD intro
Agile Programming Systems # TDD intro
 
Test Driven Development
Test Driven DevelopmentTest Driven Development
Test Driven Development
 
Test-Driven Development (TDD)
Test-Driven Development (TDD)Test-Driven Development (TDD)
Test-Driven Development (TDD)
 
The WHY behind TDD/BDD and the HOW with RSpec
The WHY behind TDD/BDD and the HOW with RSpecThe WHY behind TDD/BDD and the HOW with RSpec
The WHY behind TDD/BDD and the HOW with RSpec
 

Viewers also liked

Solid principles – interface segregation principle
Solid principles – interface segregation principle Solid principles – interface segregation principle
Solid principles – interface segregation principle Nitisak Mooltreesri
 
Daniele Dellafiore - No-Backend Web Architecture | Codemotion Milan 2015
Daniele Dellafiore - No-Backend Web Architecture | Codemotion Milan 2015Daniele Dellafiore - No-Backend Web Architecture | Codemotion Milan 2015
Daniele Dellafiore - No-Backend Web Architecture | Codemotion Milan 2015Codemotion
 
Come scrivere software SOLID(O)
Come scrivere software SOLID(O)Come scrivere software SOLID(O)
Come scrivere software SOLID(O)Innoteam Srl
 
Strategia Oceano Blu 3: Differenziazione e 6 principi di Oceano blu
Strategia Oceano Blu 3: Differenziazione e 6 principi di Oceano bluStrategia Oceano Blu 3: Differenziazione e 6 principi di Oceano blu
Strategia Oceano Blu 3: Differenziazione e 6 principi di Oceano bluManager.it
 
Object Oriented Design SOLID Principles
Object Oriented Design SOLID PrinciplesObject Oriented Design SOLID Principles
Object Oriented Design SOLID Principlesrainynovember12
 
SOLID - Principles of Object Oriented Design
SOLID - Principles of Object Oriented DesignSOLID - Principles of Object Oriented Design
SOLID - Principles of Object Oriented DesignRiccardo Cardin
 

Viewers also liked (8)

Solid principles – interface segregation principle
Solid principles – interface segregation principle Solid principles – interface segregation principle
Solid principles – interface segregation principle
 
(ISP) - Interface Segregation Principle
(ISP)  - Interface Segregation Principle(ISP)  - Interface Segregation Principle
(ISP) - Interface Segregation Principle
 
Daniele Dellafiore - No-Backend Web Architecture | Codemotion Milan 2015
Daniele Dellafiore - No-Backend Web Architecture | Codemotion Milan 2015Daniele Dellafiore - No-Backend Web Architecture | Codemotion Milan 2015
Daniele Dellafiore - No-Backend Web Architecture | Codemotion Milan 2015
 
Object Oriented Design
Object Oriented DesignObject Oriented Design
Object Oriented Design
 
Come scrivere software SOLID(O)
Come scrivere software SOLID(O)Come scrivere software SOLID(O)
Come scrivere software SOLID(O)
 
Strategia Oceano Blu 3: Differenziazione e 6 principi di Oceano blu
Strategia Oceano Blu 3: Differenziazione e 6 principi di Oceano bluStrategia Oceano Blu 3: Differenziazione e 6 principi di Oceano blu
Strategia Oceano Blu 3: Differenziazione e 6 principi di Oceano blu
 
Object Oriented Design SOLID Principles
Object Oriented Design SOLID PrinciplesObject Oriented Design SOLID Principles
Object Oriented Design SOLID Principles
 
SOLID - Principles of Object Oriented Design
SOLID - Principles of Object Oriented DesignSOLID - Principles of Object Oriented Design
SOLID - Principles of Object Oriented Design
 

Similar to Design for testability as a way to good coding (SOLID and IoC)

Functional solid
Functional solidFunctional solid
Functional solidMatt Stine
 
Oleksandr Valetskyy - Become a .NET dependency injection ninja with Ninject
Oleksandr Valetskyy - Become a .NET dependency injection ninja with NinjectOleksandr Valetskyy - Become a .NET dependency injection ninja with Ninject
Oleksandr Valetskyy - Become a .NET dependency injection ninja with NinjectOleksandr Valetskyy
 
Dependency Injection and Autofac
Dependency Injection and AutofacDependency Injection and Autofac
Dependency Injection and Autofacmeghantaylor
 
Evolutionary Design Solid
Evolutionary Design SolidEvolutionary Design Solid
Evolutionary Design SolidSai Venkat
 
Design poo my_jug_en_ppt
Design poo my_jug_en_pptDesign poo my_jug_en_ppt
Design poo my_jug_en_pptagnes_crepet
 
Dependency Inversion Principle
Dependency Inversion PrincipleDependency Inversion Principle
Dependency Inversion PrincipleShahriar Hyder
 
Object Oriented Concepts and Principles
Object Oriented Concepts and PrinciplesObject Oriented Concepts and Principles
Object Oriented Concepts and Principlesdeonpmeyer
 
OpenDaylight Developer Experience 2.0
 OpenDaylight Developer Experience 2.0 OpenDaylight Developer Experience 2.0
OpenDaylight Developer Experience 2.0Michael Vorburger
 
DEVNET-1127 Unifying Application Logic with Datacenter Automation
DEVNET-1127	Unifying Application Logic with Datacenter AutomationDEVNET-1127	Unifying Application Logic with Datacenter Automation
DEVNET-1127 Unifying Application Logic with Datacenter AutomationCisco DevNet
 
The OO Design Principles
The OO Design PrinciplesThe OO Design Principles
The OO Design PrinciplesSteve Zhang
 
C:\Fakepath\Combating Software Entropy 2
C:\Fakepath\Combating Software Entropy 2C:\Fakepath\Combating Software Entropy 2
C:\Fakepath\Combating Software Entropy 2Hammad Rajjoub
 
C:\Fakepath\Combating Software Entropy 2
C:\Fakepath\Combating Software Entropy 2C:\Fakepath\Combating Software Entropy 2
C:\Fakepath\Combating Software Entropy 2Hammad Rajjoub
 
Introduction to Unit Testing
Introduction to Unit TestingIntroduction to Unit Testing
Introduction to Unit TestingSwanky Hsiao
 
DDD and Microservices: Like Peanut Butter and Jelly - Matt Stine
DDD and Microservices: Like Peanut Butter and Jelly - Matt StineDDD and Microservices: Like Peanut Butter and Jelly - Matt Stine
DDD and Microservices: Like Peanut Butter and Jelly - Matt StineVMware Tanzu
 
ConFoo Montreal - Microservices for building an IDE - The innards of JetBrain...
ConFoo Montreal - Microservices for building an IDE - The innards of JetBrain...ConFoo Montreal - Microservices for building an IDE - The innards of JetBrain...
ConFoo Montreal - Microservices for building an IDE - The innards of JetBrain...Maarten Balliauw
 
The Design, Evolution and Use of KernelF
The Design, Evolution and Use of KernelFThe Design, Evolution and Use of KernelF
The Design, Evolution and Use of KernelFMarkus Voelter
 
Project onion - Project Architecture for .Net Core Application
Project onion - Project Architecture for .Net Core ApplicationProject onion - Project Architecture for .Net Core Application
Project onion - Project Architecture for .Net Core ApplicationAbhinav Jha
 

Similar to Design for testability as a way to good coding (SOLID and IoC) (20)

SOLID Code
SOLID CodeSOLID Code
SOLID Code
 
Functional solid
Functional solidFunctional solid
Functional solid
 
Oleksandr Valetskyy - Become a .NET dependency injection ninja with Ninject
Oleksandr Valetskyy - Become a .NET dependency injection ninja with NinjectOleksandr Valetskyy - Become a .NET dependency injection ninja with Ninject
Oleksandr Valetskyy - Become a .NET dependency injection ninja with Ninject
 
Dependency Injection and Autofac
Dependency Injection and AutofacDependency Injection and Autofac
Dependency Injection and Autofac
 
Evolutionary Design Solid
Evolutionary Design SolidEvolutionary Design Solid
Evolutionary Design Solid
 
Design poo my_jug_en_ppt
Design poo my_jug_en_pptDesign poo my_jug_en_ppt
Design poo my_jug_en_ppt
 
Dependency Inversion Principle
Dependency Inversion PrincipleDependency Inversion Principle
Dependency Inversion Principle
 
Object Oriented Concepts and Principles
Object Oriented Concepts and PrinciplesObject Oriented Concepts and Principles
Object Oriented Concepts and Principles
 
OpenDaylight Developer Experience 2.0
 OpenDaylight Developer Experience 2.0 OpenDaylight Developer Experience 2.0
OpenDaylight Developer Experience 2.0
 
DEVNET-1127 Unifying Application Logic with Datacenter Automation
DEVNET-1127	Unifying Application Logic with Datacenter AutomationDEVNET-1127	Unifying Application Logic with Datacenter Automation
DEVNET-1127 Unifying Application Logic with Datacenter Automation
 
The OO Design Principles
The OO Design PrinciplesThe OO Design Principles
The OO Design Principles
 
C:\Fakepath\Combating Software Entropy 2
C:\Fakepath\Combating Software Entropy 2C:\Fakepath\Combating Software Entropy 2
C:\Fakepath\Combating Software Entropy 2
 
C:\Fakepath\Combating Software Entropy 2
C:\Fakepath\Combating Software Entropy 2C:\Fakepath\Combating Software Entropy 2
C:\Fakepath\Combating Software Entropy 2
 
Introduction to Unit Testing
Introduction to Unit TestingIntroduction to Unit Testing
Introduction to Unit Testing
 
Design for Testability
Design for TestabilityDesign for Testability
Design for Testability
 
DDD and Microservices: Like Peanut Butter and Jelly - Matt Stine
DDD and Microservices: Like Peanut Butter and Jelly - Matt StineDDD and Microservices: Like Peanut Butter and Jelly - Matt Stine
DDD and Microservices: Like Peanut Butter and Jelly - Matt Stine
 
ConFoo Montreal - Microservices for building an IDE - The innards of JetBrain...
ConFoo Montreal - Microservices for building an IDE - The innards of JetBrain...ConFoo Montreal - Microservices for building an IDE - The innards of JetBrain...
ConFoo Montreal - Microservices for building an IDE - The innards of JetBrain...
 
The Design, Evolution and Use of KernelF
The Design, Evolution and Use of KernelFThe Design, Evolution and Use of KernelF
The Design, Evolution and Use of KernelF
 
Orchestration, the conductor's score
Orchestration, the conductor's scoreOrchestration, the conductor's score
Orchestration, the conductor's score
 
Project onion - Project Architecture for .Net Core Application
Project onion - Project Architecture for .Net Core ApplicationProject onion - Project Architecture for .Net Core Application
Project onion - Project Architecture for .Net Core Application
 

More from Simone Chiaretta

Fast and furious(ly) multilingual: Publishing of EU politics in 24 languages ...
Fast and furious(ly) multilingual: Publishing of EU politics in 24 languages ...Fast and furious(ly) multilingual: Publishing of EU politics in 24 languages ...
Fast and furious(ly) multilingual: Publishing of EU politics in 24 languages ...Simone Chiaretta
 
OpenROV: Node.js takes a dive into the ocean
OpenROV: Node.js takes a dive into the oceanOpenROV: Node.js takes a dive into the ocean
OpenROV: Node.js takes a dive into the oceanSimone Chiaretta
 
What's new in asp.net mvc 4
What's new in asp.net mvc 4What's new in asp.net mvc 4
What's new in asp.net mvc 4Simone Chiaretta
 
FeedTso, History of a WP7 FeedReader
FeedTso, History of a WP7 FeedReaderFeedTso, History of a WP7 FeedReader
FeedTso, History of a WP7 FeedReaderSimone Chiaretta
 
Ruby on Rails vs ASP.NET MVC
Ruby on Rails vs ASP.NET MVCRuby on Rails vs ASP.NET MVC
Ruby on Rails vs ASP.NET MVCSimone Chiaretta
 
Lavorare con applicazioni Brownfield: il caso di 39x27.com
Lavorare con applicazioni Brownfield: il caso di 39x27.comLavorare con applicazioni Brownfield: il caso di 39x27.com
Lavorare con applicazioni Brownfield: il caso di 39x27.comSimone Chiaretta
 

More from Simone Chiaretta (10)

Fast and furious(ly) multilingual: Publishing of EU politics in 24 languages ...
Fast and furious(ly) multilingual: Publishing of EU politics in 24 languages ...Fast and furious(ly) multilingual: Publishing of EU politics in 24 languages ...
Fast and furious(ly) multilingual: Publishing of EU politics in 24 languages ...
 
OpenROV: Node.js takes a dive into the ocean
OpenROV: Node.js takes a dive into the oceanOpenROV: Node.js takes a dive into the ocean
OpenROV: Node.js takes a dive into the ocean
 
La UX delle cose
La UX delle coseLa UX delle cose
La UX delle cose
 
UGIALT.net Keynote
UGIALT.net KeynoteUGIALT.net Keynote
UGIALT.net Keynote
 
What's new in asp.net mvc 4
What's new in asp.net mvc 4What's new in asp.net mvc 4
What's new in asp.net mvc 4
 
FeedTso, History of a WP7 FeedReader
FeedTso, History of a WP7 FeedReaderFeedTso, History of a WP7 FeedReader
FeedTso, History of a WP7 FeedReader
 
Ruby on Rails vs ASP.NET MVC
Ruby on Rails vs ASP.NET MVCRuby on Rails vs ASP.NET MVC
Ruby on Rails vs ASP.NET MVC
 
The ViewModel pattern
The ViewModel patternThe ViewModel pattern
The ViewModel pattern
 
ASP.NET MVC Extensibility
ASP.NET MVC ExtensibilityASP.NET MVC Extensibility
ASP.NET MVC Extensibility
 
Lavorare con applicazioni Brownfield: il caso di 39x27.com
Lavorare con applicazioni Brownfield: il caso di 39x27.comLavorare con applicazioni Brownfield: il caso di 39x27.com
Lavorare con applicazioni Brownfield: il caso di 39x27.com
 

Design for testability as a way to good coding (SOLID and IoC)

  • 1. Design for testability as a way to good coding Simone ChiarettaArchitect, Council of the EU http://codeclimber.net.nz Twitter: @simonech December 9th, 2010
  • 2. Who the hell am I? Simone Chiaretta Microsoft MVP ASP.NET ASP Insider Blogger – http://codeclimber.net.nz ItalianALT.NET UG Founder OpenSource developer Climber All Around Nice Guy Disclaimer:"The viewsexpressed are purelythose of the speaker and may not in anycircumstancesberegarded as stating an official position of the Council"
  • 3. What are we going to talk about? What is “Good Design”? Testability requirements? What is Design for Testability? What is Dependency Injection? What is Inversion of Control? How to do IoC via DI using Ninject? How to do IoC via DI using Unity? References
  • 4. What is Good Design?
  • 5. What is Good Design High Cohesion Low Coupling Good Encapsulation
  • 6. What is Good Design
  • 7. Solid: Single Responsibility Principle (SRP) A class should have one, and only one, reason to change.
  • 8.
  • 9. sOlid: Open Closed Principle (OCP) You should be able to extend a classes behavior, without modifying it.
  • 10. sOlid: OpenClosedPrinciple (OCP) “Modules that conform to the open-closed principle have two primary attributes. They are “Open For Extension”. This means that the behavior of the module can be extended. That we can make the module behave in new and different ways as the requirements of the application change, or to meet the needs of new applications. They are “Closed for Modification”.The source code of such a module is inviolate. No one is allowed to make source code changes to it.” - Robert C. Martin
  • 11. sOlid: OpenClosedPrinciple (OCP) Email Sender FileReader Service IFileFormat Reader Flat File XML File
  • 12. soLid: Liskov Substitution Principle (LSP) Derived classes must be substitutable for their base classes.
  • 13. soLid: LiskovSubstitutionPrinciple (LSP) “If for each object o1 of type S there is an object o2 of type T such that for all programs P defined in terms of T, the behavior of P is unchanged when o1 is substituted for o2 then S is a subtype of T.” - Barbara Liskov
  • 14. soLid: LiskovSubstitutionPrinciple (LSP) Email Sender FileReader Service Database IFileFormat Reader Flat File XML File Database Connection File
  • 15. soLid: LiskovSubstitutionPrinciple (LSP) Database Database Reader Service Email Sender Flat File IFileFormat Reader FileReader Service XML File
  • 16. solId: Interface Segregation Principle (ISP) Clientsshouldnotbeforcedtodependuponinterfacestheydon’t use
  • 17. solId: InterfaceSegregationPrinciple (ISP) “This principle deals with the disadvantages of ‘fat’ interfaces. Classes that have ‘fat’ interfaces are classes whose interfaces are not cohesive. In other words, the interfaces of the class can be broken up into groups of member functions. Each group serves a different set of clients. Thus some clients use one group of member functions, and other clients use the other groups.” - Robert Martin
  • 18.
  • 23.
  • 24. soliD: DependencyInversionPrinciple (DIP) “What is it that makes a design rigid, fragile and immobile? It is the interdependence of the modules within that design. A design is rigid if it cannot be easily changed. Such rigidity is due to the fact that a single change to heavily interdependent software begins a cascade of changes in dependent modules.” - Robert Martin
  • 25. soliD: DependencyInversionPrinciple (DIP) Flat File Reader Xml File Reader Email Sender Database Reader Service IMessageInfoRetriever IEmailService ProcessingService IFileFormat Reader File Reader Service
  • 26. Before and After IMessageInfo Retriever IEmailSender EmailProcessingService Email Sending App Database Database Reader Service Flat File IMessage Info Retriever XML File IFileFormat Reader FileReader Service File IEmail Service EmailService Before After
  • 27. How to test for “good design”? You can’t Actually you can  Clear?
  • 29. Testability Actors System Under Test Depended On Component Mock/Fake/Stub
  • 30. Testability Concepts Test just one feature Indipendency from environment Indipendency from dependencies Fast
  • 32. Design for Testability = Good Design Good design is difficult to measure Easily testable = Good Design
  • 33. What is Dependency Injection
  • 34. Bad Code Demo: Hard-Coded Dependencies 1-2
  • 35. The problem of strong coupling Rigid – Must change the Climber code to change the Tools he uses Fragile – Changes to the Tools can affect the Climbers Not Testable – Cannot replace the Tools with a stub/fake when I want to test the Climber in isolation
  • 36. Better Code Demo: Hard-Coded Dependencies with Interface 3
  • 37. Still problems We have lower coupling but still Climber has to be changed to change tools
  • 38. Slightly Better Code Demo: Hard-Coded Dependencies with Service Locator 4
  • 39. Still problems Still Climber depends on the Locator Just moving the problem inside another module
  • 40. Introducing Dependency Injection Demo: Dependency Injection by Hand 5
  • 41. Good, isn’t it? Climber is always the same, and doesn’t know how to “get” the tools The Climber is given the tools he has to use
  • 42. Dependency Injection Are we done? NOT YET!
  • 43. Introducing Dependency Injection Demo: Dependency Injection by Hand (more complex) 6
  • 44. Needs Improvements Host must know how to assemble dependencies Weloose encapsulation
  • 45. What is Inversion of Control
  • 46. Inversion of Control Demo: Inversion of Control 7
  • 47. What we achieved Still have DIP Got encapsulation back Dependencies are handled by external component
  • 48. How to configure XML Attributes Fluent API all of them
  • 51. The Kernel Factory Method on Steroids Hold the configuration Returns objects IKernel kernel = new StandardKernel( new ClimbingModule()); var climber = kernel.Get<Climber>();
  • 52. Modules Modules hold specific configurations Configuration through Fluent API Bind<Climber>().ToSelf(); Bind<IClimbingTools>().To<QuickDraws>();
  • 53. Inversion of Control Demo: Inversion of Control (complex) 8
  • 54. Different kinds of Injection Constructor Injection Property Injection Method Injection Through Factory Method
  • 55. Attributes Are used to help discriminate injection patterns [Inject] public IClimbingTools tools {get; set;} [Inject] public void GetReady(IClimbingTools tools)
  • 56. Inversion of Control Demo: Attributes Injection Patterns 9
  • 57. Behaviours Singleton (Default) Transient Per Thread Per Request BYO Bind<Climber>().ToSelf().InTransientScope(); Bind<Climber>().ToSelf().InSingletonScope();
  • 58. Inversion of Control Demo: Activation Behaviours 10
  • 59. But there is more... Constructor Parameters Contextual Binding Named Binding Bind<IClimbingTools>().To<IceScrews>() .WithConstructorArgument("brand", "Black Diamond"); Bind<IClimbingTools>().To<QuickDraws>() .WhenInjectedInto(typeof(SportClimber)); Bind<Climber>().To<SportClimber>() .Named("Simone"); climber = kernel.Get<Climber>("Simone");
  • 60. Inversion of Control Demo: Advanced Features 11
  • 61. Finally Some Testing No need to use IoC any more (and you should not) MockTools tools = new MockTools(); Climber climber = new Climber(tools); climber.Climb(); Assert.IsTrue(tools.Placed);
  • 62. Finally some Testing Demo: Testing 12
  • 64. Unity Microsoft IoC container Configured via code Configured through XML myContainer .RegisterType<IClimbingTools, QuickDraws>(); <unity> <typeAliases> <typeAlias alias="IClimbingTools” type="ClimbDemoIoCUnity.IClimbingTools, ClimbDemoIoCUnity" /> <typeAlias alias="QuickDraws” type="ClimbDemoIoCUnity.Tools.QuickDraws, ClimbDemoIoCUnity" /> </typeAliases> <containers> <container> <types> <type type="IClimbingTools" mapTo="IceScrews" /> </types> </container> </containers> </unity>
  • 67. Func By Daniel Cazzulino (of Moq fame) The fastestIoCavailable Doesn’t usereflection Alwayswrite factory method container.Register<IClimbingTools>( c => newQuickDraws()); container.Register( c => newClimber( c.Resolve<IClimbingTools>()));
  • 68. Bonus section: Func Demo: Func 14
  • 70. IoC in other hosts IoC shines when activation is already delegated to factories ASP.NET MVC WCF Requires changes in the default “object factory” ControllerFactory ServiceHostFactory
  • 71. IoC in other hosts Demo: ASP.NET MVC 15
  • 73. Call for Actions Think about a project you worked on Think about any maintainabily/change issue you had: Most likely they would have been solved with DI/IoC Think how DI/IoC could have helped
  • 74. Main takeaways DI/IoC helps building service oriented applications DI/IoC helps managing dependencies DI/IoC helps bulding highly cohese, loose coupled code while maintaling encapsulation
  • 75. References Uncle Bob’s Principle Of Object Oriented Development: http://butunclebob.com/ArticleS.UncleBob.PrinciplesOfOod OO Design Principles:http://www.oodesign.com/design-principles.html Complete SOLID slides and demo (Derick Bailey):http://www.lostechies.com/media/p/5415.aspx Ninject:http://ninject.org/ - v2http://github.com/enkari/ninject/ - v2.2 beta p&p Unity:http://unity.codeplex.com/ - v2 (part of EntLib5) Funq:http://funq.codeplex.com/
  • 76. Contacts – Simone Chiaretta MSN: simone_ch@hotmail.com Blog: English: http://codeclimber.net.nz/ Italian: http://blogs.ugidotnet.org/piyo/ Twitter: @simonech 72
  • 77. Questions? Disclaimer:"The viewsexpressed are purelythose of the speaker and may not in anycircumstancesberegarded as stating an official position of the Council"
  • 78. Rating If you liked this talk, please consider rating it: http://speakerrate.com/talks/5193-design-for-testability-as-a-way-to-good-coding 74 Disclaimer:"The viewsexpressed are purelythose of the speaker and may not in anycircumstancesberegarded as stating an official position of the Council"

Editor's Notes

  1. Cohesion:“A measure of how strongly-related and focused the various responsibilities of a software module are” - WikipediaCoupling:“The degree to which each program module relies on each one of the other modules” – WikipediaEncapsulation:“The hiding of design decisions in a computer program that are most likely to change” - Wikipedia
  2. Jenga game = tower where if you remove one piece, all the tower can collapse
  3. Examplemightbeanemailsendingapplicationthatsendsemailtaking the textfroman external file:Ifyouread the text and send the emailfrom the same class you are breaking the SRPprinciple.Itwouldbebetterto separate thereadingpartfrom the sending one.
  4. It’sallaboutbehaviours and pre/post conditions:A derivedtype can onlyweakenpre-conditionsA derivedtype can onlystreghtenpost-conditions
  5. Imagineyouwanttoputtemplates in a database: youcannot just write a “file” readerthatuses a databaseasitwillneed a connectionstring, and the usershould do differentthingsbased on thetype of thereader, thusmaking the substitutionnottransparent.
  6. Hereitwouldhavebeenbettertocompletely separate thetwothings, andhave a databasereader and a file reader.
  7. After adding the Databasereader, wenowhave the emailsendingservicethat can bothread file anddatabases, andobviouslysendingemails.So it’s betterto split theseresponsibilities in differentinterfaces.
  8. Finally,instead of having the singleobject create theirowndependencies, itis the top-mostclientthatconfigures the systemforwhatitneeds.