SlideShare ist ein Scribd-Unternehmen logo
1 von 28
Magento code testability:
Problems and Solutions
Unit testing

One of the main reasons for unit testing is
improvement of code quality.

Unit tests are indicators that instantly show all the
defects of object oriented code.

If code is hard to test – its quality is questionable.
Code flaws in magento detected by unit tests

•   Fat constructors
•   Method complexity
•   Poor OOD (God objects)
•   Law of Demeter violations
•   Global State and Behavior usage
•   …
Fat constructors

Objects that have a lot of behavior in
constructors are hard to test.

You’ve just created the object and it already
created other objects, made some global calls,
changed some global state, etc.
Fat constructors » Solution

Bad: mock all dependencies, create constructor
tests and test all scenarios of constructor.

Good: Move all behavior from constructors.
Leave only data initialization code.
Method Complexity

Unit tests test behavior scenarios. Unit testing
paradigm requires every scenario covered by
separate test.

Each flow control statement adds scenario to
method, so complex methods with many control
structures and protected calls require a lot of
tests and mocks/stubs.
Method Complexity » Solution

Bad: For protected calls – use reflection or
inheritance to test protected behavior in
isolation. Write test per each scenario.

Good: Extract behavior from complex methods
to separate objects that have small
dependencies and are easily testable.
Substitute conditions with polymorphism.
Poor OOD (God objects)

If an object has too many responsibilities there
is a big chance that it will have internal calls
between its public methods.

This creates problems for testing. Developer
has to mock whole object to stub internal public
calls, otherwise he will have test duplication.
Poor OOD (God objects) » Solution

Bad: Mock tested object and stub internal
public calls.

Good: Extract small objects that will have their
own responsibilities to avoid internal public
calls.
Law of Demeter Violations

When tested object receives some context
object that is used only to gain access to third
service object the Law of Demeter is violated.

To test such code one would have to stub
context object only to return service object. If
the chains of calls are long, testing becomes
problematic.
Law of Demeter Violations » Solution

Bad: Create mocks for context objects that will
return themselves on every call except
predefined stubbed calls.

Good: Refactor code to eliminate context
objects. Depend only on objects that are
required for delivering business goals of objects
under test.
Global State And Behavior

Global mutable state is a reason for most bugs. It
is unreliable for code that uses it.

Global state decreases code testability. Code that
uses global state can not be tested in isolation.
Developer must reproduce global environment of a
unit to test it.

Global behavior is a killer of testability. It can not
be mocked or stubbed for testing.
Global State And Behavior in Magento

•   Global arrays
•   Global variables
•   Global factories
•   Mix (state + behavior)
Global State » Arrays


Mage::registry, Mage::register and
Mage::unregister form an interface of
global dynamic service locator simply
wrapping mutable array with global
behavior that restricts access to array
but makes it harder to emulate in testing
environment
Global State » Objects And Variables

•   Mage::app()
•   Mage::getConfig()
•   Mage::get/setIsdeveloperMode()
•   Mage::getIsDownloader()
Global State » Factories

Global factories localize important part of application
behavior – object creation. They eliminate direct
dependencies in code. Which is good.

But instead of implicitly depending on created objects, code
that uses global factories starts to implicitly depend on
them.

Also global factories cannot be substituted in test
environments.
Global State » Factories » Examples

• Mage::getModel()
• Mage::getResourceModel()
• Mage::getControllerInstance()
Global State » Mix (Behavior + State)

These are dangerous in code and are hard to
substitute in tests:

• Mage::getSingleton()
• Mage::helper()
• Mage::getResourceHelper()
Global Behavior and State » Big deal

The big problem with global state and
behavior in Magento is it’s used everywhere.
All the dependencies of objects are pulled
from global state instead of being pushed
(injected) into these objects.

We cannot simply refactor our code to
eliminate global dependencies. We would
have to rewrite magento.
Global Behavior and State » Solution 1

Build “Magento Unit Testing Framework” on top
of PHPUnit, write testing-environment-special
Mage, make it “mockable” and test our code “in
isolation”.

This is an absolutely viable solution that will let
us unit test our code in isolation avoiding
massive refactoring.
The problem

The problem with this solution is the same as
with bad solutions described in previous
sections: It fights the symptom (code non-
testability), not the disease (global state).

And mutable global state and behavior is the
reason of hard to debug type of bugs and
encourages bad practices.
The problem » Bad practices

