SlideShare a Scribd company logo
Design for testability as a
way to good coding
Simone Chiaretta
Architect, 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
► Italian ALT.NET UG Founder
► OpenSource developer
► Climber
► All Around Nice Guy
Disclaimer:"The views expressed are purely those of the speaker and may not in any circumstances be regarded 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: Single Responsibility Principle
(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.”
-Robert C. Martin
Solid: Single Responsibility Principle
(SRP)
sOlid: Open Closed Principle (OCP)
You should be able to extend a classes behavior, without modifying it.
sOlid: Open Closed Principle (OCP)
“Modules that conform to the open-closed principle have
two primary attributes.
1. 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.
2. 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: Open Closed Principle (OCP)
soLid: Liskov Substitution Principle
(LSP)
Derived classes must be substitutable for their base classes.
soLid: Liskov Substitution Principle
(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: Liskov Substitution Principle
(LSP)
soLid: Liskov Substitution Principle
(LSP)
solId: Interface Segregation Principle
(ISP)
Clients should not be forced to depend upon interfaces they don’t use
solId: Interface Segregation Principle
(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: Interface Segregation Principle
(ISP)
soliD: Dependency Inversion Principle
(DIP)
Depend on abstractions, not on concretions.
soliD: Dependency Inversion Principle
(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: Dependency Inversion Principle
(DIP)
Before and After
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
► We loose 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: Funq
Funq
► By Daniel Cazzulino (of Moq fame)
► The fastest IoC available
► Doesn’t use reflection
► Always write factory method
container.Register<IClimbingTools>(
c => new QuickDraws());
container.Register(
c => new Climber(
c.Resolve<IClimbingTools>()));
Bonus section: Func
Demo:
Funq
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.PrinciplesOfO
od
► 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/ - v2
http://github.com/enkari/ninject/ - v2.2 beta
► p&p Unity:
http://unity.codeplex.com/ - v2 (part of EntLib5)
► Funq:
http://funq.codeplex.com/
Contacts – Simone Chiaretta
► MSN: simone_ch@hotmail.com
► Blog:
– English: http://codeclimber.net.nz/
– Italian: http://blogs.ugidotnet.org/piyo/
► Twitter: @simonech
72
Questions?
Disclaimer:"The views expressed are purely those of the speaker and may not in any circumstances be regarded as stating an
official position of the Council"
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 views expressed are purely those of the speaker and may not in any circumstances be regarded as stating an
official position of the Council"

More Related Content

Similar to SOLID Code

Mock Objects, Design and Dependency Inversion Principle
Mock Objects, Design and Dependency Inversion PrincipleMock Objects, Design and Dependency Inversion Principle
Mock Objects, Design and Dependency Inversion Principle
P Heinonen
 
Verilator: Fast, Free, But for Me?
Verilator: Fast, Free, But for Me? Verilator: Fast, Free, But for Me?
Verilator: Fast, Free, But for Me?
DVClub
 
Robots in Swift
Robots in SwiftRobots in Swift
Robots in Swift
Janie Clayton
 
I gotta dependency on dependency injection
I gotta dependency on dependency injectionI gotta dependency on dependency injection
I gotta dependency on dependency injection
mhenroid
 
Refactoring to SOLID Code
Refactoring to SOLID CodeRefactoring to SOLID Code
Refactoring to SOLID Code
Adil Mughal
 
Build software like a bag of marbles, not a castle of LEGO®
Build software like a bag of marbles, not a castle of LEGO®Build software like a bag of marbles, not a castle of LEGO®
Build software like a bag of marbles, not a castle of LEGO®
Hannes Lowette
 
Build software like a bag of marbles, not a castle of LEGO®
Build software like a bag of marbles, not a castle of LEGO®Build software like a bag of marbles, not a castle of LEGO®
Build software like a bag of marbles, not a castle of LEGO®
Hannes Lowette
 
Object Oriented Concepts and Principles
Object Oriented Concepts and PrinciplesObject Oriented Concepts and Principles
Object Oriented Concepts and Principles
deonpmeyer
 
Thinking In Swift
Thinking In SwiftThinking In Swift
Thinking In Swift
Janie Clayton
 
Getting Started with the Angular 2 CLI
Getting Started with the Angular 2 CLIGetting Started with the Angular 2 CLI
Getting Started with the Angular 2 CLI
Jim Lynch
 
SOLID principles-Present
SOLID principles-PresentSOLID principles-Present
SOLID principles-Present
Quang Nguyen
 
Mocking vtcc3 - en
Mocking   vtcc3 - enMocking   vtcc3 - en
Mocking vtcc3 - en
vgrondin
 
Dependency Injection in .NET applications
Dependency Injection in .NET applicationsDependency Injection in .NET applications
Dependency Injection in .NET applications
Babak Naffas
 
Pavlo Zhdanov "Mastering solid and base principles for software design"
Pavlo Zhdanov "Mastering solid and base principles for software design"Pavlo Zhdanov "Mastering solid and base principles for software design"
Pavlo Zhdanov "Mastering solid and base principles for software design"
LogeekNightUkraine
 
OpenDaylight Developer Experience 2.0
 OpenDaylight Developer Experience 2.0 OpenDaylight Developer Experience 2.0
OpenDaylight Developer Experience 2.0
Michael Vorburger
 
Design patterns illustrated-2015-03
Design patterns illustrated-2015-03Design patterns illustrated-2015-03
Design patterns illustrated-2015-03
Herman Peeren
 
Dsug 05 02-15 - ScalDI - lightweight DI in Scala
Dsug 05 02-15 - ScalDI - lightweight DI in ScalaDsug 05 02-15 - ScalDI - lightweight DI in Scala
Dsug 05 02-15 - ScalDI - lightweight DI in Scala
Ugo Matrangolo
 
Commonly used design patterns
Commonly used design patternsCommonly used design patterns
Commonly used design patterns
Mojammel Haque
 
Object Oriented Design Principles
Object Oriented Design PrinciplesObject Oriented Design Principles
Object Oriented Design Principles
Thang Tran Duc
 
C:\Fakepath\Combating Software Entropy 2
C:\Fakepath\Combating Software Entropy 2C:\Fakepath\Combating Software Entropy 2
C:\Fakepath\Combating Software Entropy 2
Hammad Rajjoub
 

Similar to SOLID Code (20)

Mock Objects, Design and Dependency Inversion Principle
Mock Objects, Design and Dependency Inversion PrincipleMock Objects, Design and Dependency Inversion Principle
Mock Objects, Design and Dependency Inversion Principle
 
Verilator: Fast, Free, But for Me?
Verilator: Fast, Free, But for Me? Verilator: Fast, Free, But for Me?
Verilator: Fast, Free, But for Me?
 
Robots in Swift
Robots in SwiftRobots in Swift
Robots in Swift
 
I gotta dependency on dependency injection
I gotta dependency on dependency injectionI gotta dependency on dependency injection
I gotta dependency on dependency injection
 
Refactoring to SOLID Code
Refactoring to SOLID CodeRefactoring to SOLID Code
Refactoring to SOLID Code
 
Build software like a bag of marbles, not a castle of LEGO®
Build software like a bag of marbles, not a castle of LEGO®Build software like a bag of marbles, not a castle of LEGO®
Build software like a bag of marbles, not a castle of LEGO®
 
Build software like a bag of marbles, not a castle of LEGO®
Build software like a bag of marbles, not a castle of LEGO®Build software like a bag of marbles, not a castle of LEGO®
Build software like a bag of marbles, not a castle of LEGO®
 
Object Oriented Concepts and Principles
Object Oriented Concepts and PrinciplesObject Oriented Concepts and Principles
Object Oriented Concepts and Principles
 
Thinking In Swift
Thinking In SwiftThinking In Swift
Thinking In Swift
 
Getting Started with the Angular 2 CLI
Getting Started with the Angular 2 CLIGetting Started with the Angular 2 CLI
Getting Started with the Angular 2 CLI
 
SOLID principles-Present
SOLID principles-PresentSOLID principles-Present
SOLID principles-Present
 
Mocking vtcc3 - en
Mocking   vtcc3 - enMocking   vtcc3 - en
Mocking vtcc3 - en
 
Dependency Injection in .NET applications
Dependency Injection in .NET applicationsDependency Injection in .NET applications
Dependency Injection in .NET applications
 
Pavlo Zhdanov "Mastering solid and base principles for software design"
Pavlo Zhdanov "Mastering solid and base principles for software design"Pavlo Zhdanov "Mastering solid and base principles for software design"
Pavlo Zhdanov "Mastering solid and base principles for software design"
 
OpenDaylight Developer Experience 2.0
 OpenDaylight Developer Experience 2.0 OpenDaylight Developer Experience 2.0
OpenDaylight Developer Experience 2.0
 
Design patterns illustrated-2015-03
Design patterns illustrated-2015-03Design patterns illustrated-2015-03
Design patterns illustrated-2015-03
 
Dsug 05 02-15 - ScalDI - lightweight DI in Scala
Dsug 05 02-15 - ScalDI - lightweight DI in ScalaDsug 05 02-15 - ScalDI - lightweight DI in Scala
Dsug 05 02-15 - ScalDI - lightweight DI in Scala
 
Commonly used design patterns
Commonly used design patternsCommonly used design patterns
Commonly used design patterns
 
Object Oriented Design Principles
Object Oriented Design PrinciplesObject Oriented Design Principles
Object Oriented 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
 

More from NETUserGroupBern

Large Language Models, Data & APIs - Integrating Generative AI Power into you...
Large Language Models, Data & APIs - Integrating Generative AI Power into you...Large Language Models, Data & APIs - Integrating Generative AI Power into you...
Large Language Models, Data & APIs - Integrating Generative AI Power into you...
NETUserGroupBern
 
AAD und .NET
AAD und .NETAAD und .NET
AAD und .NET
NETUserGroupBern
 
SHIFT LEFT WITH DEVSECOPS
SHIFT LEFT WITH DEVSECOPSSHIFT LEFT WITH DEVSECOPS
SHIFT LEFT WITH DEVSECOPS
NETUserGroupBern
 
Securing .NET Core, ASP.NET Core applications
Securing .NET Core, ASP.NET Core applicationsSecuring .NET Core, ASP.NET Core applications
Securing .NET Core, ASP.NET Core applications
NETUserGroupBern
 
Application Security in ASP.NET Core
Application Security in ASP.NET CoreApplication Security in ASP.NET Core
Application Security in ASP.NET Core
NETUserGroupBern
 
Ruby und Rails für .NET Entwickler
Ruby und Rails für .NET EntwicklerRuby und Rails für .NET Entwickler
Ruby und Rails für .NET Entwickler
NETUserGroupBern
 
Einführung in RavenDB
Einführung in RavenDBEinführung in RavenDB
Einführung in RavenDB
NETUserGroupBern
 
What Doctors Can Teach Us on Continuous Learning
What Doctors Can Teach Us on Continuous LearningWhat Doctors Can Teach Us on Continuous Learning
What Doctors Can Teach Us on Continuous Learning
NETUserGroupBern
 
Entity Framework Core - Der Umstieg auf Core
Entity Framework Core - Der Umstieg auf CoreEntity Framework Core - Der Umstieg auf Core
Entity Framework Core - Der Umstieg auf Core
NETUserGroupBern
 
Weiches Zeugs für harte Jungs und Mädels
Weiches Zeugs für harte Jungs und MädelsWeiches Zeugs für harte Jungs und Mädels
Weiches Zeugs für harte Jungs und Mädels
NETUserGroupBern
 
Änderungen im Cardinality Estimator SQL Server 2014
Änderungen im Cardinality Estimator SQL Server 2014Änderungen im Cardinality Estimator SQL Server 2014
Änderungen im Cardinality Estimator SQL Server 2014
NETUserGroupBern
 
Rest Fundamentals
Rest FundamentalsRest Fundamentals
Rest Fundamentals
NETUserGroupBern
 
Refactoring: Mythen & Fakten
Refactoring: Mythen & FaktenRefactoring: Mythen & Fakten
Refactoring: Mythen & Fakten
NETUserGroupBern
 
AngularJs
AngularJsAngularJs
AngularJs
NETUserGroupBern
 
Pragmatische Anforderungen
Pragmatische AnforderungenPragmatische Anforderungen
Pragmatische Anforderungen
NETUserGroupBern
 
Einführung in MongoDB
Einführung in MongoDBEinführung in MongoDB
Einführung in MongoDB
NETUserGroupBern
 
What the hell is PowerShell?
What the hell is PowerShell?What the hell is PowerShell?
What the hell is PowerShell?
NETUserGroupBern
 
Know your warm up
Know your warm upKnow your warm up
Know your warm up
NETUserGroupBern
 
BDD mit Machine.Specifications (MSpec)
BDD mit Machine.Specifications (MSpec)BDD mit Machine.Specifications (MSpec)
BDD mit Machine.Specifications (MSpec)
NETUserGroupBern
 
Versionskontrolle mit Git
Versionskontrolle mit GitVersionskontrolle mit Git
Versionskontrolle mit Git
NETUserGroupBern
 

More from NETUserGroupBern (20)

Large Language Models, Data & APIs - Integrating Generative AI Power into you...
Large Language Models, Data & APIs - Integrating Generative AI Power into you...Large Language Models, Data & APIs - Integrating Generative AI Power into you...
Large Language Models, Data & APIs - Integrating Generative AI Power into you...
 
AAD und .NET
AAD und .NETAAD und .NET
AAD und .NET
 
SHIFT LEFT WITH DEVSECOPS
SHIFT LEFT WITH DEVSECOPSSHIFT LEFT WITH DEVSECOPS
SHIFT LEFT WITH DEVSECOPS
 
Securing .NET Core, ASP.NET Core applications
Securing .NET Core, ASP.NET Core applicationsSecuring .NET Core, ASP.NET Core applications
Securing .NET Core, ASP.NET Core applications
 
Application Security in ASP.NET Core
Application Security in ASP.NET CoreApplication Security in ASP.NET Core
Application Security in ASP.NET Core
 
Ruby und Rails für .NET Entwickler
Ruby und Rails für .NET EntwicklerRuby und Rails für .NET Entwickler
Ruby und Rails für .NET Entwickler
 
Einführung in RavenDB
Einführung in RavenDBEinführung in RavenDB
Einführung in RavenDB
 
What Doctors Can Teach Us on Continuous Learning
What Doctors Can Teach Us on Continuous LearningWhat Doctors Can Teach Us on Continuous Learning
What Doctors Can Teach Us on Continuous Learning
 
Entity Framework Core - Der Umstieg auf Core
Entity Framework Core - Der Umstieg auf CoreEntity Framework Core - Der Umstieg auf Core
Entity Framework Core - Der Umstieg auf Core
 
Weiches Zeugs für harte Jungs und Mädels
Weiches Zeugs für harte Jungs und MädelsWeiches Zeugs für harte Jungs und Mädels
Weiches Zeugs für harte Jungs und Mädels
 
Änderungen im Cardinality Estimator SQL Server 2014
Änderungen im Cardinality Estimator SQL Server 2014Änderungen im Cardinality Estimator SQL Server 2014
Änderungen im Cardinality Estimator SQL Server 2014
 
Rest Fundamentals
Rest FundamentalsRest Fundamentals
Rest Fundamentals
 
Refactoring: Mythen & Fakten
Refactoring: Mythen & FaktenRefactoring: Mythen & Fakten
Refactoring: Mythen & Fakten
 
AngularJs
AngularJsAngularJs
AngularJs
 
Pragmatische Anforderungen
Pragmatische AnforderungenPragmatische Anforderungen
Pragmatische Anforderungen
 
Einführung in MongoDB
Einführung in MongoDBEinführung in MongoDB
Einführung in MongoDB
 
What the hell is PowerShell?
What the hell is PowerShell?What the hell is PowerShell?
What the hell is PowerShell?
 
Know your warm up
Know your warm upKnow your warm up
Know your warm up
 
BDD mit Machine.Specifications (MSpec)
BDD mit Machine.Specifications (MSpec)BDD mit Machine.Specifications (MSpec)
BDD mit Machine.Specifications (MSpec)
 
Versionskontrolle mit Git
Versionskontrolle mit GitVersionskontrolle mit Git
Versionskontrolle mit Git
 

Recently uploaded

What is Continuous Testing in DevOps - A Definitive Guide.pdf
What is Continuous Testing in DevOps - A Definitive Guide.pdfWhat is Continuous Testing in DevOps - A Definitive Guide.pdf
What is Continuous Testing in DevOps - A Definitive Guide.pdf
kalichargn70th171
 
Alluxio Webinar | 10x Faster Trino Queries on Your Data Platform
Alluxio Webinar | 10x Faster Trino Queries on Your Data PlatformAlluxio Webinar | 10x Faster Trino Queries on Your Data Platform
Alluxio Webinar | 10x Faster Trino Queries on Your Data Platform
Alluxio, Inc.
 
Voxxed Days Trieste 2024 - Unleashing the Power of Vector Search and Semantic...
Voxxed Days Trieste 2024 - Unleashing the Power of Vector Search and Semantic...Voxxed Days Trieste 2024 - Unleashing the Power of Vector Search and Semantic...
Voxxed Days Trieste 2024 - Unleashing the Power of Vector Search and Semantic...
Luigi Fugaro
 
The Rising Future of CPaaS in the Middle East 2024
The Rising Future of CPaaS in the Middle East 2024The Rising Future of CPaaS in the Middle East 2024
The Rising Future of CPaaS in the Middle East 2024
Yara Milbes
 
Baha Majid WCA4Z IBM Z Customer Council Boston June 2024.pdf
Baha Majid WCA4Z IBM Z Customer Council Boston June 2024.pdfBaha Majid WCA4Z IBM Z Customer Council Boston June 2024.pdf
Baha Majid WCA4Z IBM Z Customer Council Boston June 2024.pdf
Baha Majid
 
Penify - Let AI do the Documentation, you write the Code.
Penify - Let AI do the Documentation, you write the Code.Penify - Let AI do the Documentation, you write the Code.
Penify - Let AI do the Documentation, you write the Code.
KrishnaveniMohan1
 
TMU毕业证书精仿办理
TMU毕业证书精仿办理TMU毕业证书精仿办理
TMU毕业证书精仿办理
aeeva
 
Modelling Up - DDDEurope 2024 - Amsterdam
Modelling Up - DDDEurope 2024 - AmsterdamModelling Up - DDDEurope 2024 - Amsterdam
Modelling Up - DDDEurope 2024 - Amsterdam
Alberto Brandolini
 
Everything You Need to Know About X-Sign: The eSign Functionality of XfilesPr...
Everything You Need to Know About X-Sign: The eSign Functionality of XfilesPr...Everything You Need to Know About X-Sign: The eSign Functionality of XfilesPr...
Everything You Need to Know About X-Sign: The eSign Functionality of XfilesPr...
XfilesPro
 
Beginner's Guide to Observability@Devoxx PL 2024
Beginner's  Guide to Observability@Devoxx PL 2024Beginner's  Guide to Observability@Devoxx PL 2024
Beginner's Guide to Observability@Devoxx PL 2024
michniczscribd
 
Building API data products on top of your real-time data infrastructure
Building API data products on top of your real-time data infrastructureBuilding API data products on top of your real-time data infrastructure
Building API data products on top of your real-time data infrastructure
confluent
 
Transforming Product Development using OnePlan To Boost Efficiency and Innova...
Transforming Product Development using OnePlan To Boost Efficiency and Innova...Transforming Product Development using OnePlan To Boost Efficiency and Innova...
Transforming Product Development using OnePlan To Boost Efficiency and Innova...
OnePlan Solutions
 
一比一原版(USF毕业证)旧金山大学毕业证如何办理
一比一原版(USF毕业证)旧金山大学毕业证如何办理一比一原版(USF毕业证)旧金山大学毕业证如何办理
一比一原版(USF毕业证)旧金山大学毕业证如何办理
dakas1
 
Unlock the Secrets to Effortless Video Creation with Invideo: Your Ultimate G...
Unlock the Secrets to Effortless Video Creation with Invideo: Your Ultimate G...Unlock the Secrets to Effortless Video Creation with Invideo: Your Ultimate G...
Unlock the Secrets to Effortless Video Creation with Invideo: Your Ultimate G...
The Third Creative Media
 
Why Apache Kafka Clusters Are Like Galaxies (And Other Cosmic Kafka Quandarie...
Why Apache Kafka Clusters Are Like Galaxies (And Other Cosmic Kafka Quandarie...Why Apache Kafka Clusters Are Like Galaxies (And Other Cosmic Kafka Quandarie...
Why Apache Kafka Clusters Are Like Galaxies (And Other Cosmic Kafka Quandarie...
Paul Brebner
 
Superpower Your Apache Kafka Applications Development with Complementary Open...
Superpower Your Apache Kafka Applications Development with Complementary Open...Superpower Your Apache Kafka Applications Development with Complementary Open...
Superpower Your Apache Kafka Applications Development with Complementary Open...
Paul Brebner
 
Going AOT: Everything you need to know about GraalVM for Java applications
Going AOT: Everything you need to know about GraalVM for Java applicationsGoing AOT: Everything you need to know about GraalVM for Java applications
Going AOT: Everything you need to know about GraalVM for Java applications
Alina Yurenko
 
Stork Product Overview: An AI-Powered Autonomous Delivery Fleet
Stork Product Overview: An AI-Powered Autonomous Delivery FleetStork Product Overview: An AI-Powered Autonomous Delivery Fleet
Stork Product Overview: An AI-Powered Autonomous Delivery Fleet
Vince Scalabrino
 
WWDC 2024 Keynote Review: For CocoaCoders Austin
WWDC 2024 Keynote Review: For CocoaCoders AustinWWDC 2024 Keynote Review: For CocoaCoders Austin
WWDC 2024 Keynote Review: For CocoaCoders Austin
Patrick Weigel
 

Recently uploaded (20)

What is Continuous Testing in DevOps - A Definitive Guide.pdf
What is Continuous Testing in DevOps - A Definitive Guide.pdfWhat is Continuous Testing in DevOps - A Definitive Guide.pdf
What is Continuous Testing in DevOps - A Definitive Guide.pdf
 
Alluxio Webinar | 10x Faster Trino Queries on Your Data Platform
Alluxio Webinar | 10x Faster Trino Queries on Your Data PlatformAlluxio Webinar | 10x Faster Trino Queries on Your Data Platform
Alluxio Webinar | 10x Faster Trino Queries on Your Data Platform
 
Voxxed Days Trieste 2024 - Unleashing the Power of Vector Search and Semantic...
Voxxed Days Trieste 2024 - Unleashing the Power of Vector Search and Semantic...Voxxed Days Trieste 2024 - Unleashing the Power of Vector Search and Semantic...
Voxxed Days Trieste 2024 - Unleashing the Power of Vector Search and Semantic...
 
The Rising Future of CPaaS in the Middle East 2024
The Rising Future of CPaaS in the Middle East 2024The Rising Future of CPaaS in the Middle East 2024
The Rising Future of CPaaS in the Middle East 2024
 
Baha Majid WCA4Z IBM Z Customer Council Boston June 2024.pdf
Baha Majid WCA4Z IBM Z Customer Council Boston June 2024.pdfBaha Majid WCA4Z IBM Z Customer Council Boston June 2024.pdf
Baha Majid WCA4Z IBM Z Customer Council Boston June 2024.pdf
 
Penify - Let AI do the Documentation, you write the Code.
Penify - Let AI do the Documentation, you write the Code.Penify - Let AI do the Documentation, you write the Code.
Penify - Let AI do the Documentation, you write the Code.
 
TMU毕业证书精仿办理
TMU毕业证书精仿办理TMU毕业证书精仿办理
TMU毕业证书精仿办理
 
Modelling Up - DDDEurope 2024 - Amsterdam
Modelling Up - DDDEurope 2024 - AmsterdamModelling Up - DDDEurope 2024 - Amsterdam
Modelling Up - DDDEurope 2024 - Amsterdam
 
Everything You Need to Know About X-Sign: The eSign Functionality of XfilesPr...
Everything You Need to Know About X-Sign: The eSign Functionality of XfilesPr...Everything You Need to Know About X-Sign: The eSign Functionality of XfilesPr...
Everything You Need to Know About X-Sign: The eSign Functionality of XfilesPr...
 
Beginner's Guide to Observability@Devoxx PL 2024
Beginner's  Guide to Observability@Devoxx PL 2024Beginner's  Guide to Observability@Devoxx PL 2024
Beginner's Guide to Observability@Devoxx PL 2024
 
Building API data products on top of your real-time data infrastructure
Building API data products on top of your real-time data infrastructureBuilding API data products on top of your real-time data infrastructure
Building API data products on top of your real-time data infrastructure
 
Transforming Product Development using OnePlan To Boost Efficiency and Innova...
Transforming Product Development using OnePlan To Boost Efficiency and Innova...Transforming Product Development using OnePlan To Boost Efficiency and Innova...
Transforming Product Development using OnePlan To Boost Efficiency and Innova...
 
bgiolcb
bgiolcbbgiolcb
bgiolcb
 
一比一原版(USF毕业证)旧金山大学毕业证如何办理
一比一原版(USF毕业证)旧金山大学毕业证如何办理一比一原版(USF毕业证)旧金山大学毕业证如何办理
一比一原版(USF毕业证)旧金山大学毕业证如何办理
 
Unlock the Secrets to Effortless Video Creation with Invideo: Your Ultimate G...
Unlock the Secrets to Effortless Video Creation with Invideo: Your Ultimate G...Unlock the Secrets to Effortless Video Creation with Invideo: Your Ultimate G...
Unlock the Secrets to Effortless Video Creation with Invideo: Your Ultimate G...
 
Why Apache Kafka Clusters Are Like Galaxies (And Other Cosmic Kafka Quandarie...
Why Apache Kafka Clusters Are Like Galaxies (And Other Cosmic Kafka Quandarie...Why Apache Kafka Clusters Are Like Galaxies (And Other Cosmic Kafka Quandarie...
Why Apache Kafka Clusters Are Like Galaxies (And Other Cosmic Kafka Quandarie...
 
Superpower Your Apache Kafka Applications Development with Complementary Open...
Superpower Your Apache Kafka Applications Development with Complementary Open...Superpower Your Apache Kafka Applications Development with Complementary Open...
Superpower Your Apache Kafka Applications Development with Complementary Open...
 
Going AOT: Everything you need to know about GraalVM for Java applications
Going AOT: Everything you need to know about GraalVM for Java applicationsGoing AOT: Everything you need to know about GraalVM for Java applications
Going AOT: Everything you need to know about GraalVM for Java applications
 
Stork Product Overview: An AI-Powered Autonomous Delivery Fleet
Stork Product Overview: An AI-Powered Autonomous Delivery FleetStork Product Overview: An AI-Powered Autonomous Delivery Fleet
Stork Product Overview: An AI-Powered Autonomous Delivery Fleet
 
WWDC 2024 Keynote Review: For CocoaCoders Austin
WWDC 2024 Keynote Review: For CocoaCoders AustinWWDC 2024 Keynote Review: For CocoaCoders Austin
WWDC 2024 Keynote Review: For CocoaCoders Austin
 

SOLID Code

  • 1. Design for testability as a way to good coding Simone Chiaretta Architect, 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 ► Italian ALT.NET UG Founder ► OpenSource developer ► Climber ► All Around Nice Guy Disclaimer:"The views expressed are purely those of the speaker and may not in any circumstances be regarded 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. Solid: Single Responsibility Principle (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.” -Robert C. Martin
  • 10. sOlid: Open Closed Principle (OCP) You should be able to extend a classes behavior, without modifying it.
  • 11. sOlid: Open Closed Principle (OCP) “Modules that conform to the open-closed principle have two primary attributes. 1. 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. 2. 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
  • 12. sOlid: Open Closed Principle (OCP)
  • 13. soLid: Liskov Substitution Principle (LSP) Derived classes must be substitutable for their base classes.
  • 14. soLid: Liskov Substitution Principle (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
  • 15. soLid: Liskov Substitution Principle (LSP)
  • 16. soLid: Liskov Substitution Principle (LSP)
  • 17. solId: Interface Segregation Principle (ISP) Clients should not be forced to depend upon interfaces they don’t use
  • 18. solId: Interface Segregation Principle (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
  • 19. solId: Interface Segregation Principle (ISP)
  • 20. soliD: Dependency Inversion Principle (DIP) Depend on abstractions, not on concretions.
  • 21. soliD: Dependency Inversion Principle (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
  • 22. soliD: Dependency Inversion Principle (DIP)
  • 24. How to test for “good design”? ► You can’t ► Actually you can  Clear?
  • 26. Testability Actors ► System Under Test ► Depended On Component ► Mock/Fake/Stub
  • 27. Testability Concepts ► Test just one feature ► Indipendency from environment ► Indipendency from dependencies ► Fast
  • 29. Design for Testability = Good Design ► Good design is difficult to measure ► Easily testable = Good Design
  • 30. What is Dependency Injection
  • 32. 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
  • 34. Still problems ► We have lower coupling but still Climber has to be changed to change tools
  • 35. Slightly Better Code Demo: Hard-Coded Dependencies with Service Locator 4
  • 36. Still problems ► Still Climber depends on the Locator ► Just moving the problem inside another module
  • 38. 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
  • 39. Dependency Injection Are we done? NOT YET!
  • 40. Introducing Dependency Injection Demo: Dependency Injection by Hand (more complex) 6
  • 41. Needs Improvements ► Host must know how to assemble dependencies ► We loose encapsulation
  • 42. What is Inversion of Control
  • 44. What we achieved ► Still have DIP ► Got encapsulation back ► Dependencies are handled by external component
  • 45. How to configure ► XML ► Attributes ► Fluent API ► all of them
  • 48. The Kernel ► Factory Method on Steroids ► Hold the configuration ► Returns objects IKernel kernel = new StandardKernel( new ClimbingModule()); var climber = kernel.Get<Climber>();
  • 49. Modules ► Modules hold specific configurations ► Configuration through Fluent API Bind<Climber>().ToSelf(); Bind<IClimbingTools>().To<QuickDraws>();
  • 50. Inversion of Control Demo: Inversion of Control (complex) 8
  • 51. Different kinds of Injection ► Constructor Injection ► Property Injection ► Method Injection ► Through Factory Method
  • 52. Attributes ► Are used to help discriminate injection patterns [Inject] public IClimbingTools tools {get; set;} [Inject] public void GetReady(IClimbingTools tools)
  • 54. Behaviours ► Singleton (Default) ► Transient ► Per Thread ► Per Request ► BYO Bind<Climber>().ToSelf().InTransientScope(); Bind<Climber>().ToSelf().InSingletonScope();
  • 56. 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");
  • 58. 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);
  • 61. 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>
  • 64. Funq ► By Daniel Cazzulino (of Moq fame) ► The fastest IoC available ► Doesn’t use reflection ► Always write factory method container.Register<IClimbingTools>( c => new QuickDraws()); container.Register( c => new Climber( c.Resolve<IClimbingTools>()));
  • 67. 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
  • 68. IoC in other hosts Demo: ASP.NET MVC 15
  • 70. 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
  • 71. 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
  • 72. References ► Uncle Bob’s Principle Of Object Oriented Development: http://butunclebob.com/ArticleS.UncleBob.PrinciplesOfO od ► 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/ - v2 http://github.com/enkari/ninject/ - v2.2 beta ► p&p Unity: http://unity.codeplex.com/ - v2 (part of EntLib5) ► Funq: http://funq.codeplex.com/
  • 73. Contacts – Simone Chiaretta ► MSN: simone_ch@hotmail.com ► Blog: – English: http://codeclimber.net.nz/ – Italian: http://blogs.ugidotnet.org/piyo/ ► Twitter: @simonech 72
  • 74. Questions? Disclaimer:"The views expressed are purely those of the speaker and may not in any circumstances be regarded as stating an official position of the Council"
  • 75. 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 views expressed are purely those of the speaker and may not in any circumstances be regarded 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” - Wikipedia Coupling: “The degree to which each program module relies on each one of the other modules” – Wikipedia Encapsulation: “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. Example might be an email sending application that sends email taking the text from an external file: If you read the text and send the email from the same class you are breaking the SRP principle. It would be better to separate the reading part from the sending one.
  4. It’s all about behaviours and pre/post conditions: A derived type can only weaken pre-conditions A derived type can only streghten post-conditions
  5. Imagine you want to put templates in a database: you cannot just write a “file” reader that uses a database as it will need a connection string, and the user should do different things based on the type of the reader, thus making the substitution not transparent.
  6. Here it would have been better to completely separate the two things, and have a database reader and a file reader.
  7. After adding the Database reader, we now have the email sending service that can both read file and databases, and obviously sending emails. So it’s better to split these responsibilities in different interfaces.
  8. Finally, instead of having the single object create their own dependencies, it is the top-most client that configures the system for what it needs.