SlideShare une entreprise Scribd logo
1  sur  18
Why should we use an INTERFACE
even when we only have one concrete class?
Based on PHP
by Rafal Ksiazek, IT Leader
https://github.com/harpcio
Real example (or maybe not):
Application based on one repository
for an electronics company which has
two departments: one in Europe and one in USA
(Detroit)
Requirements:
…
Sometimes we get an extra job during the day
and we want to know how many free hours we
have
...
Interface
Without With
class Worker {
private $workedHours = 0;
public function work() {
$this->hours += 1;
}
public function getWorkedHours() {
return $this->workedHours;
}
}
class Company {
public function calculateHoursCapacity() {
$workers = $this->hrDepartment->getAllWorkers();
$freeHours = 0;
foreach ($workers as $worker) {
$freeHours += $this->hrDepartment->getFreeHoursLeft($worker);
}
return $freeHours;
}
}
class HRDepartmant {
private $hoursPerDay = 8;
public function getAllWorkers() {}
public function getFreeHoursLeft(Worker $worker) {
return $this->hoursPerDay - $worker->getWorkedHours();
}
}
class Worker implements WorkerInterface {
private $workedHours = 0;
public function work() {
$this->hours += 1;
}
public function getWorkedHours() {
return $this->workedHours;
}
}
class Company {
public function calculateHoursCapacity() {
$workers = $this->hrDepartment->getAllWorkers();
$freeHours = 0;
foreach ($workers as $worker) {
$freeHours += $this->hrDepartment->getFreeHoursLeft($worker);
}
return $freeHours;
}
}
class HRDepartmant {
private $hoursPerDay = 8;
public function getAllWorkers() {}
public function getFreeHoursLeft(WorkerInterface $worker) {
return $hoursPerDay - $worker->getWorkedHours();
}
}
Everything works perfectly
The programmer in the European department got
a $1000 bonus
The company can now handle the extra jobs.
There is one thing we can be sure of:
CHANGE
So be prepared!
New client requirement!
Our department in USA bought
new 24h workers - robots,
we need to handle that
The new functionality should be implemented by a programmer in Detroit
Interface
Without With
class Worker {
...
protected $maxHoursPerDay = 8;
…
public function getMaxHoursPerDay() {
return $this->maxHoursPerDay;
}
}
class Robot extends Worker {
protected $maxHoursPerDay = 24;
}
class HRDepartmant {
...
public function getFreeHoursLeft(Worker $worker) {
return $worker->getMaxHoursPerDay()
- $worker->getWorkedHours();
}
}
interface WorkerInterface {
...
public function getMaxHoursPerDay();
}
class Worker implements WorkerInterface {
...
private $maxHoursPerDay = 8;
…
public function getMaxHoursPerDay() {
return $this->maxHoursPerDay;
}
}
class Robot implements WorkerInterface {
private $workedHours = 0;
private $maxHoursPerDay = 24;
public function work() {
$this->hours += 1;
}
public function getWorkedHours() {
return $this->workedHours;
}
public function getMaxHoursPerDay() {
return $this->maxHoursPerDay;
}
}
class HRDepartmant {
...
public function getFreeHoursLeft(Worker $worker) {
return $worker->getMaxHoursPerDay() - $worker->getWorkedHours();
}
}
New client requirement!
Our departments in both Europe and USA
built canteens for their workers
The new functionality should be implemented by a programmer in Europe
Interface
Without With
class Worker {
...
private $meals = 0;
...
public function eat() {
$this->meals += 1;
}
...
public function getEatenMeals() {
return $this->meals;
}
}
class Company {
public function calculateMealsCost() {
$workers = $this->hrDepartment->getAllWorkers();
$mealsCost = 0;
foreach ($workers as $worker) {
$mealsCost += $this->accountantDepartment->getMealsCost($worker);
}
return $mealsCost;
}
}
class AccountingDepartment {
private $mealCost = 2; // $
public function getMealsCost(Worker $worker) {
return $worker->getEatenMeals() * $this->mealCost;
}
}
interface WorkerInterface {
public function eat();
public function getEatenMeals();
}
.. all the same code from the left side..
.. and after he started testing the application he saw something like this:
FatalErrorException in Robot.php line 21:
Error: Class ApplicationRobot contains 1 abstract method and must therefore
be declared abstract or implement the remaining methods
(ApplicationWorkerInterface::eat())
What is going on!?
The two programmers (one in Europe, one in USA) didn't have the same
knowledge about specific implementations of inherited classes.
Interface
Without With
In this case the programmer unintentionally gave the Robot class a human
behaviour in to form of the eat() method and after some manual testing he
deployed this code to production.
After a few months he was informed that the application is displaying some
strange behaviour: while the departmant in Detroit has only 150 employees,
450 meals are eaten every day.
In this case the programmer also unintentionally provided the Robot's class
with a human behaviour in the form of the eat() method, but he got a fatal error
exception.
He now has the knowledge of the Robot class and he knows that his
implementation is wrong — he can change it and make it more logical.
Interface
Without With
Pros:
● We'll build our application „faster”*
* yes, a couple of minutes less per class is really an irrefutable
fact
Cons:
● Sometimes we can give other classes
behaviours that shouldn't belong to them..
Pros:
● At some point in time, we will be able to save a
lot of our time, the client’s time, and of course
– money
● We can write tests for our classes in a better
way - i.e. FakeArrayRepositories,
FakeFileSystemManagers, FakeConnectors
(like Twitter / Facebook / Google) instead of
creating mocks everywhere..
Cons:
● We need 1-3 minutes to create an interface
Big picture of inheritance
Freelancer
Full time
worker
Worker
Intern
worker
...
Freelancer
... ...
Robots
Adding behaviour to a parent
class also unintentionally
provides child classes with this
new behaviour.
Big picture of interfaces
Freelancer
Full time
worker
Workable
interface
Intern
worker
Freelancer Robots
Eatable
interface
...
Introducing interfaces to our classes
made the application more robust.
Charge'able
interface
Inspection'able
interface
And what about the
Liskov substitution principle?
class Robot extends Worker implements WorkableInterface {
public function eat() {
throw new LogicException('Robots cannot eat');
}
}
but now in this following piece of code we need to do something like this:
foreach($workers as $worker) {
try {
$worker->eat();
} catch (Exception $e) {}
}
And this is a violation of the Liskov substitution principle..
because we cannot substitute Worker with Robot – we need to add
try/catch and we'll be duplicating these try-catches in multiple places..
… it is only a matter of time.
What about KISS
Do you remember the simpler and stupider class?
class A() {
public function doNothing() {
// yes this method really do nothing
}
}
There is another one - the simplest and stupidest
structure.. an interface!!
interface A() {
public function doNothing();
}
What about YAGNI
Yes, but YAGNI is about adding new
functionalities, and interface is a simple and
stupid API without implementation.
It's a simple contract that forces all the classes
that implement the interface to have the same
functionality... nothing more.. nothing less..
Favor composition over inheritance
Inheritance (whitebox reuse) and Composition (blackbox reuse)
If you try to reuse code by inheriting from a class
you will make the subclass dependent on the parent class.
This makes a system in many cases unnecessarily complex and less testable.
Thank you very much
for waching!

