SlideShare a Scribd company logo
1 of 6
Download to read offline
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.

More Related Content

What's hot

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
 

What's hot (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
 

Similar to 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
 

Similar to 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
 

More from 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
 

More from 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
 

Recently uploaded

(Genuine) Escort Service Lucknow | Starting ₹,5K To @25k with A/C 🧑🏽‍❤️‍🧑🏻 89...
(Genuine) Escort Service Lucknow | Starting ₹,5K To @25k with A/C 🧑🏽‍❤️‍🧑🏻 89...(Genuine) Escort Service Lucknow | Starting ₹,5K To @25k with A/C 🧑🏽‍❤️‍🧑🏻 89...
(Genuine) Escort Service Lucknow | Starting ₹,5K To @25k with A/C 🧑🏽‍❤️‍🧑🏻 89...gurkirankumar98700
 
Software Quality Assurance Interview Questions
Software Quality Assurance Interview QuestionsSoftware Quality Assurance Interview Questions
Software Quality Assurance Interview QuestionsArshad QA
 
Diamond Application Development Crafting Solutions with Precision
Diamond Application Development Crafting Solutions with PrecisionDiamond Application Development Crafting Solutions with Precision
Diamond Application Development Crafting Solutions with PrecisionSolGuruz
 
Active Directory Penetration Testing, cionsystems.com.pdf
Active Directory Penetration Testing, cionsystems.com.pdfActive Directory Penetration Testing, cionsystems.com.pdf
Active Directory Penetration Testing, cionsystems.com.pdfCionsystems
 
The Ultimate Test Automation Guide_ Best Practices and Tips.pdf
The Ultimate Test Automation Guide_ Best Practices and Tips.pdfThe Ultimate Test Automation Guide_ Best Practices and Tips.pdf
The Ultimate Test Automation Guide_ Best Practices and Tips.pdfkalichargn70th171
 
SyndBuddy AI 2k Review 2024: Revolutionizing Content Syndication with AI
SyndBuddy AI 2k Review 2024: Revolutionizing Content Syndication with AISyndBuddy AI 2k Review 2024: Revolutionizing Content Syndication with AI
SyndBuddy AI 2k Review 2024: Revolutionizing Content Syndication with AIABDERRAOUF MEHENNI
 
W01_panagenda_Navigating-the-Future-with-The-Hitchhikers-Guide-to-Notes-and-D...
W01_panagenda_Navigating-the-Future-with-The-Hitchhikers-Guide-to-Notes-and-D...W01_panagenda_Navigating-the-Future-with-The-Hitchhikers-Guide-to-Notes-and-D...
W01_panagenda_Navigating-the-Future-with-The-Hitchhikers-Guide-to-Notes-and-D...panagenda
 
Learn the Fundamentals of XCUITest Framework_ A Beginner's Guide.pdf
Learn the Fundamentals of XCUITest Framework_ A Beginner's Guide.pdfLearn the Fundamentals of XCUITest Framework_ A Beginner's Guide.pdf
Learn the Fundamentals of XCUITest Framework_ A Beginner's Guide.pdfkalichargn70th171
 
Unveiling the Tech Salsa of LAMs with Janus in Real-Time Applications
Unveiling the Tech Salsa of LAMs with Janus in Real-Time ApplicationsUnveiling the Tech Salsa of LAMs with Janus in Real-Time Applications
Unveiling the Tech Salsa of LAMs with Janus in Real-Time ApplicationsAlberto González Trastoy
 
Short Story: Unveiling the Reasoning Abilities of Large Language Models by Ke...
Short Story: Unveiling the Reasoning Abilities of Large Language Models by Ke...Short Story: Unveiling the Reasoning Abilities of Large Language Models by Ke...
Short Story: Unveiling the Reasoning Abilities of Large Language Models by Ke...kellynguyen01
 
Shapes for Sharing between Graph Data Spaces - and Epistemic Querying of RDF-...
Shapes for Sharing between Graph Data Spaces - and Epistemic Querying of RDF-...Shapes for Sharing between Graph Data Spaces - and Epistemic Querying of RDF-...
Shapes for Sharing between Graph Data Spaces - and Epistemic Querying of RDF-...Steffen Staab
 
