SlideShare una empresa de Scribd logo
1 de 33
Descargar para leer sin conexión
Coupling and Cohesion




       by: Carl Sutton
   http://dogmatic69.com
Cohesion

               Before




After
What is "Cohesion"
 ● Modules / Classes do related jobs
 ● Good: High cohesion
 ● Bad: Low cohesion
 ● Three levels to look at (in Cake apps)
     ○ The Method (does one thing properly)
     ○ The Class (all methods are similar)
     ○ The Plugin (collectively does *a* single job eg: "cart" plugin does not do mini
       blog posts)
What is "Cohesion"
Possible Pros
 ● Easier to understand
 ● More robust
 ● Reliability
 ● Maintainable


Possible Cons
 ● Difficult to understand
 ● Not DRY
Examples of Cohesion
Good:
CakePHP's session class
- all methods manage one set of data, the sessions (Communicational)


Bad:
CakePHP's basics.php file
- a bunch of utilities, related because they are not related (Coincidental)
Levels of "Cohesion"
Coincidental cohesion
  ● Lowest level of cohesion, almost none
  ● Parts of a module are grouped arbitrarily
  ● related because they are not related

Eg:
   ● Utility classes / files
   ● basics.php
Levels of "Cohesion"
Logical cohesion
Parts of a module are grouped because logically they are categorized to do the same thing, even if
they are different by nature.

eg:
      ● Putting all your model files in APP/models
Levels of "Cohesion"
Temporal cohesion
  ● Grouped by when they are processed
  ● the parts are processed at a particular time in program execution

Eg:
   ● a function which is called after catching an exception
        ○ closes open connections
        ○ creates an error log
        ○ notifies the user

Procedural cohesion
  ● parts of a module are grouped because they always follow a certain sequence of execution
  ● Similar to Temporal
Levels of "Cohesion"
Communicational cohesion
  ● Parts of a module are grouped because they operate on the same data.

Eg:
   ● SessionComponent + SessionHelper
   ● Cache engines

Bad Model methods:
Levels of "Cohesion"
Sequential cohesion
  ● parts of a module are grouped because the output from one part is the input to another part like
    an assembly line

Eg:
   ● a function which reads data from a file and processes the data.
   ● Model methods like Find -> beforeFind -> _find -> afterFind -> $output
Levels of "Cohesion"
Functional cohesion
  ● The best Type
  ● parts of a module are grouped because they all contribute to a single well-defined task of the
    module

Eg:
  ● CakeSocket
      ○ Does one single job (low level network communication)




 "Perfection is achieved, not when there is nothing more to add, but when there is nothing left to
                                            take away."
Checking for low cohesion
 ● ClassesThatSeemDifficultToName
 ● Seems like splitting it up would be easy
 ● Tests are (much) bigger than the class/method itself
 ● Tests fail in the same way for different reasons
 ● Code is not DRY


Notes
 ● Rules of premature optimisations apply
 ● No point having hundreds of one line methods or one method classes
 ● Sometimes a bit of low cohesion code is needed and/or better than high cohesion
   (Utility classes)
CakePHP 2.0 - higher cohesion
● Auth was broken into two parts
   ○ AuthComponent
   ○ Authorisation Adaptor
       ■ Digest
       ■ Basic
       ■ Form
       ■ Custom
● basic.php removed random functions
● CakeRequest created
   ○ parts of RequestHandler, Dispacher and Controller
   ○ request and response objects
See code examples
Before




After
What is "Coupling"
 ● Relation between bits of code
 ● Code A requires Code B to work
 ● Similar to dependency (inter dependency)
 ● Changes in Code A ripples changes to Code B
 ● Less is more
     ○ Good: ([low][loose][weak]) coupling
     ○ Bad: ([high][tight][strong]) coupling
What is "Coupling"
Possible Pros
 ● Dumb code
 ● Easier to:
     ○ read
     ○ debug
     ○ test
     ○ reuse (DRY)
     ○ maintain
 ● Cheaper / quicker to extend
Possible Cons
 ● More overhead
 ● More magic
 ● Longer dev time / more expensive initially
Examples of Coupling
Good (loose):
CakePHP's ORM (1.x -> )
- use MySQL, MsSQL, PostgreSQL or Custom with the same code