Contenu connexe

Tendances

Objects, Testing, and Responsibility
Objects, Testing, and ResponsibilityObjects, Testing, and Responsibility
Objects, Testing, and Responsibilitymachuga
 
HTML, not just for desktops: Firefox OS - Congreso Universitario Móvil - 201...
HTML, not just for desktops: Firefox OS - Congreso Universitario Móvil - 201...HTML, not just for desktops: Firefox OS - Congreso Universitario Móvil - 201...
HTML, not just for desktops: Firefox OS - Congreso Universitario Móvil - 201...Frédéric Harper
 
"Managing API Complexity". Matthew Flaming, Temboo
"Managing API Complexity". Matthew Flaming, Temboo"Managing API Complexity". Matthew Flaming, Temboo
"Managing API Complexity". Matthew Flaming, TembooYandex
 
Bring the fun back to java
Bring the fun back to javaBring the fun back to java
Bring the fun back to javaciklum_ods
 
Non Conventional Android Programming En
Non Conventional Android Programming EnNon Conventional Android Programming En
Non Conventional Android Programming Enguest9bcef2f
 
Surviving javascript.pptx
Surviving javascript.pptxSurviving javascript.pptx
Surviving javascript.pptxTamas Rev
 
Adding ES6 to Your Developer Toolbox
Adding ES6 to Your Developer ToolboxAdding ES6 to Your Developer Toolbox
Adding ES6 to Your Developer ToolboxJeff Strauss
 