How To Use Server-Side Rendering with Nuxt.js
How To Use Server-Side Rendering with Nuxt.jsHow To Use Server-Side Rendering with Nuxt.js
How To Use Server-Side Rendering with Nuxt.jsAndolasoft Inc
 
Steps To Getting Up And Running Quickly With MyTimeClock Employee Scheduling ...
Steps To Getting Up And Running Quickly With MyTimeClock Employee Scheduling ...Steps To Getting Up And Running Quickly With MyTimeClock Employee Scheduling ...
Steps To Getting Up And Running Quickly With MyTimeClock Employee Scheduling ...MyIntelliSource, Inc.
 
Optimizing AI for immediate response in Smart CCTV
Optimizing AI for immediate response in Smart CCTVOptimizing AI for immediate response in Smart CCTV
Optimizing AI for immediate response in Smart CCTVshikhaohhpro
 
HR Software Buyers Guide in 2024 - HRSoftware.com
HR Software Buyers Guide in 2024 - HRSoftware.comHR Software Buyers Guide in 2024 - HRSoftware.com
HR Software Buyers Guide in 2024 - HRSoftware.comFatema Valibhai
 
Test Automation Strategy for Frontend and Backend
Test Automation Strategy for Frontend and BackendTest Automation Strategy for Frontend and Backend
Test Automation Strategy for Frontend and BackendArshad QA
 

Recently uploaded (20)

(Genuine) Escort Service Lucknow | Starting ₹,5K To @25k with A/C 🧑🏽‍❤️‍🧑🏻 89...
(Genuine) Escort Service Lucknow | Starting ₹,5K To @25k with A/C 🧑🏽‍❤️‍🧑🏻 89...(Genuine) Escort Service Lucknow | Starting ₹,5K To @25k with A/C 🧑🏽‍❤️‍🧑🏻 89...
(Genuine) Escort Service Lucknow | Starting ₹,5K To @25k with A/C 🧑🏽‍❤️‍🧑🏻 89...
 
Software Quality Assurance Interview Questions
Software Quality Assurance Interview QuestionsSoftware Quality Assurance Interview Questions
Software Quality Assurance Interview Questions
 
Diamond Application Development Crafting Solutions with Precision
Diamond Application Development Crafting Solutions with PrecisionDiamond Application Development Crafting Solutions with Precision
Diamond Application Development Crafting Solutions with Precision
 
Active Directory Penetration Testing, cionsystems.com.pdf
Active Directory Penetration Testing, cionsystems.com.pdfActive Directory Penetration Testing, cionsystems.com.pdf
Active Directory Penetration Testing, cionsystems.com.pdf
 
The Ultimate Test Automation Guide_ Best Practices and Tips.pdf
The Ultimate Test Automation Guide_ Best Practices and Tips.pdfThe Ultimate Test Automation Guide_ Best Practices and Tips.pdf
The Ultimate Test Automation Guide_ Best Practices and Tips.pdf
 
SyndBuddy AI 2k Review 2024: Revolutionizing Content Syndication with AI
SyndBuddy AI 2k Review 2024: Revolutionizing Content Syndication with AISyndBuddy AI 2k Review 2024: Revolutionizing Content Syndication with AI
SyndBuddy AI 2k Review 2024: Revolutionizing Content Syndication with AI
 
W01_panagenda_Navigating-the-Future-with-The-Hitchhikers-Guide-to-Notes-and-D...
W01_panagenda_Navigating-the-Future-with-The-Hitchhikers-Guide-to-Notes-and-D...W01_panagenda_Navigating-the-Future-with-The-Hitchhikers-Guide-to-Notes-and-D...
W01_panagenda_Navigating-the-Future-with-The-Hitchhikers-Guide-to-Notes-and-D...
 
Learn the Fundamentals of XCUITest Framework_ A Beginner's Guide.pdf
Learn the Fundamentals of XCUITest Framework_ A Beginner's Guide.pdfLearn the Fundamentals of XCUITest Framework_ A Beginner's Guide.pdf
Learn the Fundamentals of XCUITest Framework_ A Beginner's Guide.pdf
 
