SlideShare une entreprise Scribd logo
1  sur  6
Télécharger pour lire hors ligne
1	of	6
InvertingDependencies
photo credit: Stéfan	(http://www.flickr.com/photos/st3f4n/4085958000/)	()	via
photopin	(http://photopin.com)	cc	(http://creativecommons.org/licenses/by-nc-sa/2.0/)
Polymorphism is the super power of the OO designer. However, many designers don't exploit
this power, they use inheritance for structural purposes. In a language like Java, this results in
an abuse of the instanceof statement	(http://www.javapractices.com/topic/TopicAction.do?Id=31)	.
Maybe Polymorphism is not the right word; maybe we should use multiple personality
disorder (not as sexy as polymorphism when you're trying to sell your OO suite...). Depending
on the runtime context, the object does not change form, it does not morph, it changes
behavior, it behaves as another object.
But the interesting part of this mechanism is how the dependencies align. Looking at the
dependencies from a UML Class diagram viewpoint, inheritance goes in the opposite
direction as composition or aggregation.
The next example shows two different ways for the print method of Object to invoke the
myFunction method of Child. The first case, Child inherites from Object (Template Method
Pattern	(http://sourcemaking.com/design_patterns/template_method)	) this require the myFunction
method to be present in Object. In the second case, Object depends on Child and invokes it.
2	of	6
Object
void	print()
Child
int	myFunction()
Object
int	myFunction()
void	print()
Child
int	myFunction()
However looking at it from a UML sequence diagram viewpoint, the direction of the method
invocation is not reversed.
o:Object c:Child
print()
myFunction()
Concretely, inheritance is a tool that offers the possibility to inverse dependencies arrows
while preserving the direction of behavioral arrows! This super power can be extremely
powerful in light of architectural styles that impose constraints on the direction of
dependencies.
Examples of constraints imposed on the direction of dependencies are Robert C. Martin's
"The Dependency Rule"	(http://blog.8thlight.com/uncle-bob/2012/08/13/the-clean-architecture.html)	and the
layers architectural style. The later imposes a downward "can use" relationship between
layers. By using inheritance, one can respect this structural constraint of downward
dependencies yet allow behavior to invoke upwards.
Let see how all this works, but to do so, let's use a programming language that is not object
oriented. This way the details will not be hidden away by syntactic sugar or by compiler magic.
Let's start by defining Object with a simple struct (Object.h
(https://github.com/luctrudeau/InvertingDependencies/blob/master/Object.h)	)
struct	Object;
struct	Object	build(int	a,	int	b);
struct	Object	{
				int	a;
				int	b;

3	of	6
The first line is a forward declaration, it's required because the Object structure is used inside
the definition of the Object structure. Next, there's the build function that is the equivalent of
a constructor/factory. Finally the Object structure is defined. Notice that the last two
declarations are function pointers. These two function pointers are myFunction that expects
an Object structure as parameter and print that also expects an Object structure as parameter.
Notice that all the implementation details are hidden in Object.c (this is encapsulation). The
idea behind this header file is to expose only the structure but not the behavior. No one
knows, how build work, or even what's in myFunction or print, but they know that these
functions exist. This separation is key in flipping the direction of the dependency without
flipping the direction of invocation.
To find out what the behavior is, we can look at the Object.c
(https://github.com/luctrudeau/InvertingDependencies/blob/master/Object.c)	file.
Now we know that myFunction points to an add function, and that print simply does a printf.
Even if not all languages use the same keyword, the concept of an abstract method is
generally available. We can match this concept to the functions pointers. If these pointers are
not assigned then the method is abstract. This is why you can't instantiate classes with
abstract methods.
Notice that the parameter of the functions inside the Object structure are structures of type
Object. For now, we can think of this as a solution to the problem of accessing the values of
the instance of the Object structure, but we will see shortly that there's another more
				int	(*myFunction)(struct	Object);
				void	(*print)(struct	Object);	
};
#include	"Object.h"
int	add(struct	Object	o)
{
				return	o.a	+	o.b;
}
void	print(struct	Object	o)
{
				printf("Result	=	%dn",	o.myFunction(o));
}
struct	Object	build(int	a,	int	b)
{
				struct	Object	o;
				o.a	=	a;
				o.b	=	b;
				o.myFunction	=	&add;
				o.print	=	&print;
				return	o;
}

4	of	6
profound mechanism at work here. Some programming languages hide this detail behind the
"this" keyword, others like python will make the instance parameter visible to developer and
define it as the first parameter of every method.
Let's say main.c wants to use the Object structure, it only need to include "Object.h", it does
not need to care about Object.c. If we look at the dependencies we can see the inversion effect.
The main.c file depends on Object.h but Object.h does not depend upon Object.c, it's the other
way around Object.c depends upon Object.h. The header file is an abstraction.
main.c
Object.h
struct	Object
struct	Object	build(int	a,	int	b)
Object.c
int	add(struct	Object	o){...}
void	print(struct	Object	o){...}
struct	Object	build(int	a,	int	b)	{...}
<<includes>>
<<includes>>
Now let's try inheritance, I'm not interested in structural inheritance, I don't want to add a
third variable to Object. I'm interested in polymorphism; I want to change the behavior of
Object.
This is the content of Child.h	(https://github.com/luctrudeau/InvertingDependencies/blob/master/Child.h)
The Child depends on Object.h and defines a new constructor/factory buildChild. Let's look at
its behavior (Child.c	(https://github.com/luctrudeau/InvertingDependencies/blob/master/Child.c)	)
#include	"Object.h"
struct	Object	buildChild(int	a,	int	b);

#include	"Child.h"
int	sub(struct	Object	o)
{
				return	o.a	-	o.b;
}
struct	Object	buildChild(int	a,	int	b)
{
				struct	Object	o	=	build(a,b);
				o.myFunction	=	&sub;
				return	o;
}

5	of	6
Instead of invoking the add function, the Child version of the Object structure will invoke the
sub function. Notice how the buildChild function invokes build of Object and then overrides
the myFunction function pointer.
Now we have an Object that acts like a Child, yet almost no one needs to know. The only
entity that needs to know is the one calling buildChild function instead of the build function.
This switch can be executed dynamically at runtime. Looking at main.c we can see that the
choice between the build or the buildChild functions is performed dynamically based on a
random variable.
Dependency injection	(http://martinfowler.com/articles/injection.html)	is exactly what is going on
inside the print function. At runtime, when the buildChild function is selected, the Child
variant of Object is being injected into the print function. This is interesting because the type
of the parameter is mandatory (aka closed	(http://en.wikipedia.org/wiki/Open/closed_principle)	) but its
behavior is not (aka open	(http://en.wikipedia.org/wiki/Open/closed_principle)	).
The Child variant of Object can be developed years after Object was written, by completely
different developers, yet it will still work inside print function without requiring modifications
to the print function.
#include	<stdio.h>
#include	<stdlib.h>
#include	<time.h>
#include	"Object.h"
#include	"Child.h"
int	main()
{
				struct	Object	o;
				srand(time(0));
				if	(rand()	%	2)
				{
								o	=	buildChild(5,	3);
				}	else	{
								o	=	build(2,	3);
				}
				o.print(o);
}

6	of	6
main.c
Object.h
struct	Object
struct	Object	build(int	a,	int	b)
Object.c
int	add(struct	Object	o){...}
void	print(struct	Object	o){...}
struct	Object	build(int	a,	int	b)	{...}
Child.h
struct	Object	buildChild(int	a,	int	b)
Child.c
int	sub(struct	Object	o){...}
struct	Object	buildChild(int	a,	int	b)	{...}
<<includes>><<includes>>
<<includes>>
<<includes>>
<<includes>>
Not only does this allows the Object's print function to invoke the Child's sub function
without depending on it, but to do so Child is the one depending on the Object.

Contenu connexe

Tendances

Javascript Objects Deep Dive
Javascript Objects Deep DiveJavascript Objects Deep Dive
Javascript Objects Deep DiveManish Jangir
 
Javascript Prototypal Inheritance - Big Picture
Javascript Prototypal Inheritance - Big PictureJavascript Prototypal Inheritance - Big Picture
Javascript Prototypal Inheritance - Big PictureManish Jangir
 
Java Static Factory Methods
Java Static Factory MethodsJava Static Factory Methods
Java Static Factory MethodsYe Win
 
Introduction to Design Patterns in Javascript
Introduction to Design Patterns in JavascriptIntroduction to Design Patterns in Javascript
Introduction to Design Patterns in JavascriptSanthosh Kumar Srinivasan
 
Factory Design Pattern
Factory Design PatternFactory Design Pattern
Factory Design PatternJaswant Singh
 
Avoid creating unncessary objects
Avoid creating unncessary objectsAvoid creating unncessary objects
Avoid creating unncessary objectsYe Win
 
Design Patterns Illustrated
Design Patterns IllustratedDesign Patterns Illustrated
Design Patterns IllustratedHerman Peeren
 
JavaScript - Programming Languages course
JavaScript - Programming Languages course JavaScript - Programming Languages course
JavaScript - Programming Languages course yoavrubin
 
Design pattern (Abstract Factory & Singleton)
Design pattern (Abstract Factory & Singleton)Design pattern (Abstract Factory & Singleton)
Design pattern (Abstract Factory & Singleton)paramisoft
 
25 java tough interview questions
25 java tough interview questions25 java tough interview questions
25 java tough interview questionsArun Banotra
 
Scala 3 by Example - Algebraic Data Types for Domain Driven Design - Part 2
Scala 3 by Example - Algebraic Data Types for Domain Driven Design - Part 2Scala 3 by Example - Algebraic Data Types for Domain Driven Design - Part 2
Scala 3 by Example - Algebraic Data Types for Domain Driven Design - Part 2Philip Schwarz
 
Scalable JavaScript Design Patterns
Scalable JavaScript Design PatternsScalable JavaScript Design Patterns
Scalable JavaScript Design PatternsAddy Osmani
 
Angular Interview Questions & Answers
Angular Interview Questions & AnswersAngular Interview Questions & Answers
Angular Interview Questions & AnswersRatnala Charan kumar
 
Compositionality and Category Theory - a montage of slides/transcript for sec...
Compositionality and Category Theory - a montage of slides/transcript for sec...Compositionality and Category Theory - a montage of slides/transcript for sec...
Compositionality and Category Theory - a montage of slides/transcript for sec...Philip Schwarz
 
Definitions of Functional Programming
Definitions of Functional ProgrammingDefinitions of Functional Programming
Definitions of Functional ProgrammingPhilip Schwarz
 

Tendances (20)

Javascript Objects Deep Dive
Javascript Objects Deep DiveJavascript Objects Deep Dive
Javascript Objects Deep Dive
 
Javascript Prototypal Inheritance - Big Picture
Javascript Prototypal Inheritance - Big PictureJavascript Prototypal Inheritance - Big Picture
Javascript Prototypal Inheritance - Big Picture
 
Javascript Design Patterns
Javascript Design PatternsJavascript Design Patterns
Javascript Design Patterns
 
Javascript Design Patterns
Javascript Design PatternsJavascript Design Patterns
Javascript Design Patterns
 
Java Static Factory Methods
Java Static Factory MethodsJava Static Factory Methods
Java Static Factory Methods
 
Prototype
PrototypePrototype
Prototype
 
Introduction to Design Patterns in Javascript
Introduction to Design Patterns in JavascriptIntroduction to Design Patterns in Javascript
Introduction to Design Patterns in Javascript
 
Factory Design Pattern
Factory Design PatternFactory Design Pattern
Factory Design Pattern
 
Avoid creating unncessary objects
Avoid creating unncessary objectsAvoid creating unncessary objects
Avoid creating unncessary objects
 
Design Patterns Illustrated
Design Patterns IllustratedDesign Patterns Illustrated
Design Patterns Illustrated
 
Patterns In-Javascript
Patterns In-JavascriptPatterns In-Javascript
Patterns In-Javascript
 
JavaScript - Programming Languages course
JavaScript - Programming Languages course JavaScript - Programming Languages course
JavaScript - Programming Languages course
 
Design pattern (Abstract Factory & Singleton)
Design pattern (Abstract Factory & Singleton)Design pattern (Abstract Factory & Singleton)
Design pattern (Abstract Factory & Singleton)
 
25 java tough interview questions
25 java tough interview questions25 java tough interview questions
25 java tough interview questions
 
Scala 3 by Example - Algebraic Data Types for Domain Driven Design - Part 2
Scala 3 by Example - Algebraic Data Types for Domain Driven Design - Part 2Scala 3 by Example - Algebraic Data Types for Domain Driven Design - Part 2
Scala 3 by Example - Algebraic Data Types for Domain Driven Design - Part 2
 
Oop Extract
Oop ExtractOop Extract
Oop Extract
 
Scalable JavaScript Design Patterns
Scalable JavaScript Design PatternsScalable JavaScript Design Patterns
Scalable JavaScript Design Patterns
 
Angular Interview Questions & Answers
Angular Interview Questions & AnswersAngular Interview Questions & Answers
Angular Interview Questions & Answers
 
Compositionality and Category Theory - a montage of slides/transcript for sec...
Compositionality and Category Theory - a montage of slides/transcript for sec...Compositionality and Category Theory - a montage of slides/transcript for sec...
Compositionality and Category Theory - a montage of slides/transcript for sec...
 
Definitions of Functional Programming
Definitions of Functional ProgrammingDefinitions of Functional Programming
Definitions of Functional Programming
 

Similaire à Inverting Dependencies

Jump start to OOP, OOAD, and Design Pattern
Jump start to OOP, OOAD, and Design PatternJump start to OOP, OOAD, and Design Pattern
Jump start to OOP, OOAD, and Design PatternNishith Shukla
 
Jump Start To Ooad And Design Patterns
Jump Start To Ooad And Design PatternsJump Start To Ooad And Design Patterns
Jump Start To Ooad And Design PatternsLalit Kale
 
Object Oriented PHP - PART-1
Object Oriented PHP - PART-1Object Oriented PHP - PART-1
Object Oriented PHP - PART-1Jalpesh Vasa
 
C++ [ principles of object oriented programming ]
C++ [ principles of object oriented programming ]C++ [ principles of object oriented programming ]
C++ [ principles of object oriented programming ]Rome468
 
Advanced JavaScript
Advanced JavaScriptAdvanced JavaScript
Advanced JavaScriptFu Cheng
 
My 70-480 HTML5 certification learning
My 70-480 HTML5 certification learningMy 70-480 HTML5 certification learning
My 70-480 HTML5 certification learningSyed Irtaza Ali
 
Ef Poco And Unit Testing
Ef Poco And Unit TestingEf Poco And Unit Testing
Ef Poco And Unit TestingJames Phillips
 
Javascript Object Patterns.pptx
Javascript Object Patterns.pptxJavascript Object Patterns.pptx
Javascript Object Patterns.pptxAlaref Abushaala
 
CSc investigatory project
CSc investigatory projectCSc investigatory project
CSc investigatory projectDIVYANSHU KUMAR
 
(An Extended) Beginners Guide to Object Orientation in PHP
(An Extended) Beginners Guide to Object Orientation in PHP(An Extended) Beginners Guide to Object Orientation in PHP
(An Extended) Beginners Guide to Object Orientation in PHPRick Ogden
 
Javascript design patterns
Javascript design patternsJavascript design patterns
Javascript design patternsGomathiNayagam S
 
The Theory Of The Dom
The Theory Of The DomThe Theory Of The Dom
The Theory Of The Domkaven yan
 

Similaire à Inverting Dependencies (20)

Jump start to OOP, OOAD, and Design Pattern
Jump start to OOP, OOAD, and Design PatternJump start to OOP, OOAD, and Design Pattern
Jump start to OOP, OOAD, and Design Pattern
 
Jump Start To Ooad And Design Patterns
Jump Start To Ooad And Design PatternsJump Start To Ooad And Design Patterns
Jump Start To Ooad And Design Patterns
 
Object Oriented PHP - PART-1
Object Oriented PHP - PART-1Object Oriented PHP - PART-1
Object Oriented PHP - PART-1
 
C++ Interview Questions
C++ Interview QuestionsC++ Interview Questions
C++ Interview Questions
 
C++
C++C++
C++
 
C++ [ principles of object oriented programming ]
C++ [ principles of object oriented programming ]C++ [ principles of object oriented programming ]
C++ [ principles of object oriented programming ]
 
Advanced JavaScript
Advanced JavaScriptAdvanced JavaScript
Advanced JavaScript
 
My 70-480 HTML5 certification learning
My 70-480 HTML5 certification learningMy 70-480 HTML5 certification learning
My 70-480 HTML5 certification learning
 
Composite pattern
Composite patternComposite pattern
Composite pattern
 
Ef Poco And Unit Testing
Ef Poco And Unit TestingEf Poco And Unit Testing
Ef Poco And Unit Testing
 
Javascript Object Patterns.pptx
Javascript Object Patterns.pptxJavascript Object Patterns.pptx
Javascript Object Patterns.pptx
 
Advance oops concepts
Advance oops conceptsAdvance oops concepts
Advance oops concepts
 
CSc investigatory project
CSc investigatory projectCSc investigatory project
CSc investigatory project
 
(An Extended) Beginners Guide to Object Orientation in PHP
(An Extended) Beginners Guide to Object Orientation in PHP(An Extended) Beginners Guide to Object Orientation in PHP
(An Extended) Beginners Guide to Object Orientation in PHP
 
Javascript design patterns
Javascript design patternsJavascript design patterns
Javascript design patterns
 
Sda 8
Sda   8Sda   8
Sda 8
 
The Theory Of The Dom
The Theory Of The DomThe Theory Of The Dom
The Theory Of The Dom
 
Design patterns
Design patternsDesign patterns
Design patterns
 
02 objective-c session 2
02  objective-c session 202  objective-c session 2
02 objective-c session 2
 
Encapsulation
EncapsulationEncapsulation
Encapsulation
 

Plus de Luc Trudeau

Revue de l'année 2019 dans le monde des codecs videos
Revue de l'année 2019 dans le monde des codecs videosRevue de l'année 2019 dans le monde des codecs videos
Revue de l'année 2019 dans le monde des codecs videosLuc Trudeau
 
I don’t care if you have 360 Intra directional predictors
I don’t care if you have 360 Intra directional predictorsI don’t care if you have 360 Intra directional predictors
I don’t care if you have 360 Intra directional predictorsLuc Trudeau
 
Les technologies actuelles et futures de l'ott
Les technologies actuelles et futures de l'ottLes technologies actuelles et futures de l'ott
Les technologies actuelles et futures de l'ottLuc Trudeau
 
Chroma from Luma Intra Prediction for AV1
Chroma from Luma Intra Prediction for AV1Chroma from Luma Intra Prediction for AV1
Chroma from Luma Intra Prediction for AV1Luc Trudeau
 
Chroma From Luma Status Update
Chroma From Luma Status UpdateChroma From Luma Status Update
Chroma From Luma Status UpdateLuc Trudeau
 
ML2 et le Codetributhon
ML2 et le CodetributhonML2 et le Codetributhon
ML2 et le CodetributhonLuc Trudeau
 
HTTP Long Polling is awesome
HTTP Long Polling is awesomeHTTP Long Polling is awesome
HTTP Long Polling is awesomeLuc Trudeau
 
UML Class Diagrams are Awesome
UML Class Diagrams are AwesomeUML Class Diagrams are Awesome
UML Class Diagrams are AwesomeLuc Trudeau
 
Orchestre de services
Orchestre de servicesOrchestre de services
Orchestre de servicesLuc Trudeau
 
Architecture vs Design
Architecture vs DesignArchitecture vs Design
Architecture vs DesignLuc Trudeau
 

Plus de Luc Trudeau (11)

Revue de l'année 2019 dans le monde des codecs videos
Revue de l'année 2019 dans le monde des codecs videosRevue de l'année 2019 dans le monde des codecs videos
Revue de l'année 2019 dans le monde des codecs videos
 
I don’t care if you have 360 Intra directional predictors
I don’t care if you have 360 Intra directional predictorsI don’t care if you have 360 Intra directional predictors
I don’t care if you have 360 Intra directional predictors
 
Les technologies actuelles et futures de l'ott
Les technologies actuelles et futures de l'ottLes technologies actuelles et futures de l'ott
Les technologies actuelles et futures de l'ott
 
Chroma from Luma Intra Prediction for AV1
Chroma from Luma Intra Prediction for AV1Chroma from Luma Intra Prediction for AV1
Chroma from Luma Intra Prediction for AV1
 
Chroma From Luma Status Update
Chroma From Luma Status UpdateChroma From Luma Status Update
Chroma From Luma Status Update
 
ML2 et le Codetributhon
ML2 et le CodetributhonML2 et le Codetributhon
ML2 et le Codetributhon
 
HTTP Long Polling is awesome
HTTP Long Polling is awesomeHTTP Long Polling is awesome
HTTP Long Polling is awesome
 
UML Class Diagrams are Awesome
UML Class Diagrams are AwesomeUML Class Diagrams are Awesome
UML Class Diagrams are Awesome
 
Orchestre de services
Orchestre de servicesOrchestre de services
Orchestre de services
 
HTTP et REST
HTTP et RESTHTTP et REST
HTTP et REST
 
Architecture vs Design
Architecture vs DesignArchitecture vs Design
Architecture vs Design
 

Dernier

%in tembisa+277-882-255-28 abortion pills for sale in tembisa
%in tembisa+277-882-255-28 abortion pills for sale in tembisa%in tembisa+277-882-255-28 abortion pills for sale in tembisa
%in tembisa+277-882-255-28 abortion pills for sale in tembisamasabamasaba
 
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...WSO2
 
%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 masabamasaba
 
%in Bahrain+277-882-255-28 abortion pills for sale in Bahrain
%in Bahrain+277-882-255-28 abortion pills for sale in Bahrain%in Bahrain+277-882-255-28 abortion pills for sale in Bahrain
%in Bahrain+277-882-255-28 abortion pills for sale in Bahrainmasabamasaba
 
Announcing Codolex 2.0 from GDK Software
Announcing Codolex 2.0 from GDK SoftwareAnnouncing Codolex 2.0 from GDK Software
Announcing Codolex 2.0 from GDK SoftwareJim McKeeth
 
Large-scale Logging Made Easy: Meetup at Deutsche Bank 2024
Large-scale Logging Made Easy: Meetup at Deutsche Bank 2024Large-scale Logging Made Easy: Meetup at Deutsche Bank 2024
Large-scale Logging Made Easy: Meetup at Deutsche Bank 2024VictoriaMetrics
 
Artyushina_Guest lecture_YorkU CS May 2024.pptx
Artyushina_Guest lecture_YorkU CS May 2024.pptxArtyushina_Guest lecture_YorkU CS May 2024.pptx
Artyushina_Guest lecture_YorkU CS May 2024.pptxAnnaArtyushina1
 
OpenChain - The Ramifications of ISO/IEC 5230 and ISO/IEC 18974 for Legal Pro...
OpenChain - The Ramifications of ISO/IEC 5230 and ISO/IEC 18974 for Legal Pro...OpenChain - The Ramifications of ISO/IEC 5230 and ISO/IEC 18974 for Legal Pro...
OpenChain - The Ramifications of ISO/IEC 5230 and ISO/IEC 18974 for Legal Pro...Shane Coughlan
 
Architecture decision records - How not to get lost in the past
Architecture decision records - How not to get lost in the pastArchitecture decision records - How not to get lost in the past
Architecture decision records - How not to get lost in the pastPapp Krisztián
 
WSO2Con204 - Hard Rock Presentation - Keynote
WSO2Con204 - Hard Rock Presentation - KeynoteWSO2Con204 - Hard Rock Presentation - Keynote
WSO2Con204 - Hard Rock Presentation - KeynoteWSO2
 
Direct Style Effect Systems - The Print[A] Example - A Comprehension Aid
Direct Style Effect Systems -The Print[A] Example- A Comprehension AidDirect Style Effect Systems -The Print[A] Example- A Comprehension Aid
Direct Style Effect Systems - The Print[A] Example - A Comprehension AidPhilip Schwarz
 
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...WSO2
 
Devoxx UK 2024 - Going serverless with Quarkus, GraalVM native images and AWS...
Devoxx UK 2024 - Going serverless with Quarkus, GraalVM native images and AWS...Devoxx UK 2024 - Going serverless with Quarkus, GraalVM native images and AWS...
Devoxx UK 2024 - Going serverless with Quarkus, GraalVM native images and AWS...Bert Jan Schrijver
 
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 SituationJuha-Pekka Tolvanen
 
%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 sowetomasabamasaba
 
%in Midrand+277-882-255-28 abortion pills for sale in midrand
%in Midrand+277-882-255-28 abortion pills for sale in midrand%in Midrand+277-882-255-28 abortion pills for sale in midrand
%in Midrand+277-882-255-28 abortion pills for sale in midrandmasabamasaba
 
%+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
 
WSO2CON 2024 - Navigating API Complexity: REST, GraphQL, gRPC, Websocket, Web...
WSO2CON 2024 - Navigating API Complexity: REST, GraphQL, gRPC, Websocket, Web...WSO2CON 2024 - Navigating API Complexity: REST, GraphQL, gRPC, Websocket, Web...
WSO2CON 2024 - Navigating API Complexity: REST, GraphQL, gRPC, Websocket, Web...WSO2
 
WSO2CON 2024 - WSO2's Digital Transformation Journey with Choreo: A Platforml...
WSO2CON 2024 - WSO2's Digital Transformation Journey with Choreo: A Platforml...WSO2CON 2024 - WSO2's Digital Transformation Journey with Choreo: A Platforml...
WSO2CON 2024 - WSO2's Digital Transformation Journey with Choreo: A Platforml...WSO2
 

Dernier (20)

%in tembisa+277-882-255-28 abortion pills for sale in tembisa
%in tembisa+277-882-255-28 abortion pills for sale in tembisa%in tembisa+277-882-255-28 abortion pills for sale in tembisa
%in tembisa+277-882-255-28 abortion pills for sale in tembisa
 
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...
 
%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
 
%in Bahrain+277-882-255-28 abortion pills for sale in Bahrain
%in Bahrain+277-882-255-28 abortion pills for sale in Bahrain%in Bahrain+277-882-255-28 abortion pills for sale in Bahrain
%in Bahrain+277-882-255-28 abortion pills for sale in Bahrain
 
Announcing Codolex 2.0 from GDK Software
Announcing Codolex 2.0 from GDK SoftwareAnnouncing Codolex 2.0 from GDK Software
Announcing Codolex 2.0 from GDK Software
 
Abortion Pill Prices Tembisa [(+27832195400*)] 🏥 Women's Abortion Clinic in T...
Abortion Pill Prices Tembisa [(+27832195400*)] 🏥 Women's Abortion Clinic in T...Abortion Pill Prices Tembisa [(+27832195400*)] 🏥 Women's Abortion Clinic in T...
Abortion Pill Prices Tembisa [(+27832195400*)] 🏥 Women's Abortion Clinic in T...
 
Large-scale Logging Made Easy: Meetup at Deutsche Bank 2024
Large-scale Logging Made Easy: Meetup at Deutsche Bank 2024Large-scale Logging Made Easy: Meetup at Deutsche Bank 2024
Large-scale Logging Made Easy: Meetup at Deutsche Bank 2024
 
Artyushina_Guest lecture_YorkU CS May 2024.pptx
Artyushina_Guest lecture_YorkU CS May 2024.pptxArtyushina_Guest lecture_YorkU CS May 2024.pptx
Artyushina_Guest lecture_YorkU CS May 2024.pptx
 
OpenChain - The Ramifications of ISO/IEC 5230 and ISO/IEC 18974 for Legal Pro...
OpenChain - The Ramifications of ISO/IEC 5230 and ISO/IEC 18974 for Legal Pro...OpenChain - The Ramifications of ISO/IEC 5230 and ISO/IEC 18974 for Legal Pro...
OpenChain - The Ramifications of ISO/IEC 5230 and ISO/IEC 18974 for Legal Pro...
 
Architecture decision records - How not to get lost in the past
Architecture decision records - How not to get lost in the pastArchitecture decision records - How not to get lost in the past
Architecture decision records - How not to get lost in the past
 
WSO2Con204 - Hard Rock Presentation - Keynote
WSO2Con204 - Hard Rock Presentation - KeynoteWSO2Con204 - Hard Rock Presentation - Keynote
WSO2Con204 - Hard Rock Presentation - Keynote
 
Direct Style Effect Systems - The Print[A] Example - A Comprehension Aid
Direct Style Effect Systems -The Print[A] Example- A Comprehension AidDirect Style Effect Systems -The Print[A] Example- A Comprehension Aid
Direct Style Effect Systems - The Print[A] Example - A Comprehension Aid
 
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...
 
Devoxx UK 2024 - Going serverless with Quarkus, GraalVM native images and AWS...
Devoxx UK 2024 - Going serverless with Quarkus, GraalVM native images and AWS...Devoxx UK 2024 - Going serverless with Quarkus, GraalVM native images and AWS...
Devoxx UK 2024 - Going serverless with Quarkus, GraalVM native images and AWS...
 
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
 
%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
 
%in Midrand+277-882-255-28 abortion pills for sale in midrand
%in Midrand+277-882-255-28 abortion pills for sale in midrand%in Midrand+277-882-255-28 abortion pills for sale in midrand
%in Midrand+277-882-255-28 abortion pills for sale in midrand
 
%+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...
 
WSO2CON 2024 - Navigating API Complexity: REST, GraphQL, gRPC, Websocket, Web...
WSO2CON 2024 - Navigating API Complexity: REST, GraphQL, gRPC, Websocket, Web...WSO2CON 2024 - Navigating API Complexity: REST, GraphQL, gRPC, Websocket, Web...
WSO2CON 2024 - Navigating API Complexity: REST, GraphQL, gRPC, Websocket, Web...
 
WSO2CON 2024 - WSO2's Digital Transformation Journey with Choreo: A Platforml...
WSO2CON 2024 - WSO2's Digital Transformation Journey with Choreo: A Platforml...WSO2CON 2024 - WSO2's Digital Transformation Journey with Choreo: A Platforml...
WSO2CON 2024 - WSO2's Digital Transformation Journey with Choreo: A Platforml...
 

Inverting Dependencies

  • 1. 1 of 6 InvertingDependencies photo credit: Stéfan (http://www.flickr.com/photos/st3f4n/4085958000/) () via photopin (http://photopin.com) cc (http://creativecommons.org/licenses/by-nc-sa/2.0/) Polymorphism is the super power of the OO designer. However, many designers don't exploit this power, they use inheritance for structural purposes. In a language like Java, this results in an abuse of the instanceof statement (http://www.javapractices.com/topic/TopicAction.do?Id=31) . Maybe Polymorphism is not the right word; maybe we should use multiple personality disorder (not as sexy as polymorphism when you're trying to sell your OO suite...). Depending on the runtime context, the object does not change form, it does not morph, it changes behavior, it behaves as another object. But the interesting part of this mechanism is how the dependencies align. Looking at the dependencies from a UML Class diagram viewpoint, inheritance goes in the opposite direction as composition or aggregation. The next example shows two different ways for the print method of Object to invoke the myFunction method of Child. The first case, Child inherites from Object (Template Method Pattern (http://sourcemaking.com/design_patterns/template_method) ) this require the myFunction method to be present in Object. In the second case, Object depends on Child and invokes it.
  • 2. 2 of 6 Object void print() Child int myFunction() Object int myFunction() void print() Child int myFunction() However looking at it from a UML sequence diagram viewpoint, the direction of the method invocation is not reversed. o:Object c:Child print() myFunction() Concretely, inheritance is a tool that offers the possibility to inverse dependencies arrows while preserving the direction of behavioral arrows! This super power can be extremely powerful in light of architectural styles that impose constraints on the direction of dependencies. Examples of constraints imposed on the direction of dependencies are Robert C. Martin's "The Dependency Rule" (http://blog.8thlight.com/uncle-bob/2012/08/13/the-clean-architecture.html) and the layers architectural style. The later imposes a downward "can use" relationship between layers. By using inheritance, one can respect this structural constraint of downward dependencies yet allow behavior to invoke upwards. Let see how all this works, but to do so, let's use a programming language that is not object oriented. This way the details will not be hidden away by syntactic sugar or by compiler magic. Let's start by defining Object with a simple struct (Object.h (https://github.com/luctrudeau/InvertingDependencies/blob/master/Object.h) ) struct Object; struct Object build(int a, int b); struct Object { int a; int b; 
  • 3. 3 of 6 The first line is a forward declaration, it's required because the Object structure is used inside the definition of the Object structure. Next, there's the build function that is the equivalent of a constructor/factory. Finally the Object structure is defined. Notice that the last two declarations are function pointers. These two function pointers are myFunction that expects an Object structure as parameter and print that also expects an Object structure as parameter. Notice that all the implementation details are hidden in Object.c (this is encapsulation). The idea behind this header file is to expose only the structure but not the behavior. No one knows, how build work, or even what's in myFunction or print, but they know that these functions exist. This separation is key in flipping the direction of the dependency without flipping the direction of invocation. To find out what the behavior is, we can look at the Object.c (https://github.com/luctrudeau/InvertingDependencies/blob/master/Object.c) file. Now we know that myFunction points to an add function, and that print simply does a printf. Even if not all languages use the same keyword, the concept of an abstract method is generally available. We can match this concept to the functions pointers. If these pointers are not assigned then the method is abstract. This is why you can't instantiate classes with abstract methods. Notice that the parameter of the functions inside the Object structure are structures of type Object. For now, we can think of this as a solution to the problem of accessing the values of the instance of the Object structure, but we will see shortly that there's another more int (*myFunction)(struct Object); void (*print)(struct Object); }; #include "Object.h" int add(struct Object o) { return o.a + o.b; } void print(struct Object o) { printf("Result = %dn", o.myFunction(o)); } struct Object build(int a, int b) { struct Object o; o.a = a; o.b = b; o.myFunction = &add; o.print = &print; return o; } 
  • 4. 4 of 6 profound mechanism at work here. Some programming languages hide this detail behind the "this" keyword, others like python will make the instance parameter visible to developer and define it as the first parameter of every method. Let's say main.c wants to use the Object structure, it only need to include "Object.h", it does not need to care about Object.c. If we look at the dependencies we can see the inversion effect. The main.c file depends on Object.h but Object.h does not depend upon Object.c, it's the other way around Object.c depends upon Object.h. The header file is an abstraction. main.c Object.h struct Object struct Object build(int a, int b) Object.c int add(struct Object o){...} void print(struct Object o){...} struct Object build(int a, int b) {...} <<includes>> <<includes>> Now let's try inheritance, I'm not interested in structural inheritance, I don't want to add a third variable to Object. I'm interested in polymorphism; I want to change the behavior of Object. This is the content of Child.h (https://github.com/luctrudeau/InvertingDependencies/blob/master/Child.h) The Child depends on Object.h and defines a new constructor/factory buildChild. Let's look at its behavior (Child.c (https://github.com/luctrudeau/InvertingDependencies/blob/master/Child.c) ) #include "Object.h" struct Object buildChild(int a, int b);  #include "Child.h" int sub(struct Object o) { return o.a - o.b; } struct Object buildChild(int a, int b) { struct Object o = build(a,b); o.myFunction = &sub; return o; } 
  • 5. 5 of 6 Instead of invoking the add function, the Child version of the Object structure will invoke the sub function. Notice how the buildChild function invokes build of Object and then overrides the myFunction function pointer. Now we have an Object that acts like a Child, yet almost no one needs to know. The only entity that needs to know is the one calling buildChild function instead of the build function. This switch can be executed dynamically at runtime. Looking at main.c we can see that the choice between the build or the buildChild functions is performed dynamically based on a random variable. Dependency injection (http://martinfowler.com/articles/injection.html) is exactly what is going on inside the print function. At runtime, when the buildChild function is selected, the Child variant of Object is being injected into the print function. This is interesting because the type of the parameter is mandatory (aka closed (http://en.wikipedia.org/wiki/Open/closed_principle) ) but its behavior is not (aka open (http://en.wikipedia.org/wiki/Open/closed_principle) ). The Child variant of Object can be developed years after Object was written, by completely different developers, yet it will still work inside print function without requiring modifications to the print function. #include <stdio.h> #include <stdlib.h> #include <time.h> #include "Object.h" #include "Child.h" int main() { struct Object o; srand(time(0)); if (rand() % 2) { o = buildChild(5, 3); } else { o = build(2, 3); } o.print(o); } 