CakePHP's JS Engine (1.3.x -> )
- use jQuery, Prototype, Prototype or Custom with the same code
CakePHP's Cache (1.x -> )
- File, APC, XCache, Memcache or Custom

CakePHP's Sessions (1.x -> )
- use cake (file), PHP, database or cache

Bad (tight):
CakePHP's test suite (1.x -> )
- hard coded to use Simple Test
Levels of "Coupling"
Content coupling (high)
   ● One module modifies / relies on the internal workings of another module.

eg:
      ● Router::* changes
      ● In 1.3 Helpers (without the analogue code you were stuck)
            ○ 2.0 can replace helper instances on the fly with another instance
                  ■ $this->Html could be MyCustomHtmlHelper extends HtmlHelper
Levels of "Coupling"
Common coupling
  ● Two modules share the same global data.

Eg:
      ● SessionComponent + SessionHelper
           ○ moving where setFlash() saved messages requires changes to flash()
Levels of "Coupling"
External coupling
   ● Two or more modules share an externally imposed data format
         ○ communication protocol (imap, pop3, ftp, http etc)
         ○ device interface
         ○ file format (csv, xml, json etc)

Eg:
      ● EmailComponent
           ○ RFC 2822 - Internet Message Format
      ● Database Driver MySQL, MSSQL etc
           ○ need to use SQL language
Levels of "Coupling"
Control coupling
   ● one module controlling the flow of another
   ● passing it information on what to do

Eg:
      ● Controller starting up a Component
Levels of "Coupling"
Stamp coupling (Data-structured coupling)
   ● modules share a composite data structure and use only a part of it

eg:
      ● function foo($options){ return $options['bar'] * 10;}
      ● validation methods only get the field they are validating (good)
Levels of "Coupling"
Data coupling
    ● modules share data through, for example, parameters.
    ● Each datum is an elementary piece, and these are the only data shared.
eg:
    ● validation methods in a Model class
Levels of "Coupling"
Message coupling (low)
This is the loosest type of coupling. It can be achieved by state decentralization. JS Engine, Cache Engine, ORM etc

No coupling
   ● Modules do not communicate at all with one another.
   ● Only time there is *no* coupling is when you have a formatted HDD :P

Eg:
      ● EmailComponent is not coupled directly to Models
Levels of "Coupling"
Message coupling (low)
    ● This is the loosest type of coupling.
    ● Achieved by state decentralization.
Eg:
    ● JS Engine, Cache Engine, ORM etc
    ● you call a main 'engine' class that calls the correct class that you need
    ● Dependency injection
    ● Observable