iOS,From Development to Distribution
iOS,From Development to DistributioniOS,From Development to Distribution
iOS,From Development to DistributionTunvir Rahman Tusher
 
Mp24: The Bachelor, a facebook game
Mp24: The Bachelor, a facebook gameMp24: The Bachelor, a facebook game
Mp24: The Bachelor, a facebook gameMontreal Python
 
Working Effectively With Legacy Code
Working Effectively With Legacy CodeWorking Effectively With Legacy Code
Working Effectively With Legacy Codescidept
 

Tendances (14)

Tech friday 22.01.2016
Tech friday 22.01.2016Tech friday 22.01.2016
Tech friday 22.01.2016
 
Objects, Testing, and Responsibility
Objects, Testing, and ResponsibilityObjects, Testing, and Responsibility
Objects, Testing, and Responsibility
 
HTML, not just for desktops: Firefox OS - Congreso Universitario Móvil - 201...
HTML, not just for desktops: Firefox OS - Congreso Universitario Móvil - 201...HTML, not just for desktops: Firefox OS - Congreso Universitario Móvil - 201...
HTML, not just for desktops: Firefox OS - Congreso Universitario Móvil - 201...
 
Advance JS and oop
Advance JS and oopAdvance JS and oop
Advance JS and oop
 
Let's migrate to Swift 3.0
Let's migrate to Swift 3.0Let's migrate to Swift 3.0
Let's migrate to Swift 3.0
 
"Managing API Complexity". Matthew Flaming, Temboo
"Managing API Complexity". Matthew Flaming, Temboo"Managing API Complexity". Matthew Flaming, Temboo
"Managing API Complexity". Matthew Flaming, Temboo
 
Bring the fun back to java
Bring the fun back to javaBring the fun back to java
Bring the fun back to java
 
Non Conventional Android Programming En
Non Conventional Android Programming EnNon Conventional Android Programming En
Non Conventional Android Programming En
 
Surviving javascript.pptx
Surviving javascript.pptxSurviving javascript.pptx
Surviving javascript.pptx
 
JavaScript Needn't Hurt!
JavaScript Needn't Hurt!JavaScript Needn't Hurt!
JavaScript Needn't Hurt!
 
Adding ES6 to Your Developer Toolbox
Adding ES6 to Your Developer ToolboxAdding ES6 to Your Developer Toolbox
Adding ES6 to Your Developer Toolbox
 
iOS,From Development to Distribution
iOS,From Development to DistributioniOS,From Development to Distribution
iOS,From Development to Distribution
 
Mp24: The Bachelor, a facebook game
Mp24: The Bachelor, a facebook gameMp24: The Bachelor, a facebook game
Mp24: The Bachelor, a facebook game
 
Working Effectively With Legacy Code
Working Effectively With Legacy CodeWorking Effectively With Legacy Code
Working Effectively With Legacy Code
 

Similaire à Why should we use an INTERFACE even when we only have one concrete class?

How to write not breakable unit tests
How to write not breakable unit testsHow to write not breakable unit tests
How to write not breakable unit testsRafal Ksiazek
 
Twins: Object Oriented Programming and Functional Programming
Twins: Object Oriented Programming and Functional ProgrammingTwins: Object Oriented Programming and Functional Programming
Twins: Object Oriented Programming and Functional ProgrammingRichardWarburton
 
