Clean Code Part II - Dependency Injection at SoCal Code Camp
Upcoming SlideShare
Loading in...5
×
 

Clean Code Part II - Dependency Injection at SoCal Code Camp

on

  • 1,016 views

Clean Code II – Cut your Dependencies with Dependency Injection ...

Clean Code II – Cut your Dependencies with Dependency Injection
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 and Anti Patterns.
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 presentation requires you to know and understand basics like DRY, SoC, SRP, SOLID etc. which will be explained in the 1st Clean Code session. However, it will start at the basics of DI and will work towards intermediate and advanced scenarios depending on the participating group.

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. Writing clean code can significantly lower these costs. However, writing clean code also makes you more efficient during the initial development time and results in more stable code. You will be presented design patterns and best practices which will make you write better and more easily maintainable code, seeing code in a holistic way. You will learn how to apply them by using an existing implementation as the starting point of the presentation. Finally, patterns & practices benefits are explained.
This presentation is based on C# and Visual Studio 2010. However, the demonstrated patterns and practice can be applied to every other programming language too.

Statistics

Views

Total Views
1,016
Views on SlideShare
977
Embed Views
39

Actions

Likes
1
Downloads
40
Comments
0

5 Embeds 39

http://www.scoop.it 22
http://speakerrate.com 11
http://www.slashdocs.com 3
http://shakertechnologies.tumblr.com 2
http://techno-sphere.blogspot.com 1

Accessibility

Categories

Upload Details

Uploaded via as Microsoft PowerPoint

Usage Rights

CC Attribution-NonCommercial LicenseCC Attribution-NonCommercial License

Report content

Flagged as inappropriate Flag as inappropriate
Flag as inappropriate

Select your reason for flagging this presentation as inappropriate.

Cancel
  • Full Name Full Name Comment goes here.
    Are you sure you want to
    Your message goes here
    Processing…
Post Comment
Edit your comment

