Dependency Injection Joshua Lewis @joshilewis

Slides:



Advertisements
Similar presentations
Component Patterns – Architecture and Applications with EJB copyright © 2001, MATHEMA AG Component Patterns Architecture and Applications with EJB JavaForum.
Advertisements

What is an object? Your dog, your desk, your television set, your bicycle. Real-world objects share two characteristics: They all have state and behavior;
Week 8 Implementation Design Alex Baker. Implementation Design System Design – Describes what the system should do Implementation Design – Describes what.
Object Oriented Software Development
Chapter 7 Designing Classes. Class Design When we are developing a piece of software, we want to design the software We don’t want to just sit down and.
Sadegh Aliakbary Sharif University of Technology Fall 2011.
HFOOAD Chapter 2 Requirements. We create software for a reason. We create software fro people. We need to know what the people want in the software we.
DEPENDENCY INJECTION & INVERSION OF CONTROL. WHAT’S GOING TO BE COVERED Quick intro to C# for Java developers Dependency Injection Inversion of Control.
1 CS161 Introduction to Computer Science Topic #9.
Salman Marvasti Sharif University of Technology Winter 2015.
Lecture 13 Law of Demeter. Cohesion Cohesion: the “glue” that holds a module together. Don’t do things that do not support a common goal Cohesion: the.
Design Patterns Software Engineering CS 561. Last Time Introduced design patterns Abstraction-Occurrence General Hierarchy Player-Role.
ANU COMP2110 Software Design in 2003 Lecture 10Slide 1 COMP2110 Software Design in 2004 Lecture 12 Documenting Detailed Design How to write down detailed.
OOD teaches a complicated method, best for large systems. Here we teach the ten cent version. OO Design for the Rest of Us 1.
Component Patterns – Architecture and Applications with EJB copyright © 2001, MATHEMA AG Component Patterns Architecture and Applications with EJB Markus.
Dependency Injection with Guice Technion – Institute of Technology Author: Gal Lalouche - Technion 2016 ©
Module 9: Operator overloading #1 2000/01Scientific Computing in OOCourse code 3C59 Module 9: Operator Overloading In this module we will cover Overloading.
Leveraging ColdSpring to build a robust Flex applications Chris Scott, Cynergy Systems.
Anger will never disappear so long as thoughts of resentment are cherished in the mind. Anger will disappear just as soon as thoughts of resentment.
Programs – Preprocessing, Compilation and Linking
ESSENTIAL WORDS.
An Introduction to Cost of Poor Quality
Lecture 14 Throwing Custom Exceptions
Feeling Welcome – your experience
Unit 3 General exam advice
The Importance of Goals
Inheritance and Polymorphism
C++ coding standard suggestion… Separate reasoning from action, in every block. Hi, this talk is to suggest a rule (or guideline) to simplify C++ code.
What does this mean? Why I chose this topic
Session 2 Automaticity Mindfulness X.
Damned if you do and Damned if you don’t
CS 641 – Requirements Engineering
Achieve Collaborate Enjoy
Entry Task #1 – Date Self-concept is a collection of facts and ideas about yourself. Describe yourself in your journal in a least three sentences. What.
English for Civil Engineers
Intent (Thanks to Jim Fawcett for the slides)
CMPE212 – Stuff… Assn 3 due and Quiz 2 in the lab next week.
What to Do About Gossip and Rumors
Lecturer: Mukhtar Mohamed Ali “Hakaale”
Lesson 2: Building Blocks of Programming
Software Engineering Lecture 7 - Design Patterns
Top Tips Summary: Software Engineering in practice
Extemp – Your first Tournament
Lesson 1: Fundamentals of Programming
Advanced Programming Behnam Hatami Fall 2017.
The Big Thirst as a Book-Length Argument
Ms Munawar Khatoon IV Year I Sem Computer Science Engineering
Mindsets Get out your own piece of paper and a writing device!
Einführung in die Programmierung Introduction to Programming Prof. Dr
Get In Shape With EMS Training. INTRODUCTION Those that are thinking about making a change in their life might have thought about going through with EMS.
Chartboost Help Site Competitive Analysis and Proposal
How To Analyze the Development Of Theme.
I can work with different people in my class
Towards a better method of searching source code
CISC124 Assignment 3 sample solution will be posted tonight after 7pm.
Spring into action! The end isn’t the end any more.
Back to School Maths Night 04/02/19.
Learning outcomes Knowledge Skills
Interfaces.
Impossible problems.
Naming & Code Reviews.
Feeling Welcome – your experience
European conference.
CSE 153 Design of Operating Systems Winter 2019
Winter 2019 CMPE212 5/25/2019 CMPE212 – Reminders
Methods 16-May-19.
CS 5010 Program Design Paradigms "Bootcamp" Lesson 12.1
HFOOAD Chapter 5 Interlude
the impact of god’s word
Introduction to Computer Science and Object-Oriented Programming
Presentation transcript:

Joshua Lewis @joshilewis Dependency Injection Joshua Lewis @joshilewis - Thank Chris, thank group for opportunity Thanks for coming Food for thought Interactive JCSE Twitter Still learning Aim to understand why we use DI No tools or advanced usage Some Ruby-specific Approach – real-world egs, lessons applied to code I’m new to Ruby, expanded thinking