•   Liar interfaces
•   Law of Demeter violations
•   Deep code dependencies
•   Liskov substitution principle violations
•   Separation of concerns violations
•   Data envy
•   ….
Global State » Solution

• Declare all object dependencies explicitly as
  entries in constructor argument array, and all
  the method-specific arguments as method’s
  parameters instead of pulling them from global
  state. Use object managers instead of global
  arrays when needed.

It will make our interfaces honest. And most code
smells will become visible by only looking at
method signatures. LSP violations will be noted by
interpreter.
Global Behavior » Solution

• If an object must create other objects then it
  must declare dependency on object
  factory, that will be injected into the object.

It will instantly show objects that create too
much.
Global Behavior » Solution

• If an object must create other objects then it
  must declare dependency on object
  factory, that will be injected into the object.

It will instantly show objects that create too
much.
Global usage of Global » Solution

• All the constructors will check presence of
  dependencies in arguments, if an argument
  is not present – it is taken from Global.

It will let us avoid massive refactorings.
Because developer will only have to refactor
the object he tests – not all the code that uses
it. This can be a stage of transforming magento
code to prepare it for DiC.
Sources

• http://misko.hevery.com/
• http://martinfowler.com/articles/injection.html
• Test-Driven Development by Example. Kent
  Beck
Author




         Anton Kril
         Kyiv Dev Folks team
         akril@ebay.com

Weitere ähnliche Inhalte

Was ist angesagt?

Unit Testing Full@
Unit Testing Full@Unit Testing Full@
Unit Testing Full@
Alex Borsuk
 
Java Unit Test and Coverage Introduction
Java Unit Test and Coverage IntroductionJava Unit Test and Coverage Introduction
Java Unit Test and Coverage Introduction
Alex Su
 

Was ist angesagt? (20)

TDD with Visual Studio 2010
TDD with Visual Studio 2010TDD with Visual Studio 2010
TDD with Visual Studio 2010
 
Unit testing
Unit testing Unit testing
Unit testing
 
Unit Testing
Unit TestingUnit Testing
Unit Testing
 
An Introduction to Unit Testing
An Introduction to Unit TestingAn Introduction to Unit Testing
An Introduction to Unit Testing
 
Unit Testing Full@
Unit Testing Full@Unit Testing Full@
Unit Testing Full@
 
Unit and integration Testing
Unit and integration TestingUnit and integration Testing
Unit and integration Testing
 
Test driven development in .Net - 2010 + Eclipse
Test driven development in .Net - 2010 + EclipseTest driven development in .Net - 2010 + Eclipse
Test driven development in .Net - 2010 + Eclipse
 
Working Effectively with Legacy Code: Lessons in Practice
Working Effectively with Legacy Code: Lessons in PracticeWorking Effectively with Legacy Code: Lessons in Practice
Working Effectively with Legacy Code: Lessons in Practice
 
Unit Testing
Unit TestingUnit Testing
Unit Testing
 
Unit testing legacy code
Unit testing legacy codeUnit testing legacy code
Unit testing legacy code
 
Intro To Unit and integration Testing
Intro To Unit and integration TestingIntro To Unit and integration Testing
Intro To Unit and integration Testing
 
Unit testing - the hard parts
Unit testing - the hard partsUnit testing - the hard parts
Unit testing - the hard parts
 
Java Unit Test and Coverage Introduction
Java Unit Test and Coverage IntroductionJava Unit Test and Coverage Introduction
Java Unit Test and Coverage Introduction
 
Mock driven development using .NET
Mock driven development using .NETMock driven development using .NET
Mock driven development using .NET
 
Unit Testing Android Applications
Unit Testing Android ApplicationsUnit Testing Android Applications
Unit Testing Android Applications
 
Unit Test + Functional Programming = Love
Unit Test + Functional Programming = LoveUnit Test + Functional Programming = Love
Unit Test + Functional Programming = Love
 
Unit Testing Done Right
Unit Testing Done RightUnit Testing Done Right
Unit Testing Done Right
 
How and what to unit test
How and what to unit testHow and what to unit test
How and what to unit test
 
Unit Tests And Automated Testing
Unit Tests And Automated TestingUnit Tests And Automated Testing
Unit Tests And Automated Testing
 
UNIT TESTING
UNIT TESTINGUNIT TESTING
UNIT TESTING
 

Andere mochten auch

Segurtasun informatikoa1
Segurtasun informatikoa1Segurtasun informatikoa1
Segurtasun informatikoa1
Krisba
 