TWINS: OOP and FP - Warburton
TWINS: OOP and FP - WarburtonTWINS: OOP and FP - Warburton
TWINS: OOP and FP - WarburtonCodemotion
 
Extreme Swift
Extreme SwiftExtreme Swift
Extreme SwiftMovel
 
Why should we use SIMPLE FACTORY pattern even when we have one class only?
Why should we use SIMPLE FACTORY pattern even when we have one class only?Why should we use SIMPLE FACTORY pattern even when we have one class only?
Why should we use SIMPLE FACTORY pattern even when we have one class only?Rafal Ksiazek
 
TPSE Thailand 2015 - Rethinking Web with React and Flux
TPSE Thailand 2015 - Rethinking Web with React and FluxTPSE Thailand 2015 - Rethinking Web with React and Flux
TPSE Thailand 2015 - Rethinking Web with React and FluxJirat Kijlerdpornpailoj
 
SystemVerilog OOP Ovm Features Summary
SystemVerilog OOP Ovm Features SummarySystemVerilog OOP Ovm Features Summary
SystemVerilog OOP Ovm Features SummaryAmal Khailtash
 
Tasks: you gotta know how to run them
Tasks: you gotta know how to run themTasks: you gotta know how to run them
Tasks: you gotta know how to run themFilipe Ximenes
 
From object oriented to functional domain modeling
From object oriented to functional domain modelingFrom object oriented to functional domain modeling
From object oriented to functional domain modelingCodemotion
 
From object oriented to functional domain modeling
From object oriented to functional domain modelingFrom object oriented to functional domain modeling
From object oriented to functional domain modelingMario Fusco
 
documents.pub_new-features-in-java-8-it-jpoialjavanaitedwien15java8pdf-java-8...
documents.pub_new-features-in-java-8-it-jpoialjavanaitedwien15java8pdf-java-8...documents.pub_new-features-in-java-8-it-jpoialjavanaitedwien15java8pdf-java-8...
documents.pub_new-features-in-java-8-it-jpoialjavanaitedwien15java8pdf-java-8...Akaks
 
Mastering the Sling Rewriter by Justin Edelson
Mastering the Sling Rewriter by Justin EdelsonMastering the Sling Rewriter by Justin Edelson
Mastering the Sling Rewriter by Justin EdelsonAEM HUB
 
Mastering the Sling Rewriter
Mastering the Sling RewriterMastering the Sling Rewriter
Mastering the Sling RewriterJustin Edelson
 
Things about Functional JavaScript
Things about Functional JavaScriptThings about Functional JavaScript
Things about Functional JavaScriptChengHui Weng
 

Similaire à Why should we use an INTERFACE even when we only have one concrete class? (20)

How to write not breakable unit tests
How to write not breakable unit testsHow to write not breakable unit tests
How to write not breakable unit tests
 
Twins: Object Oriented Programming and Functional Programming
Twins: Object Oriented Programming and Functional ProgrammingTwins: Object Oriented Programming and Functional Programming
Twins: Object Oriented Programming and Functional Programming
 
TWINS: OOP and FP - Warburton
TWINS: OOP and FP - WarburtonTWINS: OOP and FP - Warburton
TWINS: OOP and FP - Warburton
 
SOLID Principles
SOLID PrinciplesSOLID Principles
SOLID Principles
 
OOP
OOPOOP
OOP
 
Extreme Swift
Extreme SwiftExtreme Swift
Extreme Swift
 
Why should we use SIMPLE FACTORY pattern even when we have one class only?
Why should we use SIMPLE FACTORY pattern even when we have one class only?Why should we use SIMPLE FACTORY pattern even when we have one class only?
Why should we use SIMPLE FACTORY pattern even when we have one class only?
 
Wien15 java8
Wien15 java8Wien15 java8
Wien15 java8
 
