SlideShare une entreprise Scribd logo
1  sur  31
Dependency Injection
Faiz Mohamed Haneef
Agenda
• Dependency Injection - Design Pattern
• Dependency Injection/DI - Framework
• Create DI Framework with custom compiler like Angular (Hands-On)
• Angular 2+ DI Framework
Before We Start
• Stop Me if Something Isn’t clear.
• Raise your hands / Dance / Wave/ Clap - Grab my attention
• Ground Rules are set.. Lets Start!!!
Design Patterns
• What is it?
Different Patterns
var myCode = {
name: 'Faiz',
sayName: function(){
console.log(this.name);
}
}
myCode.sayName();
var name = "Faiz";
function sayName(name) {
console.log(name);
}
sayName(name);
Design Patterns
• A general reusable solution to a commonly occurring problem
• Are formalized best practices
• Obtained by trial and error
1 Creational Patterns
These design patterns provide a way to create objects while hiding
the creation logic, rather than instantiating objects directly using
new operator. This gives program more flexibility in deciding which
objects need to be created for a given use case.
2 Structural Patterns
These design patterns concern class and object composition. Concept
of inheritance is used to compose interfaces and define ways to
compose objects to obtain new functionalities.
3 Behavioral Patterns
These design patterns are specifically concerned with
communication between objects.
Design Principles
• Law Of Demeter
• Single Responsibility Principle
• Inversion Of Control
Class in Javascript vs Typescript
class Greeter {
greeting: string;
constructor(message: string) {
this.greeting = message;
}
greet() {
return "Hello, " + this.greeting;
}
}
let greeter = new Greeter("world");
var Greeter = function Greeter(message) {
this.greeting = message;
}
Greeter.prototype.greet = function () {
return "Hello, " + this.greeting;
};
var greeter = new Greeter("world");
Quick Recap
• So far good?
• We understand
• Design Patterns
• Design Principles
• TS Class
Lets JUMP into DI !!!!
What's the problem?
export class Car {
public engine: Engine;
public tires: Tires;
public description = 'No DI';
constructor() {
this.engine = new Engine();
this.tires = new Tires();
}
}
What if the Engine class evolves and its
constructor requires a parameter?
What if you want to put a different
brand of tires on your Car?
You have no control over the car's hidden
dependencies. When you can't control the
dependencies, a class becomes difficult to
test.
DI in Javascript vs Typescript
With DI - TS
class Car {
public engine: Engine;
public tires: Tires;
public description = ’With DI';
constructor(engine: Engine, tires: Tires) {
this.engine = engine;
this.tires = tires;
}
}
WITHOUT DI - JS
function Car() {
this.description = 'No DI';
this.engine = new Engine();
this.tires = new Tires();
}
WITH DI - JS
function Car(engine, tires) {
this.description = ’With DI';
this.engine = engine;
this.tires = tires;
}
let car = new Car(new Engine(), new Tires());
Dependency Injection Pattern (Theory)
• The core concept of DI is to invert the control of managing
dependencies so that instead of the client having to manage its own
dependencies, you instead delegate this responsibility to the code
which actually calls your client, typically passing in dependencies as
arguments to that client.
• This is where the name “dependency injection” comes from –
you inject the dependencies into your client code during the
execution of that code.
Inversion Of Control Design Principle
• In object-oriented programming, there are several basic techniques to
implement inversion of control. These are:
• Using a service locator pattern
• Using dependency injection, for example
• Constructor injection
• Parameter injection
• Setter injection
• Interface injection
• Using a contextualized lookup
• Using template method design pattern
• Using strategy design pattern
Benefits of DI
• Loose coupling.
• Testing is very simple.
class MockEngine extends Engine { cylinders = 8; }
class MockTires extends Tires { make = 'YokoGoodStone'; }
// Test car with 8 cylinders and YokoGoodStone tires.
let car = new Car(new MockEngine(), new MockTires());
Detriments of DI
• More difficult to trace.
Consumer Issue
• The consumer of Car has the problem. The consumer must update the car
creation code to something like this:
class Engine2 {
constructor(public cylinders: number) { }
}
// Super car with 12 cylinders and Flintstone tires.
let bigCylinders = 12;
let car = new Car(new Engine2(bigCylinders), new Tires());
How about let car = injector.get(Car);
• The Car knows nothing about creating an Engine or Tires.
• The consumer knows nothing about creating a Car
• This is what a dependency injection framework is all about.
Quick Hands On
• Demo to create an injection Framework like Angular 1
• Demo on Custom Template Compiler as well.
Angular 2 DI
• @NgModule, @Component
Metadata: Providers - A service provider provides the concrete, runtime
version of a dependency value.
@Injectable - decorator identifies a service class that might require
injected dependencies.
injector.get(Car) in Angular 2+ : Injector
• Who?
Angular injector is responsible for creating service instances and injecting
them. The injector maintains an internal token-provider map that it
references when asked for a dependency.
• How?
Register providers with an injector before the injector can create that
service. Angular decorators - @Component and @NgModule accept
metadata with a providers property.
Inject a dependency in the component's constructor by specifying
a constructor parameter with the dependency type
Service Scope
• @NgModule or @Component?
Angular 2+ DI - Characteristics
• Singleton services
• Hierarchical injection system – i.e. if @Component.providers exists, it
also creates a new child injector
The provide object literal
• Responsibility
Locating a dependency value and registering the provider
• Syntax
providers: [Logger] same as
[{ provide: Logger, useClass: Logger }]
Alternative class providers
• [{ provide: Logger, useClass: BetterLogger }]
Class provider with dependencies
@Injectable()
export class EvenBetterLogger extends Logger {
constructor(private userService: UserService) { super(); }
log(message: string) {
let name = this.userService.user.name;
super.log(`Message to ${name}: ${message}`);
}
}
Aliased class providers
[ NewLogger,
// Not aliased! Creates two instances of `NewLogger`
{ provide: OldLogger, useClass: NewLogger}]
The solution: alias with the useExisting option.
[ NewLogger,
// Alias OldLogger w/ reference to NewLogger
{ provide: OldLogger, useExisting: NewLogger}]
Value providers
• // An object in the shape of the logger service
• export function SilentLoggerFn() {}
• const silentLogger = {
• logs: ['Silent logger says "Shhhhh!". Provided via "useValue"'],
• log: SilentLoggerFn
• };
• Then you register a provider with the useValue option, which makes this
object play the logger role.
• [{ provide: Logger, useValue: silentLogger }]
Non-class dependencies
• InjectionToken
Factory providers
src/app/heroes/hero.service.ts
constructor(
private logger: Logger,
private isAuthorized: boolean) { }
)
export let heroServiceProvider = {
provide: HeroService,
useFactory: heroServiceFactory,
deps: [Logger, UserService]
};
src/app/heroes/hero.service.provider.ts (excerpt)
let heroServiceFactory = (logger: Logger, userService: UserService) => {
return new HeroService(logger, userService.user.isAuthorized);
};
The useFactory field tells Angular
that the provider is a factory
function.
The deps property is an array
of provider tokens.
THANK YOU!