Segurtasun informatikoa1
Segurtasun informatikoa1Segurtasun informatikoa1
Segurtasun informatikoa1
Krisba
 
Data tao sql server consultancy services
Data tao sql server consultancy servicesData tao sql server consultancy services
Data tao sql server consultancy services
DataTao
 
Salim google powerpoint
Salim google powerpointSalim google powerpoint
Salim google powerpoint
sn022600
 
Magento Dependency Injection
Magento Dependency InjectionMagento Dependency Injection
Magento Dependency Injection
Anton Kril
 
2012 05 EuroChem Intro
2012 05 EuroChem Intro2012 05 EuroChem Intro
2012 05 EuroChem Intro
EuroChem
 

Andere mochten auch (16)

Online Localised Content Development (for the African region)
Online Localised Content Development (for the African region)Online Localised Content Development (for the African region)
Online Localised Content Development (for the African region)
 
Культура пачынаецца з цябе вынік
Культура пачынаецца з цябе вынікКультура пачынаецца з цябе вынік
Культура пачынаецца з цябе вынік
 
EuroChem Annual Report 2011
EuroChem Annual Report 2011EuroChem Annual Report 2011
EuroChem Annual Report 2011
 
Segurtasun informatikoa1
Segurtasun informatikoa1Segurtasun informatikoa1
Segurtasun informatikoa1
 
Technical paper on Enhansed fertilizers U+AS and U+S Page 103 116 Sandvik - s...
Technical paper on Enhansed fertilizers U+AS and U+S Page 103 116 Sandvik - s...Technical paper on Enhansed fertilizers U+AS and U+S Page 103 116 Sandvik - s...
Technical paper on Enhansed fertilizers U+AS and U+S Page 103 116 Sandvik - s...
 
Segurtasun informatikoa1
Segurtasun informatikoa1Segurtasun informatikoa1
Segurtasun informatikoa1
 
U+AS and U+S Sulphur enhansed fertilizers in Nitrogen
U+AS and U+S Sulphur enhansed fertilizers in Nitrogen U+AS and U+S Sulphur enhansed fertilizers in Nitrogen
U+AS and U+S Sulphur enhansed fertilizers in Nitrogen
 
Data tao sql server consultancy services
Data tao sql server consultancy servicesData tao sql server consultancy services
Data tao sql server consultancy services
 
Salim google powerpoint
Salim google powerpointSalim google powerpoint
Salim google powerpoint
 
Nitrogen syngas 2011
Nitrogen syngas 2011Nitrogen syngas 2011
Nitrogen syngas 2011
 
Program finantat de perfectionare a cadrelor didactice de religie
Program finantat de perfectionare a cadrelor didactice de religieProgram finantat de perfectionare a cadrelor didactice de religie
Program finantat de perfectionare a cadrelor didactice de religie
 
Recreational noise exposure and its effects on adolescents
Recreational noise exposure and its effects on adolescentsRecreational noise exposure and its effects on adolescents
Recreational noise exposure and its effects on adolescents
 
Magento Dependency Injection
Magento Dependency InjectionMagento Dependency Injection
Magento Dependency Injection
 
Neurosciences of spiritual life. Some results regarding the effect of meditat...
Neurosciences of spiritual life. Some results regarding the effect of meditat...Neurosciences of spiritual life. Some results regarding the effect of meditat...
Neurosciences of spiritual life. Some results regarding the effect of meditat...
 
2012 05 EuroChem Intro
2012 05 EuroChem Intro2012 05 EuroChem Intro
2012 05 EuroChem Intro
 
культура пачынаецца з цябе
культура пачынаецца з цябекультура пачынаецца з цябе
культура пачынаецца з цябе
 

Ähnlich wie Magento code testability: Problems and Solutions

Mock Objects, Design and Dependency Inversion Principle
Mock Objects, Design and Dependency Inversion PrincipleMock Objects, Design and Dependency Inversion Principle
Mock Objects, Design and Dependency Inversion Principle
P Heinonen
 
谷歌 Scott-lessons learned in testability
谷歌 Scott-lessons learned in testability谷歌 Scott-lessons learned in testability
谷歌 Scott-lessons learned in testability
drewz lin
 

Ähnlich wie Magento code testability: Problems and Solutions (20)

Agile principles and practices
Agile principles and practicesAgile principles and practices
Agile principles and practices
 