TPSE Thailand 2015 - Rethinking Web with React and Flux
TPSE Thailand 2015 - Rethinking Web with React and FluxTPSE Thailand 2015 - Rethinking Web with React and Flux
TPSE Thailand 2015 - Rethinking Web with React and Flux
 
SystemVerilog OOP Ovm Features Summary
SystemVerilog OOP Ovm Features SummarySystemVerilog OOP Ovm Features Summary
SystemVerilog OOP Ovm Features Summary
 
Tasks: you gotta know how to run them
Tasks: you gotta know how to run themTasks: you gotta know how to run them
Tasks: you gotta know how to run them
 
Twins: OOP and FP
Twins: OOP and FPTwins: OOP and FP
Twins: OOP and FP
 
From object oriented to functional domain modeling
From object oriented to functional domain modelingFrom object oriented to functional domain modeling
From object oriented to functional domain modeling
 
From object oriented to functional domain modeling
From object oriented to functional domain modelingFrom object oriented to functional domain modeling
From object oriented to functional domain modeling
 
documents.pub_new-features-in-java-8-it-jpoialjavanaitedwien15java8pdf-java-8...
documents.pub_new-features-in-java-8-it-jpoialjavanaitedwien15java8pdf-java-8...documents.pub_new-features-in-java-8-it-jpoialjavanaitedwien15java8pdf-java-8...
documents.pub_new-features-in-java-8-it-jpoialjavanaitedwien15java8pdf-java-8...
 
Mastering the Sling Rewriter by Justin Edelson
Mastering the Sling Rewriter by Justin EdelsonMastering the Sling Rewriter by Justin Edelson
Mastering the Sling Rewriter by Justin Edelson
 
Mastering the Sling Rewriter
Mastering the Sling RewriterMastering the Sling Rewriter
Mastering the Sling Rewriter
 
Things about Functional JavaScript
Things about Functional JavaScriptThings about Functional JavaScript
Things about Functional JavaScript
 
Refactoring
RefactoringRefactoring
Refactoring
 
Practical Celery
Practical CeleryPractical Celery
Practical Celery
 

Dernier

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
 
Try MyIntelliAccount Cloud Accounting Software As A Service Solution Risk Fre...
Try MyIntelliAccount Cloud Accounting Software As A Service Solution Risk Fre...Try MyIntelliAccount Cloud Accounting Software As A Service Solution Risk Fre...
Try MyIntelliAccount Cloud Accounting Software As A Service Solution Risk Fre...MyIntelliSource, Inc.
 
why an Opensea Clone Script might be your perfect match.pdf
why an Opensea Clone Script might be your perfect match.pdfwhy an Opensea Clone Script might be your perfect match.pdf
why an Opensea Clone Script might be your perfect match.pdfjoe51371421
 
The Real-World Challenges of Medical Device Cybersecurity- Mitigating Vulnera...
The Real-World Challenges of Medical Device Cybersecurity- Mitigating Vulnera...The Real-World Challenges of Medical Device Cybersecurity- Mitigating Vulnera...
The Real-World Challenges of Medical Device Cybersecurity- Mitigating Vulnera...ICS
 
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
 
Right Money Management App For Your Financial Goals
Right Money Management App For Your Financial GoalsRight Money Management App For Your Financial Goals
Right Money Management App For Your Financial GoalsJhone kinadey
 
Hand gesture recognition PROJECT PPT.pptx
Hand gesture recognition PROJECT PPT.pptxHand gesture recognition PROJECT PPT.pptx
Hand gesture recognition PROJECT PPT.pptxbodapatigopi8531
 
Clustering techniques data mining book ....
Clustering techniques data mining book ....Clustering techniques data mining book ....
Clustering techniques data mining book ....ShaimaaMohamedGalal
 
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
 
TECUNIQUE: Success Stories: IT Service provider
TECUNIQUE: Success Stories: IT Service providerTECUNIQUE: Success Stories: IT Service provider
TECUNIQUE: Success Stories: IT Service providermohitmore19
 