Contenu connexe

Tendances

Jug Guice Presentation
Jug Guice PresentationJug Guice Presentation
Jug Guice Presentation
Dmitry Buzdin
 

Tendances (20)

Angular1x and Angular 2 for Beginners
Angular1x and Angular 2 for BeginnersAngular1x and Angular 2 for Beginners
Angular1x and Angular 2 for Beginners
 
Angular 2: core concepts
Angular 2: core conceptsAngular 2: core concepts
Angular 2: core concepts
 
Tech Webinar: Angular 2, Introduction to a new framework
Tech Webinar: Angular 2, Introduction to a new frameworkTech Webinar: Angular 2, Introduction to a new framework
Tech Webinar: Angular 2, Introduction to a new framework
 
Angular 2: What's New?
Angular 2: What's New?Angular 2: What's New?
Angular 2: What's New?
 
Angular2 with type script
Angular2 with type scriptAngular2 with type script
Angular2 with type script
 
Angular 2 - Core Concepts
Angular 2 - Core ConceptsAngular 2 - Core Concepts
Angular 2 - Core Concepts
 
Angular interview questions
Angular interview questionsAngular interview questions
Angular interview questions
 
Angular 5
Angular 5Angular 5
Angular 5
 
Jug Guice Presentation
Jug Guice PresentationJug Guice Presentation
Jug Guice Presentation
 
Angular Application Testing
Angular Application TestingAngular Application Testing
Angular Application Testing
 
