SlideShare a Scribd company logo
1 of 71
Download to read offline
OBJECTS, TESTING, AND
RESPONSIBILITY
MATTHEW MACHUGA
LARACON EU AUGUST 2013
HI, I'M MATT MACHUGA!
SOFTWARE DEVELOPER
RUBY | JS | PHP
ONLINE: MACHUGA
IRC: machuga
GitHub: machuga
Twitter: @machuga
I WEAR MANY HATS IN IRC
"Have you checked the docs first?"
MORE MACHUGA'S
HALI AND VAEDA
VIM
THINK THROUGH LEARNING
THINK THROUGH MATH
HELP KIDS LEARN MATH
SENIOR SOFTWARE DEVELOPER
I HAVE THE BEST COWORKERS EVER!
BEFORE WE BEGIN...
LARAVEL COMMUNITY!THANK YOU, YOU'RE ALL AMAZING!
OBJECTS, TESTING, AND
RESPONSIBILITYWAT
OBJECTS
Object Oriented Programming
Object Oriented Design
Pro's and Con's
Improvements to code
TESTING
Correlation between good OOD and good tests
Tests are good
No, seriously. Tests are good. Stop hating.
RESPONSIBILITY
See also: Accountability
Holding components accountable
Giving objects explicit responsibilities
1:1 Object:Responsibility Ratio (when possible)
Responsibilty to code
Responsibilty to team
Responsibilty to your future self
OBJECTS
Alan Kay
Father of OOP
"I thought of objects being like biological cells
and/or individual computers on a network,
only able to communicate with messages"
OBJECT-ORIENTED PROGRAMMING
Originated from Functional and Procedural
Solution to code organization, data-hiding, reuse
Solution to easier testing
Solution to structure and protocols
PHP'S OOP HISTORY
QUESTION
Which version of PHP first gained objects?
PHP 3
OOP: OBJECT ORIENTED PHP
THE LIVE ACTION SERIES
OOP: OBJECT ORIENTED PHP
16 years and 4 days ago: PHP codebase gets classes
PHP 3 released in 1998
Associative Array ++
OOP: OBJECT ORIENTED PHP
PHP 3 & 4 CAPABILITIES
Classes
Objects
Simple single inheritance
Pass-by-value
All public visibility
OOP: OBJECT ORIENTED PHP
PHP 5.0 - 5.2.X ENHANCEMENTS
Pass-by-reference
public/ private/ protectedvisibility
Static methods/properties
Class constants
__construct()
Destructors
Abstract and Final classes
Interfaces
OOP: OBJECT ORIENTED PHP
PHP 5.3 ENHANCEMENTS
Usable single inheritance!
Late Static Binding
Namespaces
Closures
OOP: OBJECT ORIENTED PHP
PHP 5.3 ANTIPATTERNS
goto
No full namespace import
OOP: OBJECT ORIENTED PHP
PHP 5.4 ENHANCEMENTS
Traits
Closure Rebinding
IT TOOK ABOUT 14 YEARS
But we now have a very capable object model in PHP
THE FOUR PILLARS OF
OOP
ABSTRACTION
Remove and isolate related behavior or data
Responsibility
EXAMPLES
PROCEDURAL
<?php
function get_db() { /* return the db conneciton */}
function user_show($user) { /* Awesome procedural code */ }
function user_fetch($user) { $db = get_db(); /* Awesome procedural code */
function user_delete($user) { $db = get_db(); /* Awesome procedural code */
function user_create($user, $data) { $db = get_db(); /* Awesome procedural co
function user_update($user, $data) { $db = get_db(); /* Awesome procedural co
function user_store_data($user, $user_data)
{
if (user_fetch($user)) {
return user_update($user, $user_data);
} else {
return user_create($user, $user_data);
}
ABSTRACTED
<php
class User extends Eloquent
{
// All provided by Eloquent
public static function find($id) {}
public function delete() {}
public function create($attributes) {}
public function update($attributes) {}
public function save() {}
}
ENCAPSULATION
Keep data and behavior in a black box
Use a public interface to interact with the black box
Much like a function - data in, data out
Prevents leaky abstractions
EXAMPLE...KIND OF
ILLUMINATEDATABASEELOQUENTMODEL
PROPERTIES
4 Public Instance/Class
19 Protected Instance/Class
0 Private Instance/Class
METHODS
126 Public Instance/Class
25 Protected Instance/Class
0 Private Instance/Class
INHERITANCE
The double edged sword
Allows classes to be extended from other classes
Properties and methods can ascend the ancestry
Saves a lot of code
EXAMPLE - PLAIN CLASSES
<?php
class Rectangle
{
public function __construct($coords) {}
public function getCoordinates() {}
public function setCoordinates($coords) {}
public function getXX() {}
public function getXY() {}
public function getYX() {}
public function getYY() {}
public function setXX($coord) {}
public function setXY($coord) {}
public function setYX($coord) {}
public function setYY($coord) {}
EXAMPLE - INHERITED
<?php
class Square extends Rectangle {}
class Diamond extends Rectangle {}
class Rectangle
{
public function __construct($coords) {}
public function getCoordinates() {}
public function setCoordinates($coords) {}
public function getXX() {}
public function getXY() {}
public function getYX() {}
public function getYY() {}
public function setXX($coord) {}
POLYMORPHISM
Probably the best feature of OOP
Any object may be used if it implements expected
method/property
Allows code branching without if/else logic
PHP is a duck typed language - "If it walks like a duck"
PHP also allows type hinting - "You will be a duck and you
will like it!"
EXAMPLE
<php
class BlogPostWidget
{
public function render() {}
}
class GalleryWidget
{
public function render() {}
}
class PollWidget
{
public function render() {}
}
EXAMPLE W/ TYPE HINTING
<php
interface Widget
{
public function render() {}
}
class BlogPostWidget implements Widget
{
public function render() {}
}
class GalleryWidget implements Widget
{
public function render() {}
}
class PollWidget implements Widget
HOW IS THIS USABLE?
Phill Sparks and Fabien showed you yesterday!
Pay attention!
DESIGN PATTERNS
Finding common patterns in code and making it reusable
Take advantage of OO constructs
CODE REUSE AND EXTENSIBILITY
Proper abstraction leads to reusable code
Fluent Class in Laravel 3 as an example (not the DB one)
Validators in Laravel
Drivers
LATE-STATIC BINDING
selfnever worked like it should've
staticis what selfwanted to be
selfwill call the class the method was defined on, not the
subclass you likely expecting
statichowever will
EXAMPLE
<php
class A
{
public function sadface()
{
return new self();
}
public function happyface()
{
return new static();
}
}
class B extends A {}
$b = new B();
$b->sadface(); // A object
TRAITS
Traits allow for methods/properties to be added to a class
at compile-time
Not quite mixins, but close
In a sense, allows for multiple inheritance
This scares people
Not always the right solution, but often suited
Another great form of reusable abstraction
EXAMPLE
<php
trait Bar
{
protected $baz;
public function baz()
{
return $this->baz;
}
}
class Foo
{
use Bar;
public function setBaz($baz)
{
GET THE MOST OUT OF YOUR OBJECTS
TELL, DON'T ASK
Tell your objects what you want them to do
Don't ask them data about themselves. Remember: Black box
COMPOSITION OVER INHERITANCE
Composing two or more objects together
The sum is greater than the parts
Provides more flexibility
Not always the right solution, but often the better suited
More code to compose (usually)
"Does X belong on this object?"
COMPOSITION WITH TRAITS
SOME PEOPLE REALLY HATE TRAITS
Traits allow for methods/properties to be added to a class
at compile-time
Not quite mixins, but close
In a sense, allows for multiple inheritance
This scares people
Not always the right solution, but often the better suited
Another great form of reusable abstraction
TESTING
TESTING CAN BE HARD
ESPECIALLY IF YOU'RE MAKING IT HARD
TDD SERVES MANY PURPOSES
Guiding you to make well abstracted solutions
Help you write the least code possible
Ensure your code works
Ensure your code works as it is intended
Ensure tests become executable documentation for your
code and acceptance criteria
TDD CYCLE
Red
Green
Refactor
FULL TDD CYCLE
Red
Red
Green
Refactor
Green
Refactor
BASE TESTS OFF ACCEPTANCE CRITERIA
Stakeholders want their features
You want the features to work
You want to guarantee your unit tests come together
TDD IS NOT THE ONLY WAY
Tests don't need to drive or guide your code
Testing after is perfectly reasonable
BUT ALWAYS LISTEN TO YOUR TESTS
LISTENING TO TESTS
Tests will let you know if somethign smells funny
A class that does too many things is hard to test
A test with too many dependencies is hard to test
A test with too many mocks is hard to mantain
A test that is too difficult is easy to abandon
DON'T BE AFRAID TO ADD MORE
OBJECTS/CLASSES
EXAMPLE - AUTHORITY
<php
protected $dispatcher;
public function __construct($currentUser, $dispatcher = null)
{
$this->rules = new RuleRepository;
$this->setDispatcher($dispatcher);
$this->setCurrentUser($currentUser);
$this->dispatch('authority.initialized', array(
'user' => $this->getCurrentUser(),
));
}
public function dispatch($eventName, $payload = array())
{
if ($this->dispatcher) {
return $this->dispatcher->fire($eventName, $payload);
EXAMPLE - AUTHORITY TESTS
<php
public function testInitializeEvent()
{
$test = new stdClass;
$user = new stdClass;
$user->name = 'Tester';
$this->dispatcher->listen('authority.initialized', function($payload
$test->user = $payload->user;
$test->timestamp = $payload->timestamp;
});
$authority = new Authority($user, $this->dispatcher);
$this->assertSame($test->user, $user);
$this->assertInstanceOf('DateTime', $test->timestamp);
}
SOME THINGS ON TESTING
You do not need a test for every method
Sometimes you need more than one test for a method
Mocking can fall short and lose sync.
If you don't test everything, test areas of high churn
Do not reach for AspectMock right away because
something is hard
Test your own code, not third party
SOME MORE THINGS ON TESTING
This is not a good test
<php
testFoo()
{
$foo = new Foo();
$bar = new Bar();
$baz = $foo->doSomethingEpic($bar);
if (is_array($baz) and !is_empty($baz)) {
$this->assertTrue(true);
} else {
$this->assertFalse(true);
}
}
SOME MORE THINGS ON TESTING
Nor this
<php
testSomething()
{
$foo = new Foo();
$bar = new Bar();
$baz = $foo->doSomethingEpic($bar);
// Baz doesn't seem to eval right, passing for now
// @TODO: Come back later
$this->assertTrue(true);
}
SOME MORE THINGS ON TESTING
Nor this
<php
testStringReverse()
{
$str = new AwesomeString();
$string = 'Hello';
// Implementation: return strrev($string)
$reversed = $str->reverseString($string);
$this->assertEquals(strrev($string), $reversed);
}
SOME MORE THINGS ON TESTING
Nor this...I don't even...
<php
testWeirdFeature()
{
// 2 + 2 should be 4
if (2+2 == 3) {
$this->assertTrue(true);
} else {
$this->assertTrue(false);
}
}
CAN IT BE CLEANED UP?
ABSOLUTELY! BUT IT WORKS!
RESPONSIBILITY
RESPONSIBILITY
You have a responsibility not to make tests like what I've just
shown
RESPONSIBILITY: OBJECTS
Give your objects a task
Do not overwork your objects
Give your objects some proper tests
Like profiling and logging, objects can help with
accountability
RESPONSIBILITY: YOU
You have a responsibility to yourself
You have a responsibility to your team
You have a responsibility to your consumers
You have a responsibility to your future self
Become responsible and be accountable for your code
QUESTIONS?
THANK YOU!
IRC: machuga
GitHub: machuga
Twitter: @machuga

More Related Content

What's hot

Perl Teach-In (part 2)
Perl Teach-In (part 2)Perl Teach-In (part 2)
Perl Teach-In (part 2)Dave Cross
 
Class 7 - PHP Object Oriented Programming
Class 7 - PHP Object Oriented ProgrammingClass 7 - PHP Object Oriented Programming
Class 7 - PHP Object Oriented ProgrammingAhmed Swilam
 
Intermediate OOP in PHP
Intermediate OOP in PHPIntermediate OOP in PHP
Intermediate OOP in PHPDavid Stockton
 
Oops in PHP By Nyros Developer
Oops in PHP By Nyros DeveloperOops in PHP By Nyros Developer
Oops in PHP By Nyros DeveloperNyros Technologies
 
JavaScript - From Birth To Closure
JavaScript - From Birth To ClosureJavaScript - From Birth To Closure
JavaScript - From Birth To ClosureRobert Nyman
 
Building Testable PHP Applications
Building Testable PHP ApplicationsBuilding Testable PHP Applications
Building Testable PHP Applicationschartjes
 
Object oreinted php | OOPs
Object oreinted php | OOPsObject oreinted php | OOPs
Object oreinted php | OOPsRavi Bhadauria
 
09 Object Oriented Programming in PHP #burningkeyboards
09 Object Oriented Programming in PHP #burningkeyboards09 Object Oriented Programming in PHP #burningkeyboards
09 Object Oriented Programming in PHP #burningkeyboardsDenis Ristic
 
Introduction to OOP with PHP
Introduction to OOP with PHPIntroduction to OOP with PHP
Introduction to OOP with PHPMichael Peacock
 
Secrets of JavaScript Libraries
Secrets of JavaScript LibrariesSecrets of JavaScript Libraries
Secrets of JavaScript Librariesjeresig
 
Creating and Maintaining WordPress Plugins
Creating and Maintaining WordPress PluginsCreating and Maintaining WordPress Plugins
Creating and Maintaining WordPress PluginsMark Jaquith
 
Scalable JavaScript Design Patterns
Scalable JavaScript Design PatternsScalable JavaScript Design Patterns
Scalable JavaScript Design PatternsAddy Osmani
 
Object oriented programming in php 5
Object oriented programming in php 5Object oriented programming in php 5
Object oriented programming in php 5Sayed Ahmed
 
oop_in_php_tutorial_for_killerphp.com
oop_in_php_tutorial_for_killerphp.comoop_in_php_tutorial_for_killerphp.com
oop_in_php_tutorial_for_killerphp.comtutorialsruby
 

What's hot (19)

Perl Teach-In (part 2)
Perl Teach-In (part 2)Perl Teach-In (part 2)
Perl Teach-In (part 2)
 
Php Oop
Php OopPhp Oop
Php Oop
 
OOP in PHP
OOP in PHPOOP in PHP
OOP in PHP
 
Class 7 - PHP Object Oriented Programming
Class 7 - PHP Object Oriented ProgrammingClass 7 - PHP Object Oriented Programming
Class 7 - PHP Object Oriented Programming
 
PHP Classes and OOPS Concept
PHP Classes and OOPS ConceptPHP Classes and OOPS Concept
PHP Classes and OOPS Concept
 
Intermediate OOP in PHP
Intermediate OOP in PHPIntermediate OOP in PHP
Intermediate OOP in PHP
 
Oops in php
Oops in phpOops in php
Oops in php
 
PHP- Introduction to Object Oriented PHP
PHP-  Introduction to Object Oriented PHPPHP-  Introduction to Object Oriented PHP
PHP- Introduction to Object Oriented PHP
 
Oops in PHP By Nyros Developer
Oops in PHP By Nyros DeveloperOops in PHP By Nyros Developer
Oops in PHP By Nyros Developer
 
JavaScript - From Birth To Closure
JavaScript - From Birth To ClosureJavaScript - From Birth To Closure
JavaScript - From Birth To Closure
 
Building Testable PHP Applications
Building Testable PHP ApplicationsBuilding Testable PHP Applications
Building Testable PHP Applications
 
Object oreinted php | OOPs
Object oreinted php | OOPsObject oreinted php | OOPs
Object oreinted php | OOPs
 
09 Object Oriented Programming in PHP #burningkeyboards
09 Object Oriented Programming in PHP #burningkeyboards09 Object Oriented Programming in PHP #burningkeyboards
09 Object Oriented Programming in PHP #burningkeyboards
 
Introduction to OOP with PHP
Introduction to OOP with PHPIntroduction to OOP with PHP
Introduction to OOP with PHP
 
Secrets of JavaScript Libraries
Secrets of JavaScript LibrariesSecrets of JavaScript Libraries
Secrets of JavaScript Libraries
 
Creating and Maintaining WordPress Plugins
Creating and Maintaining WordPress PluginsCreating and Maintaining WordPress Plugins
Creating and Maintaining WordPress Plugins
 
Scalable JavaScript Design Patterns
Scalable JavaScript Design PatternsScalable JavaScript Design Patterns
Scalable JavaScript Design Patterns
 
Object oriented programming in php 5
Object oriented programming in php 5Object oriented programming in php 5
Object oriented programming in php 5
 
oop_in_php_tutorial_for_killerphp.com
oop_in_php_tutorial_for_killerphp.comoop_in_php_tutorial_for_killerphp.com
oop_in_php_tutorial_for_killerphp.com
 

Viewers also liked

Siva knjiga 8 - preporuke za smanjenje birokratije u Srbiji
Siva knjiga 8 - preporuke za smanjenje birokratije u SrbijiSiva knjiga 8 - preporuke za smanjenje birokratije u Srbiji
Siva knjiga 8 - preporuke za smanjenje birokratije u SrbijiNALED Serbia
 
Izvestaj zaI kvartal 2013 - status regulatorne reforme
Izvestaj zaI kvartal 2013  -   status regulatorne reformeIzvestaj zaI kvartal 2013  -   status regulatorne reforme
Izvestaj zaI kvartal 2013 - status regulatorne reformeNALED Serbia
 
Let’s do it toul kork talk
Let’s do it toul kork talkLet’s do it toul kork talk
Let’s do it toul kork talkKhmerTalks
 
Najbolji JPP projekti: OIE, reciklaža, turizam - Raška, Nova Varoš, Zrenjanin
Najbolji JPP projekti: OIE, reciklaža, turizam - Raška, Nova Varoš, ZrenjaninNajbolji JPP projekti: OIE, reciklaža, turizam - Raška, Nova Varoš, Zrenjanin
Najbolji JPP projekti: OIE, reciklaža, turizam - Raška, Nova Varoš, ZrenjaninNALED Serbia
 
M tsuchiya+utokyo+2013 2-1
M tsuchiya+utokyo+2013 2-1M tsuchiya+utokyo+2013 2-1
M tsuchiya+utokyo+2013 2-1masaru168
 
Berrett-Koehler Social Networking Best Practices
Berrett-Koehler Social Networking Best PracticesBerrett-Koehler Social Networking Best Practices
Berrett-Koehler Social Networking Best PracticesBerrett-Koehler Publishers
 
KhmerTalks: Find your passion
KhmerTalks: Find your passionKhmerTalks: Find your passion
KhmerTalks: Find your passionKhmerTalks
 
Majei Iana-Ukraine
Majei Iana-UkraineMajei Iana-Ukraine
Majei Iana-UkraineIana Majei
 
KhmerTalks: Essential of e learning-last
KhmerTalks: Essential of e learning-lastKhmerTalks: Essential of e learning-last
KhmerTalks: Essential of e learning-lastKhmerTalks
 
Rezultati NALED-a 2014.
Rezultati NALED-a 2014.Rezultati NALED-a 2014.
Rezultati NALED-a 2014.NALED Serbia
 
National program for countering shadow economy in Serbia
National program for countering shadow economy in SerbiaNational program for countering shadow economy in Serbia
National program for countering shadow economy in SerbiaNALED Serbia
 
Charles dickens
Charles dickensCharles dickens
Charles dickensIana Majei
 
Stop Wasting Money on SEM: Know Your Customer to Know your User
Stop Wasting Money on SEM: Know Your Customer to Know your UserStop Wasting Money on SEM: Know Your Customer to Know your User
Stop Wasting Money on SEM: Know Your Customer to Know your Usersheila_musonza
 
Stavovi privrede o regulatornom okruženju i sivoj ekonomiji, april 2015.
Stavovi privrede o regulatornom okruženju i sivoj ekonomiji, april 2015.Stavovi privrede o regulatornom okruženju i sivoj ekonomiji, april 2015.
Stavovi privrede o regulatornom okruženju i sivoj ekonomiji, april 2015.NALED Serbia
 
Why Are Affiliate Sales Recommended For Newbies?
Why Are Affiliate Sales Recommended For Newbies?Why Are Affiliate Sales Recommended For Newbies?
Why Are Affiliate Sales Recommended For Newbies?sheila_musonza
 
Zrenjaninska Siva knjiga propisa 2013
Zrenjaninska Siva knjiga propisa   2013Zrenjaninska Siva knjiga propisa   2013
Zrenjaninska Siva knjiga propisa 2013NALED Serbia
 
Steve Piersanti of Berrett-Koehler Publishers - Keynote Address at PubWest Co...
Steve Piersanti of Berrett-Koehler Publishers - Keynote Address at PubWest Co...Steve Piersanti of Berrett-Koehler Publishers - Keynote Address at PubWest Co...
Steve Piersanti of Berrett-Koehler Publishers - Keynote Address at PubWest Co...Berrett-Koehler Publishers
 
2012 03-17エッヂランク
2012 03-17エッヂランク2012 03-17エッヂランク
2012 03-17エッヂランク康孝 鈴木
 

Viewers also liked (20)

Siva knjiga 8 - preporuke za smanjenje birokratije u Srbiji
Siva knjiga 8 - preporuke za smanjenje birokratije u SrbijiSiva knjiga 8 - preporuke za smanjenje birokratije u Srbiji
Siva knjiga 8 - preporuke za smanjenje birokratije u Srbiji
 
Izvestaj zaI kvartal 2013 - status regulatorne reforme
Izvestaj zaI kvartal 2013  -   status regulatorne reformeIzvestaj zaI kvartal 2013  -   status regulatorne reforme
Izvestaj zaI kvartal 2013 - status regulatorne reforme
 
Let’s do it toul kork talk
Let’s do it toul kork talkLet’s do it toul kork talk
Let’s do it toul kork talk
 
OS Commerce
OS CommerceOS Commerce
OS Commerce
 
Najbolji JPP projekti: OIE, reciklaža, turizam - Raška, Nova Varoš, Zrenjanin
Najbolji JPP projekti: OIE, reciklaža, turizam - Raška, Nova Varoš, ZrenjaninNajbolji JPP projekti: OIE, reciklaža, turizam - Raška, Nova Varoš, Zrenjanin
Najbolji JPP projekti: OIE, reciklaža, turizam - Raška, Nova Varoš, Zrenjanin
 
M tsuchiya+utokyo+2013 2-1
M tsuchiya+utokyo+2013 2-1M tsuchiya+utokyo+2013 2-1
M tsuchiya+utokyo+2013 2-1
 
Berrett-Koehler Social Networking Best Practices
Berrett-Koehler Social Networking Best PracticesBerrett-Koehler Social Networking Best Practices
Berrett-Koehler Social Networking Best Practices
 
KhmerTalks: Find your passion
KhmerTalks: Find your passionKhmerTalks: Find your passion
KhmerTalks: Find your passion
 
Majei Iana-Ukraine
Majei Iana-UkraineMajei Iana-Ukraine
Majei Iana-Ukraine
 
KhmerTalks: Essential of e learning-last
KhmerTalks: Essential of e learning-lastKhmerTalks: Essential of e learning-last
KhmerTalks: Essential of e learning-last
 
Rezultati NALED-a 2014.
Rezultati NALED-a 2014.Rezultati NALED-a 2014.
Rezultati NALED-a 2014.
 
Alchemus pcms ver1
Alchemus pcms ver1Alchemus pcms ver1
Alchemus pcms ver1
 
National program for countering shadow economy in Serbia
National program for countering shadow economy in SerbiaNational program for countering shadow economy in Serbia
National program for countering shadow economy in Serbia
 
Charles dickens
Charles dickensCharles dickens
Charles dickens
 
Stop Wasting Money on SEM: Know Your Customer to Know your User
Stop Wasting Money on SEM: Know Your Customer to Know your UserStop Wasting Money on SEM: Know Your Customer to Know your User
Stop Wasting Money on SEM: Know Your Customer to Know your User
 
Stavovi privrede o regulatornom okruženju i sivoj ekonomiji, april 2015.
Stavovi privrede o regulatornom okruženju i sivoj ekonomiji, april 2015.Stavovi privrede o regulatornom okruženju i sivoj ekonomiji, april 2015.
Stavovi privrede o regulatornom okruženju i sivoj ekonomiji, april 2015.
 
Why Are Affiliate Sales Recommended For Newbies?
Why Are Affiliate Sales Recommended For Newbies?Why Are Affiliate Sales Recommended For Newbies?
Why Are Affiliate Sales Recommended For Newbies?
 
Zrenjaninska Siva knjiga propisa 2013
Zrenjaninska Siva knjiga propisa   2013Zrenjaninska Siva knjiga propisa   2013
Zrenjaninska Siva knjiga propisa 2013
 
Steve Piersanti of Berrett-Koehler Publishers - Keynote Address at PubWest Co...
Steve Piersanti of Berrett-Koehler Publishers - Keynote Address at PubWest Co...Steve Piersanti of Berrett-Koehler Publishers - Keynote Address at PubWest Co...
Steve Piersanti of Berrett-Koehler Publishers - Keynote Address at PubWest Co...
 
2012 03-17エッヂランク
2012 03-17エッヂランク2012 03-17エッヂランク
2012 03-17エッヂランク
 

Similar to Objects, Testing, and Responsibility

Demystifying Object-Oriented Programming - ZendCon 2016
Demystifying Object-Oriented Programming - ZendCon 2016Demystifying Object-Oriented Programming - ZendCon 2016
Demystifying Object-Oriented Programming - ZendCon 2016Alena Holligan
 
Demystifying Object-Oriented Programming - Lone Star PHP
Demystifying Object-Oriented Programming - Lone Star PHPDemystifying Object-Oriented Programming - Lone Star PHP
Demystifying Object-Oriented Programming - Lone Star PHPAlena Holligan
 
Introducing PHP Latest Updates
Introducing PHP Latest UpdatesIntroducing PHP Latest Updates
Introducing PHP Latest UpdatesIftekhar Eather
 
Demystifying Object-Oriented Programming #ssphp16
Demystifying Object-Oriented Programming #ssphp16Demystifying Object-Oriented Programming #ssphp16
Demystifying Object-Oriented Programming #ssphp16Alena Holligan
 
Demystifying Object-Oriented Programming #phpbnl18
Demystifying Object-Oriented Programming #phpbnl18Demystifying Object-Oriented Programming #phpbnl18
Demystifying Object-Oriented Programming #phpbnl18Alena Holligan
 
PHP: 4 Design Patterns to Make Better Code
PHP: 4 Design Patterns to Make Better CodePHP: 4 Design Patterns to Make Better Code
PHP: 4 Design Patterns to Make Better CodeSWIFTotter Solutions
 
Demystifying Object-Oriented Programming - PHP UK Conference 2017
Demystifying Object-Oriented Programming - PHP UK Conference 2017Demystifying Object-Oriented Programming - PHP UK Conference 2017
Demystifying Object-Oriented Programming - PHP UK Conference 2017Alena Holligan
 
Phpspec tips&amp;tricks
Phpspec tips&amp;tricksPhpspec tips&amp;tricks
Phpspec tips&amp;tricksFilip Golonka
 
Drupaljam xl 2019 presentation multilingualism makes better programmers
Drupaljam xl 2019 presentation   multilingualism makes better programmersDrupaljam xl 2019 presentation   multilingualism makes better programmers
Drupaljam xl 2019 presentation multilingualism makes better programmersAlexander Varwijk
 
Go OO! - Real-life Design Patterns in PHP 5
Go OO! - Real-life Design Patterns in PHP 5Go OO! - Real-life Design Patterns in PHP 5
Go OO! - Real-life Design Patterns in PHP 5Stephan Schmidt
 
PHP 5.3 Overview
PHP 5.3 OverviewPHP 5.3 Overview
PHP 5.3 Overviewjsmith92
 
PHP OOP Lecture - 04.pptx
PHP OOP Lecture - 04.pptxPHP OOP Lecture - 04.pptx
PHP OOP Lecture - 04.pptxAtikur Rahman
 
Why is crud a bad idea - focus on real scenarios
Why is crud a bad idea - focus on real scenariosWhy is crud a bad idea - focus on real scenarios
Why is crud a bad idea - focus on real scenariosDivante
 
Demystifying Object-Oriented Programming - PHP[tek] 2017
Demystifying Object-Oriented Programming - PHP[tek] 2017Demystifying Object-Oriented Programming - PHP[tek] 2017
Demystifying Object-Oriented Programming - PHP[tek] 2017Alena Holligan
 

Similar to Objects, Testing, and Responsibility (20)

OOP
OOPOOP
OOP
 
Demystifying Object-Oriented Programming - ZendCon 2016
Demystifying Object-Oriented Programming - ZendCon 2016Demystifying Object-Oriented Programming - ZendCon 2016
Demystifying Object-Oriented Programming - ZendCon 2016
 
OOP in PHP
OOP in PHPOOP in PHP
OOP in PHP
 
Demystifying Object-Oriented Programming - Lone Star PHP
Demystifying Object-Oriented Programming - Lone Star PHPDemystifying Object-Oriented Programming - Lone Star PHP
Demystifying Object-Oriented Programming - Lone Star PHP
 
Modern php
Modern phpModern php
Modern php
 
Introducing PHP Latest Updates
Introducing PHP Latest UpdatesIntroducing PHP Latest Updates
Introducing PHP Latest Updates
 
Demystifying Object-Oriented Programming #ssphp16
Demystifying Object-Oriented Programming #ssphp16Demystifying Object-Oriented Programming #ssphp16
Demystifying Object-Oriented Programming #ssphp16
 
Demystifying Object-Oriented Programming #phpbnl18
Demystifying Object-Oriented Programming #phpbnl18Demystifying Object-Oriented Programming #phpbnl18
Demystifying Object-Oriented Programming #phpbnl18
 
PHP: 4 Design Patterns to Make Better Code
PHP: 4 Design Patterns to Make Better CodePHP: 4 Design Patterns to Make Better Code
PHP: 4 Design Patterns to Make Better Code
 
Solid principles
Solid principlesSolid principles
Solid principles
 
Demystifying Object-Oriented Programming - PHP UK Conference 2017
Demystifying Object-Oriented Programming - PHP UK Conference 2017Demystifying Object-Oriented Programming - PHP UK Conference 2017
Demystifying Object-Oriented Programming - PHP UK Conference 2017
 
Ch8(oop)
Ch8(oop)Ch8(oop)
Ch8(oop)
 
Phpspec tips&amp;tricks
Phpspec tips&amp;tricksPhpspec tips&amp;tricks
Phpspec tips&amp;tricks
 
Drupaljam xl 2019 presentation multilingualism makes better programmers
Drupaljam xl 2019 presentation   multilingualism makes better programmersDrupaljam xl 2019 presentation   multilingualism makes better programmers
Drupaljam xl 2019 presentation multilingualism makes better programmers
 
Go OO! - Real-life Design Patterns in PHP 5
Go OO! - Real-life Design Patterns in PHP 5Go OO! - Real-life Design Patterns in PHP 5
Go OO! - Real-life Design Patterns in PHP 5
 
PHP 5.3 Overview
PHP 5.3 OverviewPHP 5.3 Overview
PHP 5.3 Overview
 
PHP OOP Lecture - 04.pptx
PHP OOP Lecture - 04.pptxPHP OOP Lecture - 04.pptx
PHP OOP Lecture - 04.pptx
 
PHP Unit Testing
PHP Unit TestingPHP Unit Testing
PHP Unit Testing
 
Why is crud a bad idea - focus on real scenarios
Why is crud a bad idea - focus on real scenariosWhy is crud a bad idea - focus on real scenarios
Why is crud a bad idea - focus on real scenarios
 
Demystifying Object-Oriented Programming - PHP[tek] 2017
Demystifying Object-Oriented Programming - PHP[tek] 2017Demystifying Object-Oriented Programming - PHP[tek] 2017
Demystifying Object-Oriented Programming - PHP[tek] 2017
 

Recently uploaded

Unraveling Multimodality with Large Language Models.pdf
Unraveling Multimodality with Large Language Models.pdfUnraveling Multimodality with Large Language Models.pdf
Unraveling Multimodality with Large Language Models.pdfAlex Barbosa Coqueiro
 
Take control of your SAP testing with UiPath Test Suite
Take control of your SAP testing with UiPath Test SuiteTake control of your SAP testing with UiPath Test Suite
Take control of your SAP testing with UiPath Test SuiteDianaGray10
 
How to write a Business Continuity Plan
How to write a Business Continuity PlanHow to write a Business Continuity Plan
How to write a Business Continuity PlanDatabarracks
 
Merck Moving Beyond Passwords: FIDO Paris Seminar.pptx
Merck Moving Beyond Passwords: FIDO Paris Seminar.pptxMerck Moving Beyond Passwords: FIDO Paris Seminar.pptx
Merck Moving Beyond Passwords: FIDO Paris Seminar.pptxLoriGlavin3
 
WordPress Websites for Engineers: Elevate Your Brand
WordPress Websites for Engineers: Elevate Your BrandWordPress Websites for Engineers: Elevate Your Brand
WordPress Websites for Engineers: Elevate Your Brandgvaughan
 
"ML in Production",Oleksandr Bagan
"ML in Production",Oleksandr Bagan"ML in Production",Oleksandr Bagan
"ML in Production",Oleksandr BaganFwdays
 
Vertex AI Gemini Prompt Engineering Tips
Vertex AI Gemini Prompt Engineering TipsVertex AI Gemini Prompt Engineering Tips
Vertex AI Gemini Prompt Engineering TipsMiki Katsuragi
 
What's New in Teams Calling, Meetings and Devices March 2024
What's New in Teams Calling, Meetings and Devices March 2024What's New in Teams Calling, Meetings and Devices March 2024
What's New in Teams Calling, Meetings and Devices March 2024Stephanie Beckett
 
Leverage Zilliz Serverless - Up to 50X Saving for Your Vector Storage Cost
Leverage Zilliz Serverless - Up to 50X Saving for Your Vector Storage CostLeverage Zilliz Serverless - Up to 50X Saving for Your Vector Storage Cost
Leverage Zilliz Serverless - Up to 50X Saving for Your Vector Storage CostZilliz
 
Powerpoint exploring the locations used in television show Time Clash
Powerpoint exploring the locations used in television show Time ClashPowerpoint exploring the locations used in television show Time Clash
Powerpoint exploring the locations used in television show Time Clashcharlottematthew16
 
Connect Wave/ connectwave Pitch Deck Presentation
Connect Wave/ connectwave Pitch Deck PresentationConnect Wave/ connectwave Pitch Deck Presentation
Connect Wave/ connectwave Pitch Deck PresentationSlibray Presentation
 
"LLMs for Python Engineers: Advanced Data Analysis and Semantic Kernel",Oleks...
"LLMs for Python Engineers: Advanced Data Analysis and Semantic Kernel",Oleks..."LLMs for Python Engineers: Advanced Data Analysis and Semantic Kernel",Oleks...
"LLMs for Python Engineers: Advanced Data Analysis and Semantic Kernel",Oleks...Fwdays
 
Anypoint Exchange: It’s Not Just a Repo!
Anypoint Exchange: It’s Not Just a Repo!Anypoint Exchange: It’s Not Just a Repo!
Anypoint Exchange: It’s Not Just a Repo!Manik S Magar
 
Transcript: New from BookNet Canada for 2024: BNC CataList - Tech Forum 2024
Transcript: New from BookNet Canada for 2024: BNC CataList - Tech Forum 2024Transcript: New from BookNet Canada for 2024: BNC CataList - Tech Forum 2024
Transcript: New from BookNet Canada for 2024: BNC CataList - Tech Forum 2024BookNet Canada
 
"Debugging python applications inside k8s environment", Andrii Soldatenko
"Debugging python applications inside k8s environment", Andrii Soldatenko"Debugging python applications inside k8s environment", Andrii Soldatenko
"Debugging python applications inside k8s environment", Andrii SoldatenkoFwdays
 
H2O.ai CEO/Founder: Sri Ambati Keynote at Wells Fargo Day
H2O.ai CEO/Founder: Sri Ambati Keynote at Wells Fargo DayH2O.ai CEO/Founder: Sri Ambati Keynote at Wells Fargo Day
H2O.ai CEO/Founder: Sri Ambati Keynote at Wells Fargo DaySri Ambati
 
SAP Build Work Zone - Overview L2-L3.pptx
SAP Build Work Zone - Overview L2-L3.pptxSAP Build Work Zone - Overview L2-L3.pptx
SAP Build Work Zone - Overview L2-L3.pptxNavinnSomaal
 
TrustArc Webinar - How to Build Consumer Trust Through Data Privacy
TrustArc Webinar - How to Build Consumer Trust Through Data PrivacyTrustArc Webinar - How to Build Consumer Trust Through Data Privacy
TrustArc Webinar - How to Build Consumer Trust Through Data PrivacyTrustArc
 
Story boards and shot lists for my a level piece
Story boards and shot lists for my a level pieceStory boards and shot lists for my a level piece
Story boards and shot lists for my a level piececharlottematthew16
 

Recently uploaded (20)

Unraveling Multimodality with Large Language Models.pdf
Unraveling Multimodality with Large Language Models.pdfUnraveling Multimodality with Large Language Models.pdf
Unraveling Multimodality with Large Language Models.pdf
 
Take control of your SAP testing with UiPath Test Suite
Take control of your SAP testing with UiPath Test SuiteTake control of your SAP testing with UiPath Test Suite
Take control of your SAP testing with UiPath Test Suite
 
How to write a Business Continuity Plan
How to write a Business Continuity PlanHow to write a Business Continuity Plan
How to write a Business Continuity Plan
 
Merck Moving Beyond Passwords: FIDO Paris Seminar.pptx
Merck Moving Beyond Passwords: FIDO Paris Seminar.pptxMerck Moving Beyond Passwords: FIDO Paris Seminar.pptx
Merck Moving Beyond Passwords: FIDO Paris Seminar.pptx
 
WordPress Websites for Engineers: Elevate Your Brand
WordPress Websites for Engineers: Elevate Your BrandWordPress Websites for Engineers: Elevate Your Brand
WordPress Websites for Engineers: Elevate Your Brand
 
"ML in Production",Oleksandr Bagan
"ML in Production",Oleksandr Bagan"ML in Production",Oleksandr Bagan
"ML in Production",Oleksandr Bagan
 
Vertex AI Gemini Prompt Engineering Tips
Vertex AI Gemini Prompt Engineering TipsVertex AI Gemini Prompt Engineering Tips
Vertex AI Gemini Prompt Engineering Tips
 
What's New in Teams Calling, Meetings and Devices March 2024
What's New in Teams Calling, Meetings and Devices March 2024What's New in Teams Calling, Meetings and Devices March 2024
What's New in Teams Calling, Meetings and Devices March 2024
 
Leverage Zilliz Serverless - Up to 50X Saving for Your Vector Storage Cost
Leverage Zilliz Serverless - Up to 50X Saving for Your Vector Storage CostLeverage Zilliz Serverless - Up to 50X Saving for Your Vector Storage Cost
Leverage Zilliz Serverless - Up to 50X Saving for Your Vector Storage Cost
 
Powerpoint exploring the locations used in television show Time Clash
Powerpoint exploring the locations used in television show Time ClashPowerpoint exploring the locations used in television show Time Clash
Powerpoint exploring the locations used in television show Time Clash
 
Connect Wave/ connectwave Pitch Deck Presentation
Connect Wave/ connectwave Pitch Deck PresentationConnect Wave/ connectwave Pitch Deck Presentation
Connect Wave/ connectwave Pitch Deck Presentation
 
"LLMs for Python Engineers: Advanced Data Analysis and Semantic Kernel",Oleks...
"LLMs for Python Engineers: Advanced Data Analysis and Semantic Kernel",Oleks..."LLMs for Python Engineers: Advanced Data Analysis and Semantic Kernel",Oleks...
"LLMs for Python Engineers: Advanced Data Analysis and Semantic Kernel",Oleks...
 
E-Vehicle_Hacking_by_Parul Sharma_null_owasp.pptx
E-Vehicle_Hacking_by_Parul Sharma_null_owasp.pptxE-Vehicle_Hacking_by_Parul Sharma_null_owasp.pptx
E-Vehicle_Hacking_by_Parul Sharma_null_owasp.pptx
 
Anypoint Exchange: It’s Not Just a Repo!
Anypoint Exchange: It’s Not Just a Repo!Anypoint Exchange: It’s Not Just a Repo!
Anypoint Exchange: It’s Not Just a Repo!
 
Transcript: New from BookNet Canada for 2024: BNC CataList - Tech Forum 2024
Transcript: New from BookNet Canada for 2024: BNC CataList - Tech Forum 2024Transcript: New from BookNet Canada for 2024: BNC CataList - Tech Forum 2024
Transcript: New from BookNet Canada for 2024: BNC CataList - Tech Forum 2024
 
"Debugging python applications inside k8s environment", Andrii Soldatenko
"Debugging python applications inside k8s environment", Andrii Soldatenko"Debugging python applications inside k8s environment", Andrii Soldatenko
"Debugging python applications inside k8s environment", Andrii Soldatenko
 
H2O.ai CEO/Founder: Sri Ambati Keynote at Wells Fargo Day
H2O.ai CEO/Founder: Sri Ambati Keynote at Wells Fargo DayH2O.ai CEO/Founder: Sri Ambati Keynote at Wells Fargo Day
H2O.ai CEO/Founder: Sri Ambati Keynote at Wells Fargo Day
 
SAP Build Work Zone - Overview L2-L3.pptx
SAP Build Work Zone - Overview L2-L3.pptxSAP Build Work Zone - Overview L2-L3.pptx
SAP Build Work Zone - Overview L2-L3.pptx
 
TrustArc Webinar - How to Build Consumer Trust Through Data Privacy
TrustArc Webinar - How to Build Consumer Trust Through Data PrivacyTrustArc Webinar - How to Build Consumer Trust Through Data Privacy
TrustArc Webinar - How to Build Consumer Trust Through Data Privacy
 
Story boards and shot lists for my a level piece
Story boards and shot lists for my a level pieceStory boards and shot lists for my a level piece
Story boards and shot lists for my a level piece
 

Objects, Testing, and Responsibility

  • 1. OBJECTS, TESTING, AND RESPONSIBILITY MATTHEW MACHUGA LARACON EU AUGUST 2013
  • 2. HI, I'M MATT MACHUGA! SOFTWARE DEVELOPER RUBY | JS | PHP
  • 3. ONLINE: MACHUGA IRC: machuga GitHub: machuga Twitter: @machuga I WEAR MANY HATS IN IRC "Have you checked the docs first?"
  • 5. THINK THROUGH LEARNING THINK THROUGH MATH HELP KIDS LEARN MATH SENIOR SOFTWARE DEVELOPER I HAVE THE BEST COWORKERS EVER!
  • 6. BEFORE WE BEGIN... LARAVEL COMMUNITY!THANK YOU, YOU'RE ALL AMAZING!
  • 8. OBJECTS Object Oriented Programming Object Oriented Design Pro's and Con's Improvements to code
  • 9. TESTING Correlation between good OOD and good tests Tests are good No, seriously. Tests are good. Stop hating.
  • 10. RESPONSIBILITY See also: Accountability Holding components accountable Giving objects explicit responsibilities 1:1 Object:Responsibility Ratio (when possible) Responsibilty to code Responsibilty to team Responsibilty to your future self
  • 12. Alan Kay Father of OOP "I thought of objects being like biological cells and/or individual computers on a network, only able to communicate with messages"
  • 13. OBJECT-ORIENTED PROGRAMMING Originated from Functional and Procedural Solution to code organization, data-hiding, reuse Solution to easier testing Solution to structure and protocols
  • 15. QUESTION Which version of PHP first gained objects? PHP 3
  • 16. OOP: OBJECT ORIENTED PHP THE LIVE ACTION SERIES
  • 17. OOP: OBJECT ORIENTED PHP 16 years and 4 days ago: PHP codebase gets classes PHP 3 released in 1998 Associative Array ++
  • 18. OOP: OBJECT ORIENTED PHP PHP 3 & 4 CAPABILITIES Classes Objects Simple single inheritance Pass-by-value All public visibility
  • 19. OOP: OBJECT ORIENTED PHP PHP 5.0 - 5.2.X ENHANCEMENTS Pass-by-reference public/ private/ protectedvisibility Static methods/properties Class constants __construct() Destructors Abstract and Final classes Interfaces
  • 20. OOP: OBJECT ORIENTED PHP PHP 5.3 ENHANCEMENTS Usable single inheritance! Late Static Binding Namespaces Closures
  • 21. OOP: OBJECT ORIENTED PHP PHP 5.3 ANTIPATTERNS goto No full namespace import
  • 22. OOP: OBJECT ORIENTED PHP PHP 5.4 ENHANCEMENTS Traits Closure Rebinding
  • 23. IT TOOK ABOUT 14 YEARS But we now have a very capable object model in PHP
  • 25. ABSTRACTION Remove and isolate related behavior or data Responsibility
  • 27. PROCEDURAL <?php function get_db() { /* return the db conneciton */} function user_show($user) { /* Awesome procedural code */ } function user_fetch($user) { $db = get_db(); /* Awesome procedural code */ function user_delete($user) { $db = get_db(); /* Awesome procedural code */ function user_create($user, $data) { $db = get_db(); /* Awesome procedural co function user_update($user, $data) { $db = get_db(); /* Awesome procedural co function user_store_data($user, $user_data) { if (user_fetch($user)) { return user_update($user, $user_data); } else { return user_create($user, $user_data); }
  • 28. ABSTRACTED <php class User extends Eloquent { // All provided by Eloquent public static function find($id) {} public function delete() {} public function create($attributes) {} public function update($attributes) {} public function save() {} }
  • 29. ENCAPSULATION Keep data and behavior in a black box Use a public interface to interact with the black box Much like a function - data in, data out Prevents leaky abstractions
  • 31. ILLUMINATEDATABASEELOQUENTMODEL PROPERTIES 4 Public Instance/Class 19 Protected Instance/Class 0 Private Instance/Class METHODS 126 Public Instance/Class 25 Protected Instance/Class 0 Private Instance/Class
  • 32. INHERITANCE The double edged sword Allows classes to be extended from other classes Properties and methods can ascend the ancestry Saves a lot of code
  • 33. EXAMPLE - PLAIN CLASSES <?php class Rectangle { public function __construct($coords) {} public function getCoordinates() {} public function setCoordinates($coords) {} public function getXX() {} public function getXY() {} public function getYX() {} public function getYY() {} public function setXX($coord) {} public function setXY($coord) {} public function setYX($coord) {} public function setYY($coord) {}
  • 34. EXAMPLE - INHERITED <?php class Square extends Rectangle {} class Diamond extends Rectangle {} class Rectangle { public function __construct($coords) {} public function getCoordinates() {} public function setCoordinates($coords) {} public function getXX() {} public function getXY() {} public function getYX() {} public function getYY() {} public function setXX($coord) {}
  • 35. POLYMORPHISM Probably the best feature of OOP Any object may be used if it implements expected method/property Allows code branching without if/else logic PHP is a duck typed language - "If it walks like a duck" PHP also allows type hinting - "You will be a duck and you will like it!"
  • 36. EXAMPLE <php class BlogPostWidget { public function render() {} } class GalleryWidget { public function render() {} } class PollWidget { public function render() {} }
  • 37. EXAMPLE W/ TYPE HINTING <php interface Widget { public function render() {} } class BlogPostWidget implements Widget { public function render() {} } class GalleryWidget implements Widget { public function render() {} } class PollWidget implements Widget
  • 38. HOW IS THIS USABLE? Phill Sparks and Fabien showed you yesterday! Pay attention!
  • 39. DESIGN PATTERNS Finding common patterns in code and making it reusable Take advantage of OO constructs
  • 40. CODE REUSE AND EXTENSIBILITY Proper abstraction leads to reusable code Fluent Class in Laravel 3 as an example (not the DB one) Validators in Laravel Drivers
  • 41. LATE-STATIC BINDING selfnever worked like it should've staticis what selfwanted to be selfwill call the class the method was defined on, not the subclass you likely expecting statichowever will
  • 42. EXAMPLE <php class A { public function sadface() { return new self(); } public function happyface() { return new static(); } } class B extends A {} $b = new B(); $b->sadface(); // A object
  • 43. TRAITS Traits allow for methods/properties to be added to a class at compile-time Not quite mixins, but close In a sense, allows for multiple inheritance This scares people Not always the right solution, but often suited Another great form of reusable abstraction
  • 44. EXAMPLE <php trait Bar { protected $baz; public function baz() { return $this->baz; } } class Foo { use Bar; public function setBaz($baz) {
  • 45. GET THE MOST OUT OF YOUR OBJECTS
  • 46. TELL, DON'T ASK Tell your objects what you want them to do Don't ask them data about themselves. Remember: Black box
  • 47. COMPOSITION OVER INHERITANCE Composing two or more objects together The sum is greater than the parts Provides more flexibility Not always the right solution, but often the better suited More code to compose (usually) "Does X belong on this object?"
  • 48. COMPOSITION WITH TRAITS SOME PEOPLE REALLY HATE TRAITS Traits allow for methods/properties to be added to a class at compile-time Not quite mixins, but close In a sense, allows for multiple inheritance This scares people Not always the right solution, but often the better suited Another great form of reusable abstraction
  • 50. TESTING CAN BE HARD ESPECIALLY IF YOU'RE MAKING IT HARD
  • 51. TDD SERVES MANY PURPOSES Guiding you to make well abstracted solutions Help you write the least code possible Ensure your code works Ensure your code works as it is intended Ensure tests become executable documentation for your code and acceptance criteria
  • 54. BASE TESTS OFF ACCEPTANCE CRITERIA Stakeholders want their features You want the features to work You want to guarantee your unit tests come together
  • 55. TDD IS NOT THE ONLY WAY Tests don't need to drive or guide your code Testing after is perfectly reasonable BUT ALWAYS LISTEN TO YOUR TESTS
  • 56. LISTENING TO TESTS Tests will let you know if somethign smells funny A class that does too many things is hard to test A test with too many dependencies is hard to test A test with too many mocks is hard to mantain A test that is too difficult is easy to abandon
  • 57. DON'T BE AFRAID TO ADD MORE OBJECTS/CLASSES
  • 58. EXAMPLE - AUTHORITY <php protected $dispatcher; public function __construct($currentUser, $dispatcher = null) { $this->rules = new RuleRepository; $this->setDispatcher($dispatcher); $this->setCurrentUser($currentUser); $this->dispatch('authority.initialized', array( 'user' => $this->getCurrentUser(), )); } public function dispatch($eventName, $payload = array()) { if ($this->dispatcher) { return $this->dispatcher->fire($eventName, $payload);
  • 59. EXAMPLE - AUTHORITY TESTS <php public function testInitializeEvent() { $test = new stdClass; $user = new stdClass; $user->name = 'Tester'; $this->dispatcher->listen('authority.initialized', function($payload $test->user = $payload->user; $test->timestamp = $payload->timestamp; }); $authority = new Authority($user, $this->dispatcher); $this->assertSame($test->user, $user); $this->assertInstanceOf('DateTime', $test->timestamp); }
  • 60. SOME THINGS ON TESTING You do not need a test for every method Sometimes you need more than one test for a method Mocking can fall short and lose sync. If you don't test everything, test areas of high churn Do not reach for AspectMock right away because something is hard Test your own code, not third party
  • 61. SOME MORE THINGS ON TESTING This is not a good test <php testFoo() { $foo = new Foo(); $bar = new Bar(); $baz = $foo->doSomethingEpic($bar); if (is_array($baz) and !is_empty($baz)) { $this->assertTrue(true); } else { $this->assertFalse(true); } }
  • 62. SOME MORE THINGS ON TESTING Nor this <php testSomething() { $foo = new Foo(); $bar = new Bar(); $baz = $foo->doSomethingEpic($bar); // Baz doesn't seem to eval right, passing for now // @TODO: Come back later $this->assertTrue(true); }
  • 63. SOME MORE THINGS ON TESTING Nor this <php testStringReverse() { $str = new AwesomeString(); $string = 'Hello'; // Implementation: return strrev($string) $reversed = $str->reverseString($string); $this->assertEquals(strrev($string), $reversed); }
  • 64. SOME MORE THINGS ON TESTING Nor this...I don't even... <php testWeirdFeature() { // 2 + 2 should be 4 if (2+2 == 3) { $this->assertTrue(true); } else { $this->assertTrue(false); } }
  • 65. CAN IT BE CLEANED UP? ABSOLUTELY! BUT IT WORKS!
  • 67. RESPONSIBILITY You have a responsibility not to make tests like what I've just shown
  • 68. RESPONSIBILITY: OBJECTS Give your objects a task Do not overwork your objects Give your objects some proper tests Like profiling and logging, objects can help with accountability
  • 69. RESPONSIBILITY: YOU You have a responsibility to yourself You have a responsibility to your team You have a responsibility to your consumers You have a responsibility to your future self Become responsible and be accountable for your code
  • 71. THANK YOU! IRC: machuga GitHub: machuga Twitter: @machuga