Unveiling the Tech Salsa of LAMs with Janus in Real-Time Applications
Unveiling the Tech Salsa of LAMs with Janus in Real-Time ApplicationsUnveiling the Tech Salsa of LAMs with Janus in Real-Time Applications
Unveiling the Tech Salsa of LAMs with Janus in Real-Time Applications
 
Call Girls In Mukherjee Nagar 📱 9999965857 🤩 Delhi 🫦 HOT AND SEXY VVIP 🍎 SE...
Call Girls In Mukherjee Nagar 📱  9999965857  🤩 Delhi 🫦 HOT AND SEXY VVIP 🍎 SE...Call Girls In Mukherjee Nagar 📱  9999965857  🤩 Delhi 🫦 HOT AND SEXY VVIP 🍎 SE...
Call Girls In Mukherjee Nagar 📱 9999965857 🤩 Delhi 🫦 HOT AND SEXY VVIP 🍎 SE...
 
Microsoft AI Transformation Partner Playbook.pdf
Microsoft AI Transformation Partner Playbook.pdfMicrosoft AI Transformation Partner Playbook.pdf
Microsoft AI Transformation Partner Playbook.pdf
 
Short Story: Unveiling the Reasoning Abilities of Large Language Models by Ke...
Short Story: Unveiling the Reasoning Abilities of Large Language Models by Ke...Short Story: Unveiling the Reasoning Abilities of Large Language Models by Ke...
Short Story: Unveiling the Reasoning Abilities of Large Language Models by Ke...
 
Shapes for Sharing between Graph Data Spaces - and Epistemic Querying of RDF-...
Shapes for Sharing between Graph Data Spaces - and Epistemic Querying of RDF-...Shapes for Sharing between Graph Data Spaces - and Epistemic Querying of RDF-...
Shapes for Sharing between Graph Data Spaces - and Epistemic Querying of RDF-...
 
Vip Call Girls Noida ➡️ Delhi ➡️ 9999965857 No Advance 24HRS Live
Vip Call Girls Noida ➡️ Delhi ➡️ 9999965857 No Advance 24HRS LiveVip Call Girls Noida ➡️ Delhi ➡️ 9999965857 No Advance 24HRS Live
Vip Call Girls Noida ➡️ Delhi ➡️ 9999965857 No Advance 24HRS Live
 
How To Use Server-Side Rendering with Nuxt.js
How To Use Server-Side Rendering with Nuxt.jsHow To Use Server-Side Rendering with Nuxt.js
How To Use Server-Side Rendering with Nuxt.js
 
Steps To Getting Up And Running Quickly With MyTimeClock Employee Scheduling ...
Steps To Getting Up And Running Quickly With MyTimeClock Employee Scheduling ...Steps To Getting Up And Running Quickly With MyTimeClock Employee Scheduling ...
Steps To Getting Up And Running Quickly With MyTimeClock Employee Scheduling ...
 
Optimizing AI for immediate response in Smart CCTV
Optimizing AI for immediate response in Smart CCTVOptimizing AI for immediate response in Smart CCTV
Optimizing AI for immediate response in Smart CCTV
 
HR Software Buyers Guide in 2024 - HRSoftware.com
HR Software Buyers Guide in 2024 - HRSoftware.comHR Software Buyers Guide in 2024 - HRSoftware.com
HR Software Buyers Guide in 2024 - HRSoftware.com
 
Test Automation Strategy for Frontend and Backend
Test Automation Strategy for Frontend and BackendTest Automation Strategy for Frontend and Backend
Test Automation Strategy for Frontend and Backend
 
CHEAP Call Girls in Pushp Vihar (-DELHI )🔝 9953056974🔝(=)/CALL GIRLS SERVICE
CHEAP Call Girls in Pushp Vihar (-DELHI )🔝 9953056974🔝(=)/CALL GIRLS SERVICECHEAP Call Girls in Pushp Vihar (-DELHI )🔝 9953056974🔝(=)/CALL GIRLS SERVICE
CHEAP Call Girls in Pushp Vihar (-DELHI )🔝 9953056974🔝(=)/CALL GIRLS SERVICE
 

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); } 