JavaScript(Es5) Interview Questions & Answers
JavaScript(Es5)  Interview Questions & AnswersJavaScript(Es5)  Interview Questions & Answers
JavaScript(Es5) Interview Questions & Answers
 
3 Simple Steps to follow to Create React JS Components
3 Simple Steps to follow to Create React JS Components3 Simple Steps to follow to Create React JS Components
3 Simple Steps to follow to Create React JS Components
 
Сергей Больщиков "Angular Components: все уже за, а вы еще нет?"
Сергей Больщиков "Angular Components: все уже за, а вы еще нет?"Сергей Больщиков "Angular Components: все уже за, а вы еще нет?"
Сергей Больщиков "Angular Components: все уже за, а вы еще нет?"
 
The evolution of Angular 2 @ AngularJS Munich Meetup #5
The evolution of Angular 2 @ AngularJS Munich Meetup #5The evolution of Angular 2 @ AngularJS Munich Meetup #5
The evolution of Angular 2 @ AngularJS Munich Meetup #5
 
Angular 2... so can I use it now??
Angular 2... so can I use it now??Angular 2... so can I use it now??
Angular 2... so can I use it now??
 
An introduction to Angular2
An introduction to Angular2 An introduction to Angular2
An introduction to Angular2
 
Introduction to Angular 2
Introduction to Angular 2Introduction to Angular 2
Introduction to Angular 2
 
AngularConf2016 - A leap of faith !?
AngularConf2016 - A leap of faith !?AngularConf2016 - A leap of faith !?
AngularConf2016 - A leap of faith !?
 
Angular 2 overview
Angular 2 overviewAngular 2 overview
Angular 2 overview
 
Creating custom Validators on Reactive Forms using Angular 6
Creating custom Validators on Reactive Forms using Angular 6Creating custom Validators on Reactive Forms using Angular 6
Creating custom Validators on Reactive Forms using Angular 6
 

Similaire à Neoito — Design patterns and depenedency injection

Angularjs for kolkata drupal meetup
Angularjs for kolkata drupal meetupAngularjs for kolkata drupal meetup
Angularjs for kolkata drupal meetup
Goutam Dey
 
The State of Front-end At CrowdTwist
The State of Front-end At CrowdTwistThe State of Front-end At CrowdTwist
The State of Front-end At CrowdTwist
Mark Fayngersh
 
4 Anguadasdfasdasdfasdfsdfasdfaslar (1).pptx
4 Anguadasdfasdasdfasdfsdfasdfaslar (1).pptx4 Anguadasdfasdasdfasdfsdfasdfaslar (1).pptx
4 Anguadasdfasdasdfasdfsdfasdfaslar (1).pptx
tilejak773
 

Similaire à Neoito — Design patterns and depenedency injection (20)

Handlebars and Require.js
Handlebars and Require.jsHandlebars and Require.js
Handlebars and Require.js
 
Lec18
Lec18Lec18
Lec18
 
Angular - Chapter 3 - Components
Angular - Chapter 3 - ComponentsAngular - Chapter 3 - Components
Angular - Chapter 3 - Components
 
Handlebars & Require JS
Handlebars  & Require JSHandlebars  & Require JS
Handlebars & Require JS
 
mean stack
mean stackmean stack
mean stack
 
Code and Design Smells. Are They a Real Threat?
Code and Design Smells. Are They a Real Threat?Code and Design Smells. Are They a Real Threat?
Code and Design Smells. Are They a Real Threat?
 
SDWest2005Goetsch
SDWest2005GoetschSDWest2005Goetsch
SDWest2005Goetsch
 
The Basics Angular JS
The Basics Angular JS The Basics Angular JS
The Basics Angular JS
 
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
 
Angular or Backbone: Go Mobile!
Angular or Backbone: Go Mobile!Angular or Backbone: Go Mobile!
Angular or Backbone: Go Mobile!
 
Angularjs2 presentation
Angularjs2 presentationAngularjs2 presentation
Angularjs2 presentation
 
Angularjs for kolkata drupal meetup
Angularjs for kolkata drupal meetupAngularjs for kolkata drupal meetup
Angularjs for kolkata drupal meetup
 
The State of Front-end At CrowdTwist
The State of Front-end At CrowdTwistThe State of Front-end At CrowdTwist
The State of Front-end At CrowdTwist
 