call girls in Vaishali (Ghaziabad) 🔝 >༒8448380779 🔝 genuine Escort Service 🔝✔️✔️
call girls in Vaishali (Ghaziabad) 🔝 >༒8448380779 🔝 genuine Escort Service 🔝✔️✔️call girls in Vaishali (Ghaziabad) 🔝 >༒8448380779 🔝 genuine Escort Service 🔝✔️✔️
call girls in Vaishali (Ghaziabad) 🔝 >༒8448380779 🔝 genuine Escort Service 🔝✔️✔️Delhi Call girls
 
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.
 
5 Signs You Need a Fashion PLM Software.pdf
5 Signs You Need a Fashion PLM Software.pdf5 Signs You Need a Fashion PLM Software.pdf
5 Signs You Need a Fashion PLM Software.pdfWave PLM
 
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
 
Unlocking the Future of AI Agents with Large Language Models
Unlocking the Future of AI Agents with Large Language ModelsUnlocking the Future of AI Agents with Large Language Models
Unlocking the Future of AI Agents with Large Language Modelsaagamshah0812
 
Software Quality Assurance Interview Questions
Software Quality Assurance Interview QuestionsSoftware Quality Assurance Interview Questions
Software Quality Assurance Interview QuestionsArshad QA
 
How To Troubleshoot Collaboration Apps for the Modern Connected Worker
How To Troubleshoot Collaboration Apps for the Modern Connected WorkerHow To Troubleshoot Collaboration Apps for the Modern Connected Worker
How To Troubleshoot Collaboration Apps for the Modern Connected WorkerThousandEyes
 
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
 

Dernier (20)

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
 
Try MyIntelliAccount Cloud Accounting Software As A Service Solution Risk Fre...
Try MyIntelliAccount Cloud Accounting Software As A Service Solution Risk Fre...Try MyIntelliAccount Cloud Accounting Software As A Service Solution Risk Fre...
Try MyIntelliAccount Cloud Accounting Software As A Service Solution Risk Fre...
 
why an Opensea Clone Script might be your perfect match.pdf
why an Opensea Clone Script might be your perfect match.pdfwhy an Opensea Clone Script might be your perfect match.pdf
why an Opensea Clone Script might be your perfect match.pdf
 
The Real-World Challenges of Medical Device Cybersecurity- Mitigating Vulnera...
The Real-World Challenges of Medical Device Cybersecurity- Mitigating Vulnera...The Real-World Challenges of Medical Device Cybersecurity- Mitigating Vulnera...
The Real-World Challenges of Medical Device Cybersecurity- Mitigating Vulnera...
 
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...
 
Microsoft AI Transformation Partner Playbook.pdf
Microsoft AI Transformation Partner Playbook.pdfMicrosoft AI Transformation Partner Playbook.pdf
Microsoft AI Transformation Partner Playbook.pdf
 
Right Money Management App For Your Financial Goals
Right Money Management App For Your Financial GoalsRight Money Management App For Your Financial Goals
Right Money Management App For Your Financial Goals
 
Hand gesture recognition PROJECT PPT.pptx
Hand gesture recognition PROJECT PPT.pptxHand gesture recognition PROJECT PPT.pptx
Hand gesture recognition PROJECT PPT.pptx
 
Clustering techniques data mining book ....
Clustering techniques data mining book ....Clustering techniques data mining book ....
Clustering techniques data mining book ....
 
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
 
TECUNIQUE: Success Stories: IT Service provider
TECUNIQUE: Success Stories: IT Service providerTECUNIQUE: Success Stories: IT Service provider
TECUNIQUE: Success Stories: IT Service provider
 
call girls in Vaishali (Ghaziabad) 🔝 >༒8448380779 🔝 genuine Escort Service 🔝✔️✔️
call girls in Vaishali (Ghaziabad) 🔝 >༒8448380779 🔝 genuine Escort Service 🔝✔️✔️call girls in Vaishali (Ghaziabad) 🔝 >༒8448380779 🔝 genuine Escort Service 🔝✔️✔️
call girls in Vaishali (Ghaziabad) 🔝 >༒8448380779 🔝 genuine Escort Service 🔝✔️✔️
 
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 ...
 