Expectations Q: Who not heard of DI? Q: Who uses DI? Q: Who doesn’t like DI? Q: Who can’t write code without DI? Q: Expectations

Short Video Show quick video Won’t discuss straight away but keep in mind

Start simple and unpack DI a bit Q: What is a dependency? A: Something you need to do your job Words like ‘need’ or ‘require’ signify dependency Can make a formal statement

We require certain resources to function and fulfil our responsibilities We call these dependencies

Q: Who needs food? Q: Who grows their own food? Q: Why not? You just said you need food, why don’t you grow your own? It’s expensive: effort, time, skills, money Not part of my purpose Not a shallow dependency Dependency chains Eg human – food ~ soil, sunlight, water, expertise

We can consume a resource without having to manage it I’ve been liberated Statement: we consume resource without worrying about how it arrives Important to distinguish between consuming and everything else What is everything else

Another example If surgeon had to sterilise equipment, how much time for surgery? Colin McRae looking at map while driving Go further – shouldn’t manage

We shouldn’t have to worry about our resources except for consuming them Q: Why is this? A: Liberates, can spend time on other things Don’t incur cost, effort, dependency chain Not part of purpose/reason for being

Now a tension: need something but can’t manage Fortunately can go to shops in real world How does it work out in code?

Class Exercise Now going to do a class exercise Have a look at handout Q: Who has seen code like this? Q: Who has written code like this?

This is Sequence Diag showing interaction of components Can see creation of Repo in Controller and Connection in Repo

Classes knowing little about collaborators Isolate from change SRP ISP Stronger than not managing:

A class should know nothing more about its dependencies than how to consume them This is ideal state Not part of purpose Too expensive Exposed to more change Cleanest code, nothing out-of-concern

Classes should be like baby birds: Tell what they need and when Someone else’s job to get it for them Let’s look at some code

public ActionResult List() { ProductRepository repository = new ProductRepository(); IList<Product> productList = repository.GetAllProducts(); return View(productList); } public IList<Product> GetAllProducts() { SqlConnection connection = new SqlConnection("connString"); IList<Product> productList = ExecuteAllProductsCommand(connection); return productList; } This is code as-is Problems? Lets try to improve it step-by-step

Now a call to static method public class ProductRepository { public IList<Product> GetAllProducts() SqlConnection connection = ConnectionProvider.GetConnection(); IList<Product> productList = ExecuteAllProductsCommand(connection); return productList; } Now a call to static method Now replaced call to ‘new’ with call to Static Can delegate management, like connection opening, pooling etc to ConnectionProvider Q: Problems? Can’t test Class still getting own dependency

public class ProductRepository { private readonly SqlConnection connection; public ProductRepository(SqlConnection connection) this.connection = connection; } public IList<Product> GetAllProducts() IList<Product> productList = ExecuteAllProductsCommand(); return productList; Class now declaring what it needs Make dependency explicit Only thing we know about SqlConnection is how to use it Less code, much cleaner But how is ProductController affected?

public class ProductController : Controller { public ActionResult List() SqlConnection connection = new SqlConnection( "connecting string"); ProductRepository repository = new ProductRepository(connection); IList<Product> productList = repository.GetAllProducts(); return View(productList); } Now ProductController has to worry about its dependency’s dependency This is bad

public class ProductController : Controller { private readonly ProductRepository repository; public ProductController(ProductRepository repository) this.repository = repository; } public ActionResult List() IList<Product> productList = repository.GetAllProducts(); return View(productList); Now made dependencies explicit again ProductController declares its dependencies Only thing we know about Repository is how to use it One more thing we can do: DIP

public interface IProductRepository { IList<Product> GetAllProducts(); } public class ProductRepository : IProductRepository To satisfy DIP we’ll make Controller and Repository depend on an abstraction, IProductRepository Personally not convinced this step is necessary, because Controller is insulated from implementation of Repository already

public class ProductController : Controller { private readonly IProductRepository repository; public ProductController(IProductRepository repository) this.repository = repository; } public ActionResult List() IList<Product> productList = repository.GetAllProducts(); return View(productList);

So now we have baby bird classes, how do we give them their worms? Classes should be concerned about how to use resources, nothing more So how do they get their dependencies? Dependency Injection is one way of achieving this There may be other ways, especially in other languages, but DI best in static-typed languages like C# and Java

SqlConnection connection = new SqlConnection("connString"); For<SqlConnection>() .Use(connection) ; For<IProductRepository>() .Use<ProductRepository>() For<ProductController>() .Use<ProductController>() This code shows declarative code showing container what classes to use when asked for types Using StructureMap Note that we don’t need to tell container how to create types, not what to use in specific cases, can work it out itself

- Sequence diagram showing how container resolves types with recursive calls

Disadvantages Q: What are the disadvantages? 1 big disadvantage: if don’t understand, works like magic, nothing ever newed up Container config bloated and complicated

Intermediate and advanced usage Some intermediate and advanced usage scenarios Eg opening and closing connection, Unit of Work pattern Can wrap resources so that opening and closing done automatically Lazy instantiation – depending on a delegate Interception

Conclusion Classes should be like baby birds Implies someone’s problem to manage and provide dependencies DI one way of doing it Particularly good way of doing it Cost i.t.o runtime magic, but small for benefits

Thank You!