AngularJs Workshop SDP December 28th 2014
AngularJs Workshop SDP December 28th 2014AngularJs Workshop SDP December 28th 2014
AngularJs Workshop SDP December 28th 2014
 
ME vs WEB - AngularJS Fundamentals
ME vs WEB - AngularJS FundamentalsME vs WEB - AngularJS Fundamentals
ME vs WEB - AngularJS Fundamentals
 
Foundations of programming
Foundations of programmingFoundations of programming
Foundations of programming
 
Angular 9
Angular 9 Angular 9
Angular 9
 
Broncosbuild.xmlBuilds, tests, and runs the project Broncos..docx
Broncosbuild.xmlBuilds, tests, and runs the project Broncos..docxBroncosbuild.xmlBuilds, tests, and runs the project Broncos..docx
Broncosbuild.xmlBuilds, tests, and runs the project Broncos..docx
 
Broncosbuild.xmlBuilds, tests, and runs the project Broncos..docx
Broncosbuild.xmlBuilds, tests, and runs the project Broncos..docxBroncosbuild.xmlBuilds, tests, and runs the project Broncos..docx
Broncosbuild.xmlBuilds, tests, and runs the project Broncos..docx
 
4 Anguadasdfasdasdfasdfsdfasdfaslar (1).pptx
4 Anguadasdfasdasdfasdfsdfasdfaslar (1).pptx4 Anguadasdfasdasdfasdfsdfasdfaslar (1).pptx
4 Anguadasdfasdasdfasdfsdfasdfaslar (1).pptx
 

Plus de Neoito

Plus de Neoito (14)

Neoito — NativeScript Best Coding Practices
Neoito — NativeScript Best Coding PracticesNeoito — NativeScript Best Coding Practices
Neoito — NativeScript Best Coding Practices
 
Neoito — *NIX kungfu for web devs
Neoito — *NIX kungfu for web devsNeoito — *NIX kungfu for web devs
Neoito — *NIX kungfu for web devs
 
Neoito — Secure coding practices
Neoito — Secure coding practicesNeoito — Secure coding practices
Neoito — Secure coding practices
 
Neoito — How modern browsers work
Neoito — How modern browsers workNeoito — How modern browsers work
Neoito — How modern browsers work
 
Neoito — React 101
Neoito — React 101Neoito — React 101
Neoito — React 101
 
Neoito — Scaling node.js
Neoito — Scaling node.jsNeoito — Scaling node.js
Neoito — Scaling node.js
 
Neoito — Grid layout
Neoito — Grid layoutNeoito — Grid layout
Neoito — Grid layout
 
Neoito — Software licensing
Neoito — Software licensingNeoito — Software licensing
Neoito — Software licensing
 
Neoito — GitLab for project management
Neoito — GitLab for project managementNeoito — GitLab for project management
Neoito — GitLab for project management
 
Neoito — Routing and navigation in Angular
Neoito — Routing and navigation in AngularNeoito — Routing and navigation in Angular
Neoito — Routing and navigation in Angular
 
Neoito — Animations in Angular 5
Neoito — Animations in Angular 5Neoito — Animations in Angular 5
Neoito — Animations in Angular 5
 
Neoito — A roadmap to Angular
Neoito — A roadmap to AngularNeoito — A roadmap to Angular
Neoito — A roadmap to Angular
 
Neoito — Intro to WebSockets
Neoito — Intro to WebSocketsNeoito — Intro to WebSockets
Neoito — Intro to WebSockets
 
Neoito — Typography for the web
Neoito — Typography for the webNeoito — Typography for the web
Neoito — Typography for the web
 

Dernier

%+27788225528 love spells in Huntington Beach Psychic Readings, Attraction sp...
%+27788225528 love spells in Huntington Beach Psychic Readings, Attraction sp...%+27788225528 love spells in Huntington Beach Psychic Readings, Attraction sp...
%+27788225528 love spells in Huntington Beach Psychic Readings, Attraction sp...
masabamasaba
 
%+27788225528 love spells in Colorado Springs Psychic Readings, Attraction sp...
%+27788225528 love spells in Colorado Springs Psychic Readings, Attraction sp...%+27788225528 love spells in Colorado Springs Psychic Readings, Attraction sp...
%+27788225528 love spells in Colorado Springs Psychic Readings, Attraction sp...
masabamasaba
 
