All 3 Clean Code presentations provide great value by themselves, but taken together are designed to offer a holistic approach to successful software creation. This first session creates the foundation for the 2nd and 3rd Clean Code presentation on Dependency Injection, as it explains expected base knowledge. Why writing Clean Code makes us more efficient Over the lifetime of a product, maintaining the product is actually one - if not the most - expensive area(s) of the overall product costs.
We will dive into the basics of Inversion of Control (IOC) and Dependency Injection (DI) to review different ways of achieving decoupling, using and exploring both: Best Practices, Design and Anti Patterns. This presentation requires knowledge and understanding of basics like DRY, SoC, SRP, SOLID etc. which are building the base for decoupled architecture. However, we will start at the basics of DI and will work towards intermediate and advanced scenarios depending on the participating group.
This presentation is based on C# and Visual Studio 2013. However, the demonstrated patterns and practice can be applied to every other programming language too.
Note: Moving forwards this presentation will be updated with the latest version of the slides for the last event I did the presentation instead of creating new separate slide decks here on SlideShare.
Presentation dates and locations:
2015-10-03 Silicon Valley Code Camp, San Jose, CA
2015-06-27 SoCal Code Camp - San Diego, CA
2015-06-25 Bay.NET South Bay, Mountain View, CA
2014-11-14 SoCal Code Camp - Los Angeles, CA
2014-10-11 Silicon Valley Code Camp, Los Altos Hills, CA
2. Theo Jungeblut
⢠Director Customer Success at
AppDynamics in San Francisco
⢠Coder & software craftsman by night,
first time dad and house builder
⢠Architects decoupled solutions
& crafts maintainable code to last
⢠Worked in healthcare and factory
automation, building mission critical
applications, framework & platforms
⢠Degree in Software Engineering
and Network Communications
⢠Enjoys cycling, running and eating
theo@designitright.net
www.designitright.net
4. Your feedback is important!
http://speakerrate.com/speakers/18667-theo-jungeblut
5. Where to get the Slides
http://www.slideshare.net/theojungeblut
6. Overview
⢠What is the issue?
⢠What is Dependency Injection?
⢠What are Dependencies?
⢠What is the IoC-Container doing for you?
⢠What, how, why?
⢠Q & A
14. Without Dependency Injection
public class ExampleClass
{
private Logger logger;
public ExampleClass()
{
this.logger = new Logger();
this.logger.Log(âConstructor callâ);
}
}
15. public class ExampleClass
{
private Logger logger;
public ExampleClass()
{
this.logger = new Logger();
this.logger.Log(âConstructor callâ);
}
}
Without Dependency Injection
16. Inversion of Control â
Constructor Injection
http://www.martinfowler.com/articles/injection.html
public class ExampleClass
{
private ILogger logger;
public ExampleClass(ILogger logger)
{
this.logger = logger;
if (logger == null)
{
throw new ArgumentNullException(âloggerâ);
}
this.logger.Log(âConstructor callâ);
}
}
18. Benefits of Dependency Injection
Benefit Description
Late binding Services can be swapped with
other services.
Extensibility Code can be extended and reused
in ways not explicitly planned for.
Parallel
development
Code can be developed in parallel.
Maintainability Classes with clearly defined
responsibilities are easier to
maintain.
TESTABILITY Classes can be unit tested.
* from Mark Seemannâs âDependency Injection in .NETâ, page 16
20. Stable Dependency
âA DEPENDENCY that can be referenced without
any detrimental effects.
The opposite of a VOLATILE DEPENDENCY. â
* From Glossary: Mark Seemannâs âDependency Injection in .NETâ
21. Volatile Dependency
âA DEPENDENCY that involves side effects that may be
undesirable at times.
This may include modules that donât yet exist, or that
have adverse requirements on its runtime
environment.
These are the DEPENDENCIES that are addressed by
DI.â
* From Glossary: Mark Seemannâs âDependency Injection in .NETâ
23. public class ExampleClass
{
private Logger logger;
public ExampleClass()
{
this.logger = new Logger();
this.logger.Log(âConstructor callâ);
}
}
Without Dependency Injection
26. Separation of Concern (SoC)
probably by Edsger W. Dijkstra in 1974
You codeExecute
⢠Focus on purpose of your code
⢠Know only the contracts of the
dependencies
⢠No need to know implementations
⢠No need to handle lifetime of the
dependencies
27. The 3 Dimensions of DI
1.Object Composition
2.Object Lifetime
3.Interception
28. Register - Composition Root
⢠XML based Configuration
⢠Code based Configuration
⢠Convention based (Discovery)
29. Resolve
Resolve a single object request for
example by Constructor Injection by
resolving the needed object graph for
this object.
33. // UNITY Example
internal static class Program
{
private static UnityContainer unityContainer;
private static SingleContactManagerForm singleContactManagerForm;
private static void InitializeMainForm()
{
singleContactManagerForm =
unityContainer.Resolve<SingleContactManagerForm>();
}
}
Inversion of Control â
Service Locator
http://www.martinfowler.com/articles/injection.html
34. // UNITY Example
internal static class Program
{
private static UnityContainer unityContainer;
private static SingleContactManagerForm singleContactManagerForm;
private static void InitializeMainForm()
{
singleContactManagerForm =
unityContainer.Resolve<SingleContactManagerForm>();
}
}
Inversion of Control â
Service Locator
http://www.martinfowler.com/articles/injection.html
35. Inversion of Control â
Setter (Property) Injection
// UNITY Example
public class ContactManager : IContactManager
{
[Dependency]
public IContactPersistence ContactPersistence
{
get { return this.contactPersistence; }
set { this.contactPersistence = value; }
}
}
http://www.martinfowler.com/articles/injection.html
36. Property Injection
+ Easy to understand
- Hard to implement robust
* Take if an good default exists
- Limited in application otherwise
37. Method Injection
public class ContactManager : IContactManager
{
âŚ.
public bool Save (IContactPersistencecontactDatabaseService,
IContact contact)
{
if (logger == null)
{
throw new ArgumentNullException(âloggerâ);
}
âŚ. // Additional business logic executed before calling the save
return contactDatabaseService.Save(contact);
}
}
http://www.martinfowler.com/articles/injection.html
39. Ambient Context
public class ContactManager : IContactManager
{
âŚ.
public bool Save (âŚ.)
{
âŚ.
IUser currentUser = ApplicationContext.CurrentUser;
âŚ.
}
}
* The Ambient Context object needs to have a default value if not assigned yet.
40. Ambient Context
⢠Avoids polluting an API with Cross Cutting
Concerns
⢠Only for Cross Cutting Concerns
⢠Limited in application otherwise
42. Interception
Public class LoggingInterceptor : IContactManager
{
public bool Save(IContact contact)
{
bool success;
this. logger.Log(âStarting savingâ);
success =
this.contactManager.Save(contact);
this. logger.Log(âStarting savingâ);
return success;
}
}
Public class ContactManager :
IContactManager
{
public bool Save(IContact contact)
{
âŚ.
return Result
}
}
* Note: strong simplification of what logically happens through interception.
43. Dependency Injection Container & more
⢠Typically support all types of Inversion of Control mechanisms
⢠Constructor Injection
⢠Property (Setter) Injection
⢠Method (Interface) Injection
⢠Service Locator
â˘.NET based DI-Container
⢠Unity
⢠Castle Windsor
⢠StructureMap
⢠Spring.NET
⢠Autofac
⢠Puzzle.Nfactory
⢠Ninject
⢠PicoContainer.NET
⢠and more
Related Technology:
⢠Managed Extensibility Framework (MEF)
45. Summary Clean Code - DI
Maintainability is achieved through:
⢠Simplification, Specialization Decoupling
(KISS, SoC, IoC, DI)
⢠Dependency Injection
Constructor Injection as default,
Property and Method Injection as needed,
Ambient Context for Dependencies with a default,
Service Locator never
⢠Registration
Configuration by Convention if possible, exception in Code as needed
Configuration by XML for explicit extensibility and post compile setup
⢠Quality through Testability (all of them!)
Graphic by Nathan Sawaya
courtesy of brickartist.com
46. Downloads,
Feedback & Comments:
Q & A
Graphic by Nathan Sawaya courtesy of brickartist.com
theo@designitright.net
www.designitright.net
http://speakerrate.com/ speakers
/18667-theo-jungeblut
47. Time to say Thank You!
The Organizers
Evergreen Valley College (team)
The volunteers (how about you?)
TheSponsors
Picturesfromhttp://blog.siliconvalley-codecamp.com
50. ⌠thanks for you attention!
And visit and support the
www.siliconvalley-codecamp.com
Please fill out the
feedback, andâŚ
www.speakerrate.com/theoj