Levels of "Coupling"
No coupling
   ● Modules do not communicate at all with one another.
   ● rm -rf /* will remove all coupling

Eg:
      ● EmailComponent is not coupled directly to Models
Checking for high coupling
 ● Changes to code A requires changes to code B, C etc
 ● Reuse of code is difficult / impossible
 ● Testing is super complicated
CakePHP 2.0 - lower coupling
● Auth was broken into two parts
   ○ Authorisation Adaptor - custom authorisation classes
● Dispatcher
   ○ Parts moved to the Controller so its easy to change /
     extend (not coupled to the one cake way)
● switch helpers and components on the fly
   ○ no need to use $this->MyCustomHtmlHelper->foo()
See code examples
Related stuff

 ● Coupling
 ● Cohesion
 ● DRY
 ● Dependency
 ● Cyclomatic complexity
 ● Adapter Pattern
 ● Dependency_injection
 ● Observer
 ● SRP
Links

        dogmatic69
        CakePHP
        Infinitas

Más contenido relacionado

La actualidad más candente

Software design principles
Software design principlesSoftware design principles
Software design principles
Ritesh Singh
 
Design concepts and principles
Design concepts and principlesDesign concepts and principles
Design concepts and principles
saurabhshertukde
 
Pressman ch-11-component-level-design
Pressman ch-11-component-level-designPressman ch-11-component-level-design
Pressman ch-11-component-level-design
Oliver Cheng
 
Design process and concepts
Design process and conceptsDesign process and concepts
Design process and concepts
Slideshare
 
Chapter 4 software design
Chapter 4  software designChapter 4  software design
Chapter 4 software design
Cliftone Mullah
 

La actualidad más candente (20)

Cohesion and Coupling - The Keys To Changing Your Code With Confidence
Cohesion and Coupling - The Keys To Changing Your Code With ConfidenceCohesion and Coupling - The Keys To Changing Your Code With Confidence
Cohesion and Coupling - The Keys To Changing Your Code With Confidence
 
Design final
Design finalDesign final
Design final
 
Seii unit7 component-level-design
Seii unit7 component-level-designSeii unit7 component-level-design
Seii unit7 component-level-design
 
Slides chapters 28-32
Slides chapters 28-32Slides chapters 28-32
Slides chapters 28-32
 
Design engineering cohesion by dinesh
Design engineering cohesion by dineshDesign engineering cohesion by dinesh
Design engineering cohesion by dinesh
 
Design Principles
Design PrinciplesDesign Principles
Design Principles
 
Software design principles
Software design principlesSoftware design principles
Software design principles
 
Design Concept software engineering
Design Concept software engineeringDesign Concept software engineering
Design Concept software engineering
 
Design concepts and principles
Design concepts and principlesDesign concepts and principles
Design concepts and principles
 
Unit iii(part d - component level design)
Unit   iii(part d - component level design)Unit   iii(part d - component level design)
Unit iii(part d - component level design)
 
Thesis Giani UIC Slides EN
Thesis Giani UIC Slides ENThesis Giani UIC Slides EN
Thesis Giani UIC Slides EN
 
Design techniques
Design techniquesDesign techniques
Design techniques
 
Pressman ch-11-component-level-design
Pressman ch-11-component-level-designPressman ch-11-component-level-design
Pressman ch-11-component-level-design
 
Design process and concepts
Design process and conceptsDesign process and concepts
Design process and concepts
 
Chapter 4 software design
Chapter 4  software designChapter 4  software design
Chapter 4 software design
 
Coupling coheshion tps
Coupling coheshion tpsCoupling coheshion tps
Coupling coheshion tps
 
SE18_Lec 06_Object Oriented Analysis and Design
SE18_Lec 06_Object Oriented Analysis and DesignSE18_Lec 06_Object Oriented Analysis and Design
SE18_Lec 06_Object Oriented Analysis and Design
 
Software Designing - Software Engineering
Software Designing - Software EngineeringSoftware Designing - Software Engineering
Software Designing - Software Engineering
 
Fundamentals of Software Engineering
Fundamentals of Software Engineering Fundamentals of Software Engineering
Fundamentals of Software Engineering
 
PhD Thesis Presentation
PhD Thesis PresentationPhD Thesis Presentation
PhD Thesis Presentation
 

Destacado

Chapter 5 software design
Chapter 5 software designChapter 5 software design
Chapter 5 software design
Piyush Gogia
 
Software requirements specification
Software  requirements specificationSoftware  requirements specification
Software requirements specification
Krishnasai Gudavalli
 

Destacado (11)

Software Design 1: Coupling & cohesion
Software Design 1: Coupling & cohesionSoftware Design 1: Coupling & cohesion
Software Design 1: Coupling & cohesion
 
Cohesion & Coupling
Cohesion & Coupling Cohesion & Coupling
Cohesion & Coupling
 
Chapter 5 software design
Chapter 5 software designChapter 5 software design
Chapter 5 software design
 
Melbourne Microservices Meetup: Agenda for a new Architecture
Melbourne Microservices Meetup: Agenda for a new ArchitectureMelbourne Microservices Meetup: Agenda for a new Architecture
Melbourne Microservices Meetup: Agenda for a new Architecture
 
Cohesion and coupling metrics for workflow process design
Cohesion and coupling metrics for workflow process designCohesion and coupling metrics for workflow process design
Cohesion and coupling metrics for workflow process design
 
Solid Principles, for better cohesion and lower coupling
Solid Principles, for better cohesion and lower coupling Solid Principles, for better cohesion and lower coupling
Solid Principles, for better cohesion and lower coupling
 
Introduction of control engineering
Introduction of control engineeringIntroduction of control engineering
Introduction of control engineering
 
8 Characteristics of good user requirements
8 Characteristics of good user requirements8 Characteristics of good user requirements
8 Characteristics of good user requirements
 
SRS on Online Blood Bank Managment system...
SRS on Online Blood Bank Managment system... SRS on Online Blood Bank Managment system...
SRS on Online Blood Bank Managment system...
 
Software requirements specification
Software  requirements specificationSoftware  requirements specification
Software requirements specification
 
Cohesion Types
Cohesion TypesCohesion Types
Cohesion Types
 

Similar a CakeFest 2011 - Coupling and cohesion

Similar a CakeFest 2011 - Coupling and cohesion (20)

Concurrency - Why it's hard ?
Concurrency - Why it's hard ?Concurrency - Why it's hard ?
Concurrency - Why it's hard ?
 
Why Concurrency is hard ?
Why Concurrency is hard ?Why Concurrency is hard ?
Why Concurrency is hard ?
 
Single Responsibility Principle
Single Responsibility PrincipleSingle Responsibility Principle
Single Responsibility Principle
 
Routing
RoutingRouting
Routing
 
Angular Rebooted: Components Everywhere - Carlo Bonamico, Sonia Pini - Codemo...
Angular Rebooted: Components Everywhere - Carlo Bonamico, Sonia Pini - Codemo...Angular Rebooted: Components Everywhere - Carlo Bonamico, Sonia Pini - Codemo...
Angular Rebooted: Components Everywhere - Carlo Bonamico, Sonia Pini - Codemo...
 
Angular Rebooted: Components Everywhere
Angular Rebooted: Components EverywhereAngular Rebooted: Components Everywhere
Angular Rebooted: Components Everywhere
 
Etl confessions pg conf us 2017
Etl confessions   pg conf us 2017Etl confessions   pg conf us 2017
Etl confessions pg conf us 2017
 
FRU Kathmandu: Adopting with Change Frontend Architecture and Patterns
FRU Kathmandu: Adopting with Change Frontend Architecture and PatternsFRU Kathmandu: Adopting with Change Frontend Architecture and Patterns
FRU Kathmandu: Adopting with Change Frontend Architecture and Patterns
 
From class to architecture
From class to architectureFrom class to architecture
From class to architecture
 
Intro to ember.js
Intro to ember.jsIntro to ember.js
Intro to ember.js
 
Software Craftmanship - Cours Polytech
Software Craftmanship - Cours PolytechSoftware Craftmanship - Cours Polytech
Software Craftmanship - Cours Polytech
 
Load testing in Zonky with Gatling
Load testing in Zonky with GatlingLoad testing in Zonky with Gatling
Load testing in Zonky with Gatling
 
Interop 2015: Hardly Enough Theory, Barley Enough Code
Interop 2015: Hardly Enough Theory, Barley Enough CodeInterop 2015: Hardly Enough Theory, Barley Enough Code
Interop 2015: Hardly Enough Theory, Barley Enough Code
 
Advanced web application architecture - Talk
Advanced web application architecture - TalkAdvanced web application architecture - Talk
Advanced web application architecture - Talk
 
Software Design Practices for Large-Scale Automation
Software Design Practices for Large-Scale AutomationSoftware Design Practices for Large-Scale Automation
Software Design Practices for Large-Scale Automation
 
Java 9 Features
Java 9 FeaturesJava 9 Features
Java 9 Features
 
Carlo Bonamico, Sonia Pini - So you want to build your (Angular) Component Li...
Carlo Bonamico, Sonia Pini - So you want to build your (Angular) Component Li...Carlo Bonamico, Sonia Pini - So you want to build your (Angular) Component Li...
Carlo Bonamico, Sonia Pini - So you want to build your (Angular) Component Li...
 
Build Your Own Angular Component Library
Build Your Own Angular Component LibraryBuild Your Own Angular Component Library
Build Your Own Angular Component Library
 
Keeping business logic out of your UIs
Keeping business logic out of your UIsKeeping business logic out of your UIs
Keeping business logic out of your UIs
 
Parallel Computing - Lec 5
Parallel Computing - Lec 5Parallel Computing - Lec 5
Parallel Computing - Lec 5
 

Último

Architecting Cloud Native Applications
Architecting Cloud Native ApplicationsArchitecting Cloud Native Applications
Architecting Cloud Native Applications
WSO2
 
Cloud Frontiers: A Deep Dive into Serverless Spatial Data and FME
Cloud Frontiers:  A Deep Dive into Serverless Spatial Data and FMECloud Frontiers:  A Deep Dive into Serverless Spatial Data and FME
Cloud Frontiers: A Deep Dive into Serverless Spatial Data and FME
Safe Software
 

Último (20)

Emergent Methods: Multi-lingual narrative tracking in the news - real-time ex...
Emergent Methods: Multi-lingual narrative tracking in the news - real-time ex...Emergent Methods: Multi-lingual narrative tracking in the news - real-time ex...
Emergent Methods: Multi-lingual narrative tracking in the news - real-time ex...
 
Understanding the FAA Part 107 License ..
Understanding the FAA Part 107 License ..Understanding the FAA Part 107 License ..
Understanding the FAA Part 107 License ..
 
ICT role in 21st century education and its challenges
ICT role in 21st century education and its challengesICT role in 21st century education and its challenges
ICT role in 21st century education and its challenges
 
Artificial Intelligence Chap.5 : Uncertainty
Artificial Intelligence Chap.5 : UncertaintyArtificial Intelligence Chap.5 : Uncertainty
Artificial Intelligence Chap.5 : Uncertainty
 
Platformless Horizons for Digital Adaptability
Platformless Horizons for Digital AdaptabilityPlatformless Horizons for Digital Adaptability
Platformless Horizons for Digital Adaptability
 
Apidays New York 2024 - Accelerating FinTech Innovation by Vasa Krishnan, Fin...
Apidays New York 2024 - Accelerating FinTech Innovation by Vasa Krishnan, Fin...Apidays New York 2024 - Accelerating FinTech Innovation by Vasa Krishnan, Fin...
Apidays New York 2024 - Accelerating FinTech Innovation by Vasa Krishnan, Fin...
 
Strategize a Smooth Tenant-to-tenant Migration and Copilot Takeoff
Strategize a Smooth Tenant-to-tenant Migration and Copilot TakeoffStrategize a Smooth Tenant-to-tenant Migration and Copilot Takeoff
Strategize a Smooth Tenant-to-tenant Migration and Copilot Takeoff
 
Six Myths about Ontologies: The Basics of Formal Ontology
Six Myths about Ontologies: The Basics of Formal OntologySix Myths about Ontologies: The Basics of Formal Ontology
Six Myths about Ontologies: The Basics of Formal Ontology
 
AWS Community Day CPH - Three problems of Terraform
AWS Community Day CPH - Three problems of TerraformAWS Community Day CPH - Three problems of Terraform
AWS Community Day CPH - Three problems of Terraform
 
Apidays New York 2024 - The value of a flexible API Management solution for O...
Apidays New York 2024 - The value of a flexible API Management solution for O...Apidays New York 2024 - The value of a flexible API Management solution for O...
Apidays New York 2024 - The value of a flexible API Management solution for O...
 
Architecting Cloud Native Applications
Architecting Cloud Native ApplicationsArchitecting Cloud Native Applications
Architecting Cloud Native Applications
 
[BuildWithAI] Introduction to Gemini.pdf
[BuildWithAI] Introduction to Gemini.pdf[BuildWithAI] Introduction to Gemini.pdf
[BuildWithAI] Introduction to Gemini.pdf
 
"I see eyes in my soup": How Delivery Hero implemented the safety system for ...
"I see eyes in my soup": How Delivery Hero implemented the safety system for ..."I see eyes in my soup": How Delivery Hero implemented the safety system for ...
"I see eyes in my soup": How Delivery Hero implemented the safety system for ...
 
Elevate Developer Efficiency & build GenAI Application with Amazon Q​
Elevate Developer Efficiency & build GenAI Application with Amazon Q​Elevate Developer Efficiency & build GenAI Application with Amazon Q​
Elevate Developer Efficiency & build GenAI Application with Amazon Q​
 
presentation ICT roal in 21st century education
presentation ICT roal in 21st century educationpresentation ICT roal in 21st century education
presentation ICT roal in 21st century education
 
Apidays New York 2024 - APIs in 2030: The Risk of Technological Sleepwalk by ...
Apidays New York 2024 - APIs in 2030: The Risk of Technological Sleepwalk by ...Apidays New York 2024 - APIs in 2030: The Risk of Technological Sleepwalk by ...
Apidays New York 2024 - APIs in 2030: The Risk of Technological Sleepwalk by ...
 
Cloud Frontiers: A Deep Dive into Serverless Spatial Data and FME
Cloud Frontiers:  A Deep Dive into Serverless Spatial Data and FMECloud Frontiers:  A Deep Dive into Serverless Spatial Data and FME
Cloud Frontiers: A Deep Dive into Serverless Spatial Data and FME
 
Web Form Automation for Bonterra Impact Management (fka Social Solutions Apri...
Web Form Automation for Bonterra Impact Management (fka Social Solutions Apri...Web Form Automation for Bonterra Impact Management (fka Social Solutions Apri...
Web Form Automation for Bonterra Impact Management (fka Social Solutions Apri...
 
DBX First Quarter 2024 Investor Presentation
DBX First Quarter 2024 Investor PresentationDBX First Quarter 2024 Investor Presentation
DBX First Quarter 2024 Investor Presentation
 
Apidays New York 2024 - The Good, the Bad and the Governed by David O'Neill, ...
Apidays New York 2024 - The Good, the Bad and the Governed by David O'Neill, ...Apidays New York 2024 - The Good, the Bad and the Governed by David O'Neill, ...
Apidays New York 2024 - The Good, the Bad and the Governed by David O'Neill, ...
 

CakeFest 2011 - Coupling and cohesion

  • 1. Coupling and Cohesion by: Carl Sutton http://dogmatic69.com
  • 2.
  • 3. Cohesion Before After
  • 4. What is "Cohesion" ● Modules / Classes do related jobs ● Good: High cohesion ● Bad: Low cohesion ● Three levels to look at (in Cake apps) ○ The Method (does one thing properly) ○ The Class (all methods are similar) ○ The Plugin (collectively does *a* single job eg: "cart" plugin does not do mini blog posts)
  • 5. What is "Cohesion" Possible Pros ● Easier to understand ● More robust ● Reliability ● Maintainable Possible Cons ● Difficult to understand ● Not DRY
  • 6. Examples of Cohesion Good: CakePHP's session class - all methods manage one set of data, the sessions (Communicational) Bad: CakePHP's basics.php file - a bunch of utilities, related because they are not related (Coincidental)
  • 7. Levels of "Cohesion" Coincidental cohesion ● Lowest level of cohesion, almost none ● Parts of a module are grouped arbitrarily ● related because they are not related Eg: ● Utility classes / files ● basics.php
  • 8. Levels of "Cohesion" Logical cohesion Parts of a module are grouped because logically they are categorized to do the same thing, even if they are different by nature. eg: ● Putting all your model files in APP/models
  • 9. Levels of "Cohesion" Temporal cohesion ● Grouped by when they are processed ● the parts are processed at a particular time in program execution Eg: ● a function which is called after catching an exception ○ closes open connections ○ creates an error log ○ notifies the user Procedural cohesion ● parts of a module are grouped because they always follow a certain sequence of execution ● Similar to Temporal
  • 10. Levels of "Cohesion" Communicational cohesion ● Parts of a module are grouped because they operate on the same data. Eg: ● SessionComponent + SessionHelper ● Cache engines Bad Model methods:
  • 11. Levels of "Cohesion" Sequential cohesion ● parts of a module are grouped because the output from one part is the input to another part like an assembly line Eg: ● a function which reads data from a file and processes the data. ● Model methods like Find -> beforeFind -> _find -> afterFind -> $output
  • 12. Levels of "Cohesion" Functional cohesion ● The best Type ● parts of a module are grouped because they all contribute to a single well-defined task of the module Eg: ● CakeSocket ○ Does one single job (low level network communication) "Perfection is achieved, not when there is nothing more to add, but when there is nothing left to take away."
  • 13. Checking for low cohesion ● ClassesThatSeemDifficultToName ● Seems like splitting it up would be easy ● Tests are (much) bigger than the class/method itself ● Tests fail in the same way for different reasons ● Code is not DRY Notes ● Rules of premature optimisations apply ● No point having hundreds of one line methods or one method classes ● Sometimes a bit of low cohesion code is needed and/or better than high cohesion (Utility classes)
  • 14. CakePHP 2.0 - higher cohesion ● Auth was broken into two parts ○ AuthComponent ○ Authorisation Adaptor ■ Digest ■ Basic ■ Form ■ Custom ● basic.php removed random functions ● CakeRequest created ○ parts of RequestHandler, Dispacher and Controller ○ request and response objects
  • 17. What is "Coupling" ● Relation between bits of code ● Code A requires Code B to work ● Similar to dependency (inter dependency) ● Changes in Code A ripples changes to Code B ● Less is more ○ Good: ([low][loose][weak]) coupling ○ Bad: ([high][tight][strong]) coupling
  • 18. What is "Coupling" Possible Pros ● Dumb code ● Easier to: ○ read ○ debug ○ test ○ reuse (DRY) ○ maintain ● Cheaper / quicker to extend Possible Cons ● More overhead ● More magic ● Longer dev time / more expensive initially
  • 19. Examples of Coupling Good (loose): CakePHP's ORM (1.x -> ) - use MySQL, MsSQL, PostgreSQL or Custom with the same code CakePHP's JS Engine (1.3.x -> ) - use jQuery, Prototype, Prototype or Custom with the same code CakePHP's Cache (1.x -> ) - File, APC, XCache, Memcache or Custom CakePHP's Sessions (1.x -> ) - use cake (file), PHP, database or cache Bad (tight): CakePHP's test suite (1.x -> ) - hard coded to use Simple Test
  • 20. Levels of "Coupling" Content coupling (high) ● One module modifies / relies on the internal workings of another module. eg: ● Router::* changes ● In 1.3 Helpers (without the analogue code you were stuck) ○ 2.0 can replace helper instances on the fly with another instance ■ $this->Html could be MyCustomHtmlHelper extends HtmlHelper
  • 21. Levels of "Coupling" Common coupling ● Two modules share the same global data. Eg: ● SessionComponent + SessionHelper ○ moving where setFlash() saved messages requires changes to flash()
  • 22. Levels of "Coupling" External coupling ● Two or more modules share an externally imposed data format ○ communication protocol (imap, pop3, ftp, http etc) ○ device interface ○ file format (csv, xml, json etc) Eg: ● EmailComponent ○ RFC 2822 - Internet Message Format ● Database Driver MySQL, MSSQL etc ○ need to use SQL language
  • 23. Levels of "Coupling" Control coupling ● one module controlling the flow of another ● passing it information on what to do Eg: ● Controller starting up a Component
  • 24. Levels of "Coupling" Stamp coupling (Data-structured coupling) ● modules share a composite data structure and use only a part of it eg: ● function foo($options){ return $options['bar'] * 10;} ● validation methods only get the field they are validating (good)
  • 25. Levels of "Coupling" Data coupling ● modules share data through, for example, parameters. ● Each datum is an elementary piece, and these are the only data shared. eg: ● validation methods in a Model class
  • 26. Levels of "Coupling" Message coupling (low) This is the loosest type of coupling. It can be achieved by state decentralization. JS Engine, Cache Engine, ORM etc No coupling ● Modules do not communicate at all with one another. ● Only time there is *no* coupling is when you have a formatted HDD :P Eg: ● EmailComponent is not coupled directly to Models
  • 27. Levels of "Coupling" Message coupling (low) ● This is the loosest type of coupling. ● Achieved by state decentralization. Eg: ● JS Engine, Cache Engine, ORM etc ● you call a main 'engine' class that calls the correct class that you need ● Dependency injection ● Observable
  • 28. Levels of "Coupling" No coupling ● Modules do not communicate at all with one another. ● rm -rf /* will remove all coupling Eg: ● EmailComponent is not coupled directly to Models
  • 29. Checking for high coupling ● Changes to code A requires changes to code B, C etc ● Reuse of code is difficult / impossible ● Testing is super complicated
  • 30. CakePHP 2.0 - lower coupling ● Auth was broken into two parts ○ Authorisation Adaptor - custom authorisation classes ● Dispatcher ○ Parts moved to the Controller so its easy to change / extend (not coupled to the one cake way) ● switch helpers and components on the fly ○ no need to use $this->MyCustomHtmlHelper->foo()
  • 32. Related stuff ● Coupling ● Cohesion ● DRY ● Dependency ● Cyclomatic complexity ● Adapter Pattern ● Dependency_injection ● Observer ● SRP
  • 33. Links dogmatic69 CakePHP Infinitas