%+27788225528 love spells in Toronto Psychic Readings, Attraction spells,Brin...
%+27788225528 love spells in Toronto Psychic Readings, Attraction spells,Brin...%+27788225528 love spells in Toronto Psychic Readings, Attraction spells,Brin...
%+27788225528 love spells in Toronto Psychic Readings, Attraction spells,Brin...
masabamasaba
 
%+27788225528 love spells in new york Psychic Readings, Attraction spells,Bri...
%+27788225528 love spells in new york Psychic Readings, Attraction spells,Bri...%+27788225528 love spells in new york Psychic Readings, Attraction spells,Bri...
%+27788225528 love spells in new york Psychic Readings, Attraction spells,Bri...
masabamasaba
 
+971565801893>>SAFE AND ORIGINAL ABORTION PILLS FOR SALE IN DUBAI AND ABUDHAB...
+971565801893>>SAFE AND ORIGINAL ABORTION PILLS FOR SALE IN DUBAI AND ABUDHAB...+971565801893>>SAFE AND ORIGINAL ABORTION PILLS FOR SALE IN DUBAI AND ABUDHAB...
+971565801893>>SAFE AND ORIGINAL ABORTION PILLS FOR SALE IN DUBAI AND ABUDHAB...
Health
 

Dernier (20)

%in Soweto+277-882-255-28 abortion pills for sale in soweto
%in Soweto+277-882-255-28 abortion pills for sale in soweto%in Soweto+277-882-255-28 abortion pills for sale in soweto
%in Soweto+277-882-255-28 abortion pills for sale in soweto
 
WSO2CON2024 - It's time to go Platformless
WSO2CON2024 - It's time to go PlatformlessWSO2CON2024 - It's time to go Platformless
WSO2CON2024 - It's time to go Platformless
 
MarTech Trend 2024 Book : Marketing Technology Trends (2024 Edition) How Data...
MarTech Trend 2024 Book : Marketing Technology Trends (2024 Edition) How Data...MarTech Trend 2024 Book : Marketing Technology Trends (2024 Edition) How Data...
MarTech Trend 2024 Book : Marketing Technology Trends (2024 Edition) How Data...
 
WSO2CON 2024 - Cloud Native Middleware: Domain-Driven Design, Cell-Based Arch...
WSO2CON 2024 - Cloud Native Middleware: Domain-Driven Design, Cell-Based Arch...WSO2CON 2024 - Cloud Native Middleware: Domain-Driven Design, Cell-Based Arch...
WSO2CON 2024 - Cloud Native Middleware: Domain-Driven Design, Cell-Based Arch...
 
WSO2CON 2024 Slides - Open Source to SaaS
WSO2CON 2024 Slides - Open Source to SaaSWSO2CON 2024 Slides - Open Source to SaaS
WSO2CON 2024 Slides - Open Source to SaaS
 
WSO2Con204 - Hard Rock Presentation - Keynote
WSO2Con204 - Hard Rock Presentation - KeynoteWSO2Con204 - Hard Rock Presentation - Keynote
WSO2Con204 - Hard Rock Presentation - Keynote
 
%+27788225528 love spells in Huntington Beach Psychic Readings, Attraction sp...
%+27788225528 love spells in Huntington Beach Psychic Readings, Attraction sp...%+27788225528 love spells in Huntington Beach Psychic Readings, Attraction sp...
%+27788225528 love spells in Huntington Beach Psychic Readings, Attraction sp...
 
%+27788225528 love spells in Colorado Springs Psychic Readings, Attraction sp...
%+27788225528 love spells in Colorado Springs Psychic Readings, Attraction sp...%+27788225528 love spells in Colorado Springs Psychic Readings, Attraction sp...
%+27788225528 love spells in Colorado Springs Psychic Readings, Attraction sp...
 
WSO2CON 2024 - How to Run a Security Program
WSO2CON 2024 - How to Run a Security ProgramWSO2CON 2024 - How to Run a Security Program
WSO2CON 2024 - How to Run a Security Program
 
WSO2Con2024 - WSO2's IAM Vision: Identity-Led Digital Transformation
WSO2Con2024 - WSO2's IAM Vision: Identity-Led Digital TransformationWSO2Con2024 - WSO2's IAM Vision: Identity-Led Digital Transformation
WSO2Con2024 - WSO2's IAM Vision: Identity-Led Digital Transformation
 