MongoDB World 2018: Tutorial - MongoDB Meets Chaos Monkey
MongoDB World 2018: Tutorial - MongoDB Meets Chaos MonkeyMongoDB World 2018: Tutorial - MongoDB Meets Chaos Monkey
MongoDB World 2018: Tutorial - MongoDB Meets Chaos Monkey
 
Unit testing basic
Unit testing basicUnit testing basic
Unit testing basic
 
Play with Testing on Android - Gilang Ramadhan (Academy Content Writer at Dic...
Play with Testing on Android - Gilang Ramadhan (Academy Content Writer at Dic...Play with Testing on Android - Gilang Ramadhan (Academy Content Writer at Dic...
Play with Testing on Android - Gilang Ramadhan (Academy Content Writer at Dic...
 
Unit testing and mocking in Python - PyCon 2018 - Kenya
Unit testing and mocking in Python - PyCon 2018 - KenyaUnit testing and mocking in Python - PyCon 2018 - Kenya
Unit testing and mocking in Python - PyCon 2018 - Kenya
 
Microsoft Fakes, Unit Testing the (almost) Untestable Code
Microsoft Fakes, Unit Testing the (almost) Untestable CodeMicrosoft Fakes, Unit Testing the (almost) Untestable Code
Microsoft Fakes, Unit Testing the (almost) Untestable Code
 
Unit Tests with Microsoft Fakes
Unit Tests with Microsoft FakesUnit Tests with Microsoft Fakes
Unit Tests with Microsoft Fakes
 
[AnDevCon 2016] Mutation Testing for Android
[AnDevCon 2016] Mutation Testing for Android[AnDevCon 2016] Mutation Testing for Android
[AnDevCon 2016] Mutation Testing for Android
 
Test driven development
Test driven developmentTest driven development
Test driven development
 
Unit testing - An introduction
Unit testing - An introductionUnit testing - An introduction
Unit testing - An introduction
 
Testing the Untestable
Testing the UntestableTesting the Untestable
Testing the Untestable
 
A minimal Django testing styleguide
A minimal Django testing styleguideA minimal Django testing styleguide
A minimal Django testing styleguide
 
Battle of The Mocking Frameworks
Battle of The Mocking FrameworksBattle of The Mocking Frameworks
Battle of The Mocking Frameworks
 
Mockito 2.x Migration - Droidcon UK 2018
Mockito 2.x Migration - Droidcon UK 2018Mockito 2.x Migration - Droidcon UK 2018
Mockito 2.x Migration - Droidcon UK 2018
 
Mock Objects, Design and Dependency Inversion Principle
Mock Objects, Design and Dependency Inversion PrincipleMock Objects, Design and Dependency Inversion Principle
Mock Objects, Design and Dependency Inversion Principle
 
Unit Testing in Swift
Unit Testing in SwiftUnit Testing in Swift
Unit Testing in Swift
 
Testing Angular
Testing AngularTesting Angular
Testing Angular
 
A la découverte des google/mock (aka gmock)
A la découverte des google/mock (aka gmock)A la découverte des google/mock (aka gmock)
A la découverte des google/mock (aka gmock)
 
谷歌 Scott-lessons learned in testability
谷歌 Scott-lessons learned in testability谷歌 Scott-lessons learned in testability
谷歌 Scott-lessons learned in testability
 
Building React Applications with Redux
Building React Applications with ReduxBuilding React Applications with Redux
Building React Applications with Redux
 

Kürzlich hochgeladen

Finding Java's Hidden Performance Traps @ DevoxxUK 2024
Finding Java's Hidden Performance Traps @ DevoxxUK 2024Finding Java's Hidden Performance Traps @ DevoxxUK 2024
Finding Java's Hidden Performance Traps @ DevoxxUK 2024
Victor Rentea
 

Kürzlich hochgeladen (20)

Introduction to Multilingual Retrieval Augmented Generation (RAG)
Introduction to Multilingual Retrieval Augmented Generation (RAG)Introduction to Multilingual Retrieval Augmented Generation (RAG)
Introduction to Multilingual Retrieval Augmented Generation (RAG)
 
[BuildWithAI] Introduction to Gemini.pdf
[BuildWithAI] Introduction to Gemini.pdf[BuildWithAI] Introduction to Gemini.pdf
[BuildWithAI] Introduction to Gemini.pdf
 
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​
 
CNIC Information System with Pakdata Cf In Pakistan
CNIC Information System with Pakdata Cf In PakistanCNIC Information System with Pakdata Cf In Pakistan
CNIC Information System with Pakdata Cf In Pakistan
 
WSO2's API Vision: Unifying Control, Empowering Developers
WSO2's API Vision: Unifying Control, Empowering DevelopersWSO2's API Vision: Unifying Control, Empowering Developers
WSO2's API Vision: Unifying Control, Empowering Developers
 
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
 
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 ...
 
Apidays New York 2024 - Scaling API-first by Ian Reasor and Radu Cotescu, Adobe
Apidays New York 2024 - Scaling API-first by Ian Reasor and Radu Cotescu, AdobeApidays New York 2024 - Scaling API-first by Ian Reasor and Radu Cotescu, Adobe
Apidays New York 2024 - Scaling API-first by Ian Reasor and Radu Cotescu, Adobe
 
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...
 
Platformless Horizons for Digital Adaptability
Platformless Horizons for Digital AdaptabilityPlatformless Horizons for Digital Adaptability
Platformless Horizons for Digital Adaptability
 
Finding Java's Hidden Performance Traps @ DevoxxUK 2024
Finding Java's Hidden Performance Traps @ DevoxxUK 2024Finding Java's Hidden Performance Traps @ DevoxxUK 2024
Finding Java's Hidden Performance Traps @ DevoxxUK 2024
 
Artificial Intelligence Chap.5 : Uncertainty
Artificial Intelligence Chap.5 : UncertaintyArtificial Intelligence Chap.5 : Uncertainty
Artificial Intelligence Chap.5 : Uncertainty
 
MINDCTI Revenue Release Quarter One 2024
MINDCTI Revenue Release Quarter One 2024MINDCTI Revenue Release Quarter One 2024
MINDCTI Revenue Release Quarter One 2024
 
Rising Above_ Dubai Floods and the Fortitude of Dubai International Airport.pdf
Rising Above_ Dubai Floods and the Fortitude of Dubai International Airport.pdfRising Above_ Dubai Floods and the Fortitude of Dubai International Airport.pdf
Rising Above_ Dubai Floods and the Fortitude of Dubai International Airport.pdf
 
FWD Group - Insurer Innovation Award 2024
FWD Group - Insurer Innovation Award 2024FWD Group - Insurer Innovation Award 2024
FWD Group - Insurer Innovation Award 2024
 
Navigating the Deluge_ Dubai Floods and the Resilience of Dubai International...
Navigating the Deluge_ Dubai Floods and the Resilience of Dubai International...Navigating the Deluge_ Dubai Floods and the Resilience of Dubai International...
Navigating the Deluge_ Dubai Floods and the Resilience of Dubai International...
 
Polkadot JAM Slides - Token2049 - By Dr. Gavin Wood
Polkadot JAM Slides - Token2049 - By Dr. Gavin WoodPolkadot JAM Slides - Token2049 - By Dr. Gavin Wood
Polkadot JAM Slides - Token2049 - By Dr. Gavin Wood
 
Mcleodganj Call Girls 🥰 8617370543 Service Offer VIP Hot Model
Mcleodganj Call Girls 🥰 8617370543 Service Offer VIP Hot ModelMcleodganj Call Girls 🥰 8617370543 Service Offer VIP Hot Model
Mcleodganj Call Girls 🥰 8617370543 Service Offer VIP Hot Model
 
Vector Search -An Introduction in Oracle Database 23ai.pptx
Vector Search -An Introduction in Oracle Database 23ai.pptxVector Search -An Introduction in Oracle Database 23ai.pptx
Vector Search -An Introduction in Oracle Database 23ai.pptx
 
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
 

Magento code testability: Problems and Solutions

  • 2. Unit testing One of the main reasons for unit testing is improvement of code quality. Unit tests are indicators that instantly show all the defects of object oriented code. If code is hard to test – its quality is questionable.
  • 3. Code flaws in magento detected by unit tests • Fat constructors • Method complexity • Poor OOD (God objects) • Law of Demeter violations • Global State and Behavior usage • …
  • 4. Fat constructors Objects that have a lot of behavior in constructors are hard to test. You’ve just created the object and it already created other objects, made some global calls, changed some global state, etc.
  • 5. Fat constructors » Solution Bad: mock all dependencies, create constructor tests and test all scenarios of constructor. Good: Move all behavior from constructors. Leave only data initialization code.
  • 6. Method Complexity Unit tests test behavior scenarios. Unit testing paradigm requires every scenario covered by separate test. Each flow control statement adds scenario to method, so complex methods with many control structures and protected calls require a lot of tests and mocks/stubs.
  • 7. Method Complexity » Solution Bad: For protected calls – use reflection or inheritance to test protected behavior in isolation. Write test per each scenario. Good: Extract behavior from complex methods to separate objects that have small dependencies and are easily testable. Substitute conditions with polymorphism.
  • 8. Poor OOD (God objects) If an object has too many responsibilities there is a big chance that it will have internal calls between its public methods. This creates problems for testing. Developer has to mock whole object to stub internal public calls, otherwise he will have test duplication.
  • 9. Poor OOD (God objects) » Solution Bad: Mock tested object and stub internal public calls. Good: Extract small objects that will have their own responsibilities to avoid internal public calls.
  • 10. Law of Demeter Violations When tested object receives some context object that is used only to gain access to third service object the Law of Demeter is violated. To test such code one would have to stub context object only to return service object. If the chains of calls are long, testing becomes problematic.
  • 11. Law of Demeter Violations » Solution Bad: Create mocks for context objects that will return themselves on every call except predefined stubbed calls. Good: Refactor code to eliminate context objects. Depend only on objects that are required for delivering business goals of objects under test.
  • 12. Global State And Behavior Global mutable state is a reason for most bugs. It is unreliable for code that uses it. Global state decreases code testability. Code that uses global state can not be tested in isolation. Developer must reproduce global environment of a unit to test it. Global behavior is a killer of testability. It can not be mocked or stubbed for testing.
  • 13. Global State And Behavior in Magento • Global arrays • Global variables • Global factories • Mix (state + behavior)
  • 14. Global State » Arrays Mage::registry, Mage::register and Mage::unregister form an interface of global dynamic service locator simply wrapping mutable array with global behavior that restricts access to array but makes it harder to emulate in testing environment
  • 15. Global State » Objects And Variables • Mage::app() • Mage::getConfig() • Mage::get/setIsdeveloperMode() • Mage::getIsDownloader()
  • 16. Global State » Factories Global factories localize important part of application behavior – object creation. They eliminate direct dependencies in code. Which is good. But instead of implicitly depending on created objects, code that uses global factories starts to implicitly depend on them. Also global factories cannot be substituted in test environments.
  • 17. Global State » Factories » Examples • Mage::getModel() • Mage::getResourceModel() • Mage::getControllerInstance()
  • 18. Global State » Mix (Behavior + State) These are dangerous in code and are hard to substitute in tests: • Mage::getSingleton() • Mage::helper() • Mage::getResourceHelper()
  • 19. Global Behavior and State » Big deal The big problem with global state and behavior in Magento is it’s used everywhere. All the dependencies of objects are pulled from global state instead of being pushed (injected) into these objects. We cannot simply refactor our code to eliminate global dependencies. We would have to rewrite magento.
  • 20. Global Behavior and State » Solution 1 Build “Magento Unit Testing Framework” on top of PHPUnit, write testing-environment-special Mage, make it “mockable” and test our code “in isolation”. This is an absolutely viable solution that will let us unit test our code in isolation avoiding massive refactoring.
  • 21. The problem The problem with this solution is the same as with bad solutions described in previous sections: It fights the symptom (code non- testability), not the disease (global state). And mutable global state and behavior is the reason of hard to debug type of bugs and encourages bad practices.
  • 22. The problem » Bad practices • Liar interfaces • Law of Demeter violations • Deep code dependencies • Liskov substitution principle violations • Separation of concerns violations • Data envy • ….
  • 23. Global State » Solution • Declare all object dependencies explicitly as entries in constructor argument array, and all the method-specific arguments as method’s parameters instead of pulling them from global state. Use object managers instead of global arrays when needed. It will make our interfaces honest. And most code smells will become visible by only looking at method signatures. LSP violations will be noted by interpreter.
  • 24. Global Behavior » Solution • If an object must create other objects then it must declare dependency on object factory, that will be injected into the object. It will instantly show objects that create too much.
  • 25. Global Behavior » Solution • If an object must create other objects then it must declare dependency on object factory, that will be injected into the object. It will instantly show objects that create too much.
  • 26. Global usage of Global » Solution • All the constructors will check presence of dependencies in arguments, if an argument is not present – it is taken from Global. It will let us avoid massive refactorings. Because developer will only have to refactor the object he tests – not all the code that uses it. This can be a stage of transforming magento code to prepare it for DiC.
  • 28. Author Anton Kril Kyiv Dev Folks team akril@ebay.com