Clean Code Part II - Dependency Injection at SoCal Code Camp Clean Code Part II - Dependency Injection at SoCal Code Camp Presentation Transcript

  • SolCal CodeCampClean Code II Dependency Injection San Diego, June 24rd 2012
  • Theo Jungeblut• Senior Software Developer at AppDynamics in San Francisco• architects decoupled solutions tailored to business needs and crafts maintainable code to last• worked in healthcare and factory automation, building mission critical applications, framework & platforms for 8+ years• degree in Software Engineering and Network Communications theo@designitright.net• enjoys cycling, running and eating www.designitright.net www.speakerrate.com/theoj
  • Overview• Why Clean Code?• What is Dependency Injection?• What are Dependencies?• What is the IoC-Container doing for you?• What, how, why?• Q&A
  • Does writing Clean Codemake us more efficient?
  • What is Clean Code?
  • Clean Code is maintainable Source code must be: • readable & well structured • extensible • testable
  • Code Maintainability * Principles Patterns Containers Why? How? What? Extensibility Clean Code Tool reuse* from: Mark Seemann’s “Dependency Injection in .NET” presentation Bay.NET 05/2011
  • What isDependency Injection?
  • Without Dependency Injectionpublic class ExampleClass{ private logger logger; public ExampleClass() { this.logger = new Logger(); this.logger.Log(“Constructor call”); }}
  • Without Dependency Injectionpublic class ExampleClass{ private logger logger; public ExampleClass() { this.logger = new Logger(); this.logger.Log(“Constructor call”); }}
  • Inversion of Control –Constructor Injection http://www.martinfowler.com/articles/injection.html public class ExampleClass { private logger logger; public ExampleClass(ILogger logger) { this.logger = logger; if (logger == null) { throw new ArgumentNullException(“logger”); } this.logger.Log(“Constructor call”); } }
  • 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 Code can be developed in parallel. development 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
  • The Adapter Pattern from Gang of Four, “Design Patterns”
  • Inversion of Control –Setter (Property) Injection http://www.martinfowler.com/articles/injection.html // UNITY Example public class ContactManager : IContactManager { [Dependency] public IContactPersistence ContactPersistence { get { return this.contactPersistence; } set { this.contactPersistence = value; } } }
  • Property Injection+ Easy to understand- Hard to implement robust* Take if an good default exists- Limited in application otherwise
  • Method Injectionhttp://www.martinfowler.com/articles/injection.htmlpublic 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); }}
  • 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.
  • Ambient Context• Avoids polluting an API with Cross Cutting Concerns• Only for Cross Cutting Concerns• Limited in application otherwise
  • What areDependencies ?
  • 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”
  • 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”
  • Lifetime a Jobfor the Container
  • “Register, Resolve, Release” “Three Calls Pattern by Krzysztof Koźmic: http://kozmic.pl/Build 1. Register Execu Clean You code Release up 2. Resolve te up
  • What the IoC-Container will do for youBuild 1. Register Clean Release up 2. Resolve up
  • Separation of Consern (SoC) probably by Edsger W. Dijkstra in 1974 • Focus on purpose of your code • Know only the contracts of theExecu You code dependencies te • No need to know implementations • No need to handle lifetime of the dependencies
  • The 3 Dimensions of DI1.Object Composition2.Object Lifetime3.Interception
  • Register - Composition Root• XML based Configuration• Code based Configuration• Convention based (Discovery)
  • ResolveResolve a single object request forexample by Consturctor Injectionby resolving the needed objectgraph for this object.
  • ReleaseRelease objects from Containerwhen not needed anymore.
  • InterceptionPublic class LoggingInterceptor : IContactManager{ public bool Save(IContact contact) { bool success; Public class ContactManager : IContactManager this. logger.Log(“Starting saving’); { public bool Save(IContact contact) success = { this.contactManager.Save(contact); …. this. logger.Log(“Starting saving’); return Result } return success; } }} * Note: strong simplification of what logically happens through interception.
  • AntiPatterns
  • Control Freakhttp://www.freakingnews.com/The-Puppet-Master-will-play-Pics-102728.asp
  • Inversion of Control –Service Locator http://www.martinfowler.com/articles/injection.html// UNITY Exampleinternal 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// UNITY Exampleinternal static class Program{ private static UnityContainer unityContainer; private static SingleContactManagerForm singleContactManagerForm; private static void InitializeMainForm() { singleContactManagerForm = unityContainer.Resolve<SingleContactManagerForm>(); }}
  • 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 Related Technology: • Spring.NET • Managed Extensibility Framework (MEF) • Autofac • Windows Communication Foundation (WCF) • Puzzle.Nfactory • Ninject • PicoContainer.NET • and more
  • The “Must Read”-Book(s) by Mark SeemannDependencyInjection is a set ofsoftware designprinciples andpatterns thatenable us todevelop looselycoupled code. http://www.manning.com/seemann/
  • Summary Clean Code - DIMaintainability 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 Graphic by Nathan Sawaya courtesy of brickartist.com• 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!)
  • Q&A Downloads, Feedback & Comments: theo@designitright.net www.designitright.net www.speakerrate.com/theojGraphic by Nathan Sawaya courtesy of brickartist.com
  • References…http://www.idesign.net/idesign/DesktopDefault.aspx?tabindex=5&tabid=11http://www.manning.com/seemann/http://en.wikipedia.org/wiki/Keep_it_simple_stupidhttp://picocontainer.org/patterns.htmlhttp://en.wikipedia.org/wiki/Dependency_inversion_principlehttp://en.wikipedia.org/wiki/Dont_repeat_yourselfhttp://en.wikipedia.org/wiki/Component-oriented_programminghttp://en.wikipedia.org/wiki/Service-oriented_architecturehttp://www.martinfowler.com/articles/injection.htmlhttp://www.codeproject.com/KB/aspnet/IOCDI.aspxhttp://msdn.microsoft.com/en-us/magazine/cc163739.aspxhttp://msdn.microsoft.com/en-us/library/ff650320.aspxhttp://msdn.microsoft.com/en-us/library/aa973811.aspxhttp://msdn.microsoft.com/en-us/library/ff647976.aspxhttp://msdn.microsoft.com/en-us/library/cc707845.aspxhttp://msdn.microsoft.com/en-us/library/bb833022.aspxhttp://unity.codeplex.com/ Lego (trademarked in capitals as LEGO)
  • Please fill out thefeedback, and… www.speakerrate.com/theoj… thanks for you attention! And visit and support the www.sandiegodotnet.com