What Goes Wrong with Language Definitions and How to Improve the Situation
What Goes Wrong with Language Definitions and How to Improve the SituationWhat Goes Wrong with Language Definitions and How to Improve the Situation
What Goes Wrong with Language Definitions and How to Improve the Situation
 
WSO2Con2024 - From Code To Cloud: Fast Track Your Cloud Native Journey with C...
WSO2Con2024 - From Code To Cloud: Fast Track Your Cloud Native Journey with C...WSO2Con2024 - From Code To Cloud: Fast Track Your Cloud Native Journey with C...
WSO2Con2024 - From Code To Cloud: Fast Track Your Cloud Native Journey with C...
 
%+27788225528 love spells in Toronto Psychic Readings, Attraction spells,Brin...
%+27788225528 love spells in Toronto Psychic Readings, Attraction spells,Brin...%+27788225528 love spells in Toronto Psychic Readings, Attraction spells,Brin...
%+27788225528 love spells in Toronto Psychic Readings, Attraction spells,Brin...
 
%in Stilfontein+277-882-255-28 abortion pills for sale in Stilfontein
%in Stilfontein+277-882-255-28 abortion pills for sale in Stilfontein%in Stilfontein+277-882-255-28 abortion pills for sale in Stilfontein
%in Stilfontein+277-882-255-28 abortion pills for sale in Stilfontein
 
%in ivory park+277-882-255-28 abortion pills for sale in ivory park
%in ivory park+277-882-255-28 abortion pills for sale in ivory park %in ivory park+277-882-255-28 abortion pills for sale in ivory park
%in ivory park+277-882-255-28 abortion pills for sale in ivory park
 
%+27788225528 love spells in new york Psychic Readings, Attraction spells,Bri...
%+27788225528 love spells in new york Psychic Readings, Attraction spells,Bri...%+27788225528 love spells in new york Psychic Readings, Attraction spells,Bri...
%+27788225528 love spells in new york Psychic Readings, Attraction spells,Bri...
 
WSO2Con2024 - Enabling Transactional System's Exponential Growth With Simplicity
WSO2Con2024 - Enabling Transactional System's Exponential Growth With SimplicityWSO2Con2024 - Enabling Transactional System's Exponential Growth With Simplicity
WSO2Con2024 - Enabling Transactional System's Exponential Growth With Simplicity
 
WSO2CON 2024 - Building the API First Enterprise – Running an API Program, fr...
WSO2CON 2024 - Building the API First Enterprise – Running an API Program, fr...WSO2CON 2024 - Building the API First Enterprise – Running an API Program, fr...
WSO2CON 2024 - Building the API First Enterprise – Running an API Program, fr...
 
+971565801893>>SAFE AND ORIGINAL ABORTION PILLS FOR SALE IN DUBAI AND ABUDHAB...
+971565801893>>SAFE AND ORIGINAL ABORTION PILLS FOR SALE IN DUBAI AND ABUDHAB...+971565801893>>SAFE AND ORIGINAL ABORTION PILLS FOR SALE IN DUBAI AND ABUDHAB...
+971565801893>>SAFE AND ORIGINAL ABORTION PILLS FOR SALE IN DUBAI AND ABUDHAB...
 
WSO2CON 2024 - API Management Usage at La Poste and Its Impact on Business an...
WSO2CON 2024 - API Management Usage at La Poste and Its Impact on Business an...WSO2CON 2024 - API Management Usage at La Poste and Its Impact on Business an...
WSO2CON 2024 - API Management Usage at La Poste and Its Impact on Business an...
 

