Dependency Injection Technion – Institute of Technology 236700 1 Author: Gal Lalouche - Technion 2015 ©

Slides:



Advertisements
Similar presentations
OOP Abstraction Classes Class Members: Properties & Methods Instance (object) Encapsulation Interfaces Inheritance Composition Polymorphism Using Inheritance.
Advertisements

CLASS INHERITANCE Class inheritance is about inheriting/deriving properties from another class. When inheriting a class you are inheriting the attributes.
CS 350 – Software Design The Bridge Pattern – Chapter 10 Most powerful pattern so far. Gang of Four Definition: Decouple an abstraction from its implementation.
Creational Patterns (2) CS350/SE310 Fall, Lower the Cost of Maintenance Economic Goal Coupling-Cohesion, Open-Close, Information-Hiding, Dependency.
SE-1020 Dr. Mark L. Hornick 1 Inheritance and Polymorphism: Abstract Classes The “not quite” classes.
The Bridge Pattern.. Intent Decouple an abstraction from its implementation so that the two can vary independently Also known as: Handle/Body.
ITEC200 – Week03 Inheritance and Class Hierarchies.
CS 106 Introduction to Computer Science I 04 / 16 / 2010 Instructor: Michael Eckmann.
8.1 Classes & Inheritance Inheritance Objects are created to model ‘things’ Sometimes, ‘things’ may be different, but still have many attributes.
Copyright © The McGraw-Hill Companies, Inc. Permission required for reproduction or display. The Factory Method Design Pattern (1) –A creational design.
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.
Multiple Choice Solutions True/False a c b e d   T F.
Inheritance using Java
REFACTORING Lecture 4. Definition Refactoring is a process of changing the internal structure of the program, not affecting its external behavior and.
Design Patterns.
Inheritance in C++ CS-1030 Dr. Mark L. Hornick.
Inheritance and Class Hierarchies Ellen Walker CPSC 201 Data Structures Hiram College.
Abstract Factory Design Pattern making abstract things.
CSCI-383 Object-Oriented Programming & Design Lecture 13.
Abstract Factory Pattern. What Is an Abstract Factory Pattern?  The Abstract Factory pattern is a creative way to expand on the basic Factory pattern.
Test Isolation and Mocking Technion – Institute of Technology Author: Gal Lalouche © 1 Author: Gal Lalouche - Technion 2015 ©
1 Computer Science 340 Software Design & Testing Inheritance.
Best Practices. Contents Bad Practices Good Practices.
The Factory Patterns SE-2811 Dr. Mark L. Hornick 1.
OOP: Encapsulation,Abstraction & Polymorphism. What is Encapsulation Described as a protective barrier that prevents the code and data being randomly.
Programming in Java CSCI-2220 Object Oriented Programming.
Design Patterns -- Omkar. Introduction  When do we use design patterns  Uses of design patterns  Classification of design patterns  Creational design.
Factory Method Explained. Intent  Define an interface for creating an object, but let subclasses decide which class to instantiate.  Factory Method.
Question of the Day  Thieves guild states it will sell to members: lock picking kits  $0.67 each 40’ rope  $2.12 each Wire cutters  $4.49 each How.
Inheritance and Access Control CS 162 (Summer 2009)
Software Design Patterns Curtsy: Fahad Hassan (TxLabs)
Object Oriented Programing (OOP)
Object Oriented Programming
Design Patterns Software Engineering CS 561. Last Time Introduced design patterns Abstraction-Occurrence General Hierarchy Player-Role.
Dependency Injection Frameworks Technion – Institute of Technology Author: Assaf Israel - Technion 2013 ©
Coming up: Inheritance
Advanced Object-oriented Design Patterns Creational Design Patterns.
Inheritance and Class Hierarchies Chapter 3. Chapter 3: Inheritance and Class Hierarchies2 Chapter Objectives To understand inheritance and how it facilitates.
Proxy Pattern defined The Proxy Pattern provides a surrogate or placeholder for another object to control access to it by creating a representative object.
Quick Review of OOP Constructs Classes:  Data types for structured data and behavior  fields and methods Objects:  Variables whose data type is a class.
Presented by Ted Higgins, SQL Server DBA An Introduction to Object – Oriented Programming.
Chapter 4 Request and Response. Servlets are controlled by the container.
Factory Design Pattern (contn’d). Static Factory Pattern public final class ComplexNumber { // Static factory method returns an object of this class.
This In Java, the keyword this allows an object to refer to itself. Or, in other words, this refers to the current object – the object whose method or.
Design Patterns Creational Patterns. Abstract the instantiation process Help make the system independent of how its objects are created, composed and.
Design Pattern : Builder SPARCS 04 고윤정. Main Concepts One of Creational Patterns. Process to construct Complex object in Abstract type. –Use the same.
Dependency Injection with Guice Technion – Institute of Technology Author: Gal Lalouche - Technion 2016 ©
Notices Assn 2 is due tomorrow, 7pm. Moodle quiz next week – written in the lab as before. Everything up to and including today’s lecture: Big Topics are.
Test Isolation and Mocking Technion – Institute of Technology Author: Gal Lalouche © 1 Author: Gal Lalouche - Technion 2016 ©
1 Inheritance One of the goals of object oriented programming is code reuse. Inheritance is one mechanism for accomplishing code reuse. It allows us to.
Inheritance a subclass extends the functionality of a superclass a subclass inherits all the functionality of a superclass don't reinvent the wheel – "stand.
Copyright © Jim Fawcett Spring 2017
Sections Inheritance and Abstract Classes
OOP: Encapsulation &Abstraction
MPCS – Advanced java Programming
Test Isolation and Mocking
Factory Patterns 1.
Design Patterns I Technion – Institute of Technology
Software Design and Architecture
Magento Technical Guidelines Eugene Shakhsuvarov, Software Magento
Chapter 10 Thinking in Objects
Week 6 Object-Oriented Programming (2): Polymorphism
Interfaces.
Advanced Java Programming
Java Inheritance.
Structural Patterns: Adapter and Bridge
Fundaments of Game Design
Designing For Testability
Chapter 11 Inheritance and Encapsulation and Polymorphism
Jim Fawcett CSE687 – Object Oriented Design Spring 2014
Presentation transcript:

Dependency Injection Technion – Institute of Technology Author: Gal Lalouche - Technion 2015 ©

Class decoupling Consider the following interface: Highly coupled implementation: public interface CreditCardProcessor { void process(PizzaOrder order, CreditCard cc); } class BillingService { private CreditCardProcessor p = new VisaProcessor(); public void chargeOrder(PizzaOrder o, CreditCard cc) { p.process(o, cc); … } 2 Author: Gal Lalouche - Technion 2015 ©

Class decoupling (cont.) What’s the problem? new always applies dependency/coupling! Although we use interfaces, the implementation is highly coupled with VisaProcessor It is much harder to test using real dependencies VisaProcessor can be a very slow class It can have unwanted side effects (do we want to be billed for every test?) How can we replace it with mocks? Solution Pass collaborators (dependencies) to the object This is called Dependency Injection 3 Author: Gal Lalouche - Technion 2015 ©

Dependency Injection The current supplier can behave differently based on the client configuration Can replace VisaProcessor with PaypalProcessor with little fuss Can inject MockProcessor for testing Dependency objects can be reused elsewhere The default behavior can still exist if we desire it Implementation of default behavior depends on the type of injection used 4 Author: Gal Lalouche - Technion 2015 ©

Setters? We can use setters to set the value after object creation We can implement default behavior by calling the setters in the default constructor Is this a good solution? Author: Gal Lalouche - Technion 2015 © 5 public class BillingService { private CreditCardProcessor processor; public void setCreditCardProcessor(CreditCardProcessor p) { processor = p; } public class BillingService { public BillingService { setCreditCardProcessor(new VisaProcessor()) }

Setters – problems There’s a window in which an object has been created and is not yet ready for use What happens if we forget to call a setter? Members cannot be final loss of write-safety; what happens if we call set more than once? class becomes mutable, which is something we should always strive to avoid Client is more verbose What happens if we need several setters? Small improvement over setters: use a Fluent API Author: Gal Lalouche - Technion 2015 © 6 public class C { public C setX(X x) { this.x = x; return this; } C c = new C().setX(x).setY(y) …

Constructors We can pass the object at the construction of the object Dependencies are injected upon object instantiation Object is always in a correct state Class can be immutable We can implement default behavior using a default constructor We can use constructor injection to provide a default constructor in an inheriting class We saw this when we discussed about using OOP in tests: we injected the actual object under test to the parent constructor Author: Gal Lalouche - Technion 2015 © 7 public class BillingService { private final CreditCardProcessor processor; public BillingService(CreditCardProcessor p) { processor = p; }

Builder Objects Combine constructors with setters using the Builder Object Object is always in a valid state Can add validation logic to build() method Class can be immutable Takes quite a bit more code to get running, but is more readble Author: Gal Lalouche - Technion 2015 © 8 public class CBuilder { public CBuilder setX(X x) { this.x = x; return this; } … public C build() { … } } C c = new CBuilder().setX(x).setY(y).build();

Factory Method pattern What if we actually want to create more than one object in our class? We could use a createProcessor() method that will be in charge of creating & configuring our Processor This method is called a factory method This method can be overridden to produce a different concrete implementation Author: Gal Lalouche - Technion 2015 © 9

Factory Method (cont.) To change the dependencies, simply override the method We can implement default behavior by providing a default method implementation Author: Gal Lalouche - Technion 2015 © 10 public class BillingService { private final CreditCardProcessor processor; protected CreditCardProcessor createProcessor(); } class VisaBillingService extends BillingService protected CreditCardProcessor createProcessor() { return new VisaProcessor(); }

Factory Method – Problems Testing is more verbose than using constructors Have to override the factory method Using the same dependencies in different places is difficult What if we want to use VisaProcessor in all of our objects? We may be forced to create many classes, causing visual clutter What do we do when we have two or more dependencies? Author: Gal Lalouche - Technion 2015 © 11

Abstract Factory We would like to separate between an object’s creation and its configuration The point (in the program) of configuration is often different than that of instantiation We will favor composition over inheritance We will delegate the job of object creation to factory objects Author: Gal Lalouche - Technion 2015 © 12

Abstract Factory Pattern 13 Processor process(PizzaOrder, CreditCard) ProcessorFactory create(): CreditCardProcessor VisaProcessorFactory create(): CreditCardProcessor VisaProcessor process(PizzaOrder, CreditCard) > Author: Gal Lalouche - Technion 2015 © > implements

Abstract Factory – Participants To change the dependencies, simply send a new factory: Author: Gal Lalouche - Technion 2015 © 14 public class VisaProcessorFactory implements ProcessorFactory { public VisaProcessor create() { return new VisaProcessor(); } public class PayPalProcessorFactory implements ProcessorFactory { public PayPalProcessor create() { return new PayPalProcessor(); } public class MockProcessorFactory implements ProcessorFactory { public MockProcessor create() { return new MockProcessor(); }

Abstract Factory – Client Client: Author: Gal Lalouche - Technion 2015 © 15 class BillingService { private final ProcessorFactory pf; public BillingService(ProcessorFactory pf) { this.pf = pf; } public void chargeOrder(PizzaOrder o, CreditCard cc) { Processor p = pf.create(); p.process(o, cc); … }

Abstract Factory vs. Factory Method – Names are important! Factory Method Creational logic is handled with methods and inheritance Modifications is handled via overriding the factory method Use when you want to couple the creational and business logic Abstract Factory Creational logic is delegated to an external object So more objects are created/passed around But factories can be reused Use when you want to decouple the creational and business logic Author: Gal Lalouche - Technion 2015 © 16

Don’t over-design A little coupling is okay You should use injection for service objects, and new for data objects generally speaking, it’s okay to use new ArrayList<>() If we replaced every field with a factory our code would blow up Know when to use constructor dependency injection, and when you need a factory Remember, the creational logic needs to be decided somewhere Be careful of creating FactoryFactory ! Author: Gal Lalouche - Technion 2015 © 17