5 Signs You Need a Fashion PLM Software.pdf
5 Signs You Need a Fashion PLM Software.pdf5 Signs You Need a Fashion PLM Software.pdf
5 Signs You Need a Fashion PLM Software.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
 
Unlocking the Future of AI Agents with Large Language Models
Unlocking the Future of AI Agents with Large Language ModelsUnlocking the Future of AI Agents with Large Language Models
Unlocking the Future of AI Agents with Large Language Models
 
Software Quality Assurance Interview Questions
Software Quality Assurance Interview QuestionsSoftware Quality Assurance Interview Questions
Software Quality Assurance Interview Questions
 
How To Troubleshoot Collaboration Apps for the Modern Connected Worker
How To Troubleshoot Collaboration Apps for the Modern Connected WorkerHow To Troubleshoot Collaboration Apps for the Modern Connected Worker
How To Troubleshoot Collaboration Apps for the Modern Connected Worker
 
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
 
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
 

Why should we use an INTERFACE even when we only have one concrete class?

  • 1. Why should we use an INTERFACE even when we only have one concrete class? Based on PHP by Rafal Ksiazek, IT Leader https://github.com/harpcio
  • 2. Real example (or maybe not): Application based on one repository for an electronics company which has two departments: one in Europe and one in USA (Detroit) Requirements: … Sometimes we get an extra job during the day and we want to know how many free hours we have ...
  • 3. Interface Without With class Worker { private $workedHours = 0; public function work() { $this->hours += 1; } public function getWorkedHours() { return $this->workedHours; } } class Company { public function calculateHoursCapacity() { $workers = $this->hrDepartment->getAllWorkers(); $freeHours = 0; foreach ($workers as $worker) { $freeHours += $this->hrDepartment->getFreeHoursLeft($worker); } return $freeHours; } } class HRDepartmant { private $hoursPerDay = 8; public function getAllWorkers() {} public function getFreeHoursLeft(Worker $worker) { return $this->hoursPerDay - $worker->getWorkedHours(); } } class Worker implements WorkerInterface { private $workedHours = 0; public function work() { $this->hours += 1; } public function getWorkedHours() { return $this->workedHours; } } class Company { public function calculateHoursCapacity() { $workers = $this->hrDepartment->getAllWorkers(); $freeHours = 0; foreach ($workers as $worker) { $freeHours += $this->hrDepartment->getFreeHoursLeft($worker); } return $freeHours; } } class HRDepartmant { private $hoursPerDay = 8; public function getAllWorkers() {} public function getFreeHoursLeft(WorkerInterface $worker) { return $hoursPerDay - $worker->getWorkedHours(); } }
  • 4. Everything works perfectly The programmer in the European department got a $1000 bonus The company can now handle the extra jobs.
  • 5. There is one thing we can be sure of: CHANGE So be prepared!
  • 6. New client requirement! Our department in USA bought new 24h workers - robots, we need to handle that The new functionality should be implemented by a programmer in Detroit
  • 7. Interface Without With class Worker { ... protected $maxHoursPerDay = 8; … public function getMaxHoursPerDay() { return $this->maxHoursPerDay; } } class Robot extends Worker { protected $maxHoursPerDay = 24; } class HRDepartmant { ... public function getFreeHoursLeft(Worker $worker) { return $worker->getMaxHoursPerDay() - $worker->getWorkedHours(); } } interface WorkerInterface { ... public function getMaxHoursPerDay(); } class Worker implements WorkerInterface { ... private $maxHoursPerDay = 8; … public function getMaxHoursPerDay() { return $this->maxHoursPerDay; } } class Robot implements WorkerInterface { private $workedHours = 0; private $maxHoursPerDay = 24; public function work() { $this->hours += 1; } public function getWorkedHours() { return $this->workedHours; } public function getMaxHoursPerDay() { return $this->maxHoursPerDay; } } class HRDepartmant { ... public function getFreeHoursLeft(Worker $worker) { return $worker->getMaxHoursPerDay() - $worker->getWorkedHours(); } }
  • 8. New client requirement! Our departments in both Europe and USA built canteens for their workers The new functionality should be implemented by a programmer in Europe
  • 9. Interface Without With class Worker { ... private $meals = 0; ... public function eat() { $this->meals += 1; } ... public function getEatenMeals() { return $this->meals; } } class Company { public function calculateMealsCost() { $workers = $this->hrDepartment->getAllWorkers(); $mealsCost = 0; foreach ($workers as $worker) { $mealsCost += $this->accountantDepartment->getMealsCost($worker); } return $mealsCost; } } class AccountingDepartment { private $mealCost = 2; // $ public function getMealsCost(Worker $worker) { return $worker->getEatenMeals() * $this->mealCost; } } interface WorkerInterface { public function eat(); public function getEatenMeals(); } .. all the same code from the left side.. .. and after he started testing the application he saw something like this: FatalErrorException in Robot.php line 21: Error: Class ApplicationRobot contains 1 abstract method and must therefore be declared abstract or implement the remaining methods (ApplicationWorkerInterface::eat())
  • 10. What is going on!? The two programmers (one in Europe, one in USA) didn't have the same knowledge about specific implementations of inherited classes. Interface Without With In this case the programmer unintentionally gave the Robot class a human behaviour in to form of the eat() method and after some manual testing he deployed this code to production. After a few months he was informed that the application is displaying some strange behaviour: while the departmant in Detroit has only 150 employees, 450 meals are eaten every day. In this case the programmer also unintentionally provided the Robot's class with a human behaviour in the form of the eat() method, but he got a fatal error exception. He now has the knowledge of the Robot class and he knows that his implementation is wrong — he can change it and make it more logical.
  • 11. Interface Without With Pros: ● We'll build our application „faster”* * yes, a couple of minutes less per class is really an irrefutable fact Cons: ● Sometimes we can give other classes behaviours that shouldn't belong to them.. Pros: ● At some point in time, we will be able to save a lot of our time, the client’s time, and of course – money ● We can write tests for our classes in a better way - i.e. FakeArrayRepositories, FakeFileSystemManagers, FakeConnectors (like Twitter / Facebook / Google) instead of creating mocks everywhere.. Cons: ● We need 1-3 minutes to create an interface
  • 12. Big picture of inheritance Freelancer Full time worker Worker Intern worker ... Freelancer ... ... Robots Adding behaviour to a parent class also unintentionally provides child classes with this new behaviour.
  • 13. Big picture of interfaces Freelancer Full time worker Workable interface Intern worker Freelancer Robots Eatable interface ... Introducing interfaces to our classes made the application more robust. Charge'able interface Inspection'able interface
  • 14. And what about the Liskov substitution principle? class Robot extends Worker implements WorkableInterface { public function eat() { throw new LogicException('Robots cannot eat'); } } but now in this following piece of code we need to do something like this: foreach($workers as $worker) { try { $worker->eat(); } catch (Exception $e) {} } And this is a violation of the Liskov substitution principle.. because we cannot substitute Worker with Robot – we need to add try/catch and we'll be duplicating these try-catches in multiple places.. … it is only a matter of time.
  • 15. What about KISS Do you remember the simpler and stupider class? class A() { public function doNothing() { // yes this method really do nothing } } There is another one - the simplest and stupidest structure.. an interface!! interface A() { public function doNothing(); }
  • 16. What about YAGNI Yes, but YAGNI is about adding new functionalities, and interface is a simple and stupid API without implementation. It's a simple contract that forces all the classes that implement the interface to have the same functionality... nothing more.. nothing less..
  • 17. Favor composition over inheritance Inheritance (whitebox reuse) and Composition (blackbox reuse) If you try to reuse code by inheriting from a class you will make the subclass dependent on the parent class. This makes a system in many cases unnecessarily complex and less testable.
  • 18. Thank you very much for waching!