Neoito — Design patterns and depenedency injection

  • 2. Agenda • Dependency Injection - Design Pattern • Dependency Injection/DI - Framework • Create DI Framework with custom compiler like Angular (Hands-On) • Angular 2+ DI Framework
  • 3. Before We Start • Stop Me if Something Isn’t clear. • Raise your hands / Dance / Wave/ Clap - Grab my attention • Ground Rules are set.. Lets Start!!!
  • 5. Different Patterns var myCode = { name: 'Faiz', sayName: function(){ console.log(this.name); } } myCode.sayName(); var name = "Faiz"; function sayName(name) { console.log(name); } sayName(name);
  • 6. Design Patterns • A general reusable solution to a commonly occurring problem • Are formalized best practices • Obtained by trial and error
  • 7. 1 Creational Patterns These design patterns provide a way to create objects while hiding the creation logic, rather than instantiating objects directly using new operator. This gives program more flexibility in deciding which objects need to be created for a given use case. 2 Structural Patterns These design patterns concern class and object composition. Concept of inheritance is used to compose interfaces and define ways to compose objects to obtain new functionalities. 3 Behavioral Patterns These design patterns are specifically concerned with communication between objects.
  • 8. Design Principles • Law Of Demeter • Single Responsibility Principle • Inversion Of Control
  • 9. Class in Javascript vs Typescript class Greeter { greeting: string; constructor(message: string) { this.greeting = message; } greet() { return "Hello, " + this.greeting; } } let greeter = new Greeter("world"); var Greeter = function Greeter(message) { this.greeting = message; } Greeter.prototype.greet = function () { return "Hello, " + this.greeting; }; var greeter = new Greeter("world");
  • 10. Quick Recap • So far good? • We understand • Design Patterns • Design Principles • TS Class Lets JUMP into DI !!!!
  • 11. What's the problem? export class Car { public engine: Engine; public tires: Tires; public description = 'No DI'; constructor() { this.engine = new Engine(); this.tires = new Tires(); } } What if the Engine class evolves and its constructor requires a parameter? What if you want to put a different brand of tires on your Car? You have no control over the car's hidden dependencies. When you can't control the dependencies, a class becomes difficult to test.
  • 12. DI in Javascript vs Typescript With DI - TS class Car { public engine: Engine; public tires: Tires; public description = ’With DI'; constructor(engine: Engine, tires: Tires) { this.engine = engine; this.tires = tires; } } WITHOUT DI - JS function Car() { this.description = 'No DI'; this.engine = new Engine(); this.tires = new Tires(); } WITH DI - JS function Car(engine, tires) { this.description = ’With DI'; this.engine = engine; this.tires = tires; } let car = new Car(new Engine(), new Tires());
  • 13. Dependency Injection Pattern (Theory) • The core concept of DI is to invert the control of managing dependencies so that instead of the client having to manage its own dependencies, you instead delegate this responsibility to the code which actually calls your client, typically passing in dependencies as arguments to that client. • This is where the name “dependency injection” comes from – you inject the dependencies into your client code during the execution of that code.
  • 14. Inversion Of Control Design Principle • In object-oriented programming, there are several basic techniques to implement inversion of control. These are: • Using a service locator pattern • Using dependency injection, for example • Constructor injection • Parameter injection • Setter injection • Interface injection • Using a contextualized lookup • Using template method design pattern • Using strategy design pattern
  • 15. Benefits of DI • Loose coupling. • Testing is very simple. class MockEngine extends Engine { cylinders = 8; } class MockTires extends Tires { make = 'YokoGoodStone'; } // Test car with 8 cylinders and YokoGoodStone tires. let car = new Car(new MockEngine(), new MockTires());
  • 16. Detriments of DI • More difficult to trace.
  • 17. Consumer Issue • The consumer of Car has the problem. The consumer must update the car creation code to something like this: class Engine2 { constructor(public cylinders: number) { } } // Super car with 12 cylinders and Flintstone tires. let bigCylinders = 12; let car = new Car(new Engine2(bigCylinders), new Tires());
  • 18. How about let car = injector.get(Car); • The Car knows nothing about creating an Engine or Tires. • The consumer knows nothing about creating a Car • This is what a dependency injection framework is all about.
  • 19. Quick Hands On • Demo to create an injection Framework like Angular 1 • Demo on Custom Template Compiler as well.
  • 20. Angular 2 DI • @NgModule, @Component Metadata: Providers - A service provider provides the concrete, runtime version of a dependency value. @Injectable - decorator identifies a service class that might require injected dependencies.
  • 21. injector.get(Car) in Angular 2+ : Injector • Who? Angular injector is responsible for creating service instances and injecting them. The injector maintains an internal token-provider map that it references when asked for a dependency. • How? Register providers with an injector before the injector can create that service. Angular decorators - @Component and @NgModule accept metadata with a providers property. Inject a dependency in the component's constructor by specifying a constructor parameter with the dependency type
  • 22. Service Scope • @NgModule or @Component?
  • 23. Angular 2+ DI - Characteristics • Singleton services • Hierarchical injection system – i.e. if @Component.providers exists, it also creates a new child injector
  • 24. The provide object literal • Responsibility Locating a dependency value and registering the provider • Syntax providers: [Logger] same as [{ provide: Logger, useClass: Logger }]
  • 25. Alternative class providers • [{ provide: Logger, useClass: BetterLogger }]
  • 26. Class provider with dependencies @Injectable() export class EvenBetterLogger extends Logger { constructor(private userService: UserService) { super(); } log(message: string) { let name = this.userService.user.name; super.log(`Message to ${name}: ${message}`); } }
  • 27. Aliased class providers [ NewLogger, // Not aliased! Creates two instances of `NewLogger` { provide: OldLogger, useClass: NewLogger}] The solution: alias with the useExisting option. [ NewLogger, // Alias OldLogger w/ reference to NewLogger { provide: OldLogger, useExisting: NewLogger}]
  • 28. Value providers • // An object in the shape of the logger service • export function SilentLoggerFn() {} • const silentLogger = { • logs: ['Silent logger says "Shhhhh!". Provided via "useValue"'], • log: SilentLoggerFn • }; • Then you register a provider with the useValue option, which makes this object play the logger role. • [{ provide: Logger, useValue: silentLogger }]
  • 30. Factory providers src/app/heroes/hero.service.ts constructor( private logger: Logger, private isAuthorized: boolean) { } ) export let heroServiceProvider = { provide: HeroService, useFactory: heroServiceFactory, deps: [Logger, UserService] }; src/app/heroes/hero.service.provider.ts (excerpt) let heroServiceFactory = (logger: Logger, userService: UserService) => { return new HeroService(logger, userService.user.isAuthorized); }; The useFactory field tells Angular that the provider is a factory function. The deps property is an array of provider tokens.

Notes de l'éditeur

  1. https://en.wikipedia.org/wiki/Inversion_of_control
  2. The Law of Demeter (LoD) or principle of least knowledge is a design guideline for developing software, particularly object-oriented programs. In its general form, the LoD is a specific case of loose coupling. The guideline was proposed by Ian Holland at Northeastern University towards the end of 1987, and can be succinctly summarized in each of the following ways:[1] Each unit should have only limited knowledge about other units: only units "closely" related to the current unit. Each unit should only talk to its friends; don't talk to strangers. Only talk to your immediate friends. https://en.wikipedia.org/wiki/Law_of_Demeter https://en.wikipedia.org/wiki/Single_responsibility_principle The single responsibility principle is a computer programming principle that states that every module or class should have responsibility over a single part of the functionality provided by the software, and that responsibility should be entirely encapsulated by the class. All its services should be narrowly aligned with that responsibility. Robert C. Martinexpresses the principle as, "A class should have only one reason to change."[1]
  3. https://www.typescriptlang.org/play/
  4.  Instead of asking for them, the Car constructor instantiates its own copies from the very specific classes Engine and Tires. Forcing me to know how to create Engine class and this is tightly coupled
  5. https://www.typescriptlang.org/play/
  6. https://thesocietea.org/2017/03/design-patterns-dependency-injection/
  7. https://en.wikipedia.org/wiki/Inversion_of_control
  8. With DI, your code is by default more loosely coupled which makes it easier to “plug-and-play” throughout your application; for example, you don’t have to worry about using a dependency that was potentially declared in an external scope compared to where you’re actually using it.  https://en.wikipedia.org/wiki/Dependency_injection#Three_types_of_dependency_injection
  9. When you’re debugging code that’s using DI, if the error stems from a dependency, then you may need to follow your stack trace a little bit further to see where the error actually occurs. Because dependencies no longer exist in the same file and/or class as where your logic is happening, you need to know exactly what called the code in question to understand where the problem may lie. https://www.journaldev.com/1827/java-design-patterns-example-tutorial https://sourcemaking.com/design_patterns https://gist.github.com/demisx/9605099 https://blog.thoughtram.io/angular/2015/05/18/dependency-injection-in-angular-2.html#dependency-injection-as-a-pattern Vojta Jina gave a great talk on dependency injection at ng-conf 2014 https://docs.angularjs.org/api/auto/service/$injector#annotate
  10. To be precise, Angular module providers are registered with the root injector unless the module is lazy loaded. In this sample, all modules are eagerly loaded when the application starts, so all module providers are registered with the app's root injector.