object oriented apologetics

80
Object Oriented Apologetics Vance Lucas CodeWorks 2009 Dallas September 27, 2009

Upload: vance-lucas

Post on 28-Jun-2015

2.484 views

Category:

Technology


6 download

DESCRIPTION

In defense of object-oriented programming - How and why you should use object oriented programming for your next project. This talk is for PHP programmers who are just learning about object oriented code, who cling to old excuses ("object oriented code is slower"), or who are otherwise unconvinced of its usefulness. Concrete real-world examples of common scenarios and challenges that programmers face will be presented, and how taking an object oriented approach is better than a procedural one in most cases. Copious code examples in both object oriented and procedural approaches will be provided throughout, and the differences and benefits of the object oriented approach will be explained.

TRANSCRIPT

Page 1: Object Oriented Apologetics

Object Oriented Apologetics

Vance LucasCodeWorks 2009 Dallas

September 27, 2009

Page 2: Object Oriented Apologetics

2

What?

Not an apologyGreek root- apologia (απολογία)- “speaking in defense”

To defend the use of, andprovide rational reasoning for

Page 3: Object Oriented Apologetics

3

Who is it for?

For People Who:• Are “on the fence” about OOP

vs procedural• Are unconvinced of the

usefulness of OOP• Want to learn WHY they should

learn about OOP

Page 4: Object Oriented Apologetics

4

Purpose: To Get You Hooked on OOP

Page 5: Object Oriented Apologetics

5

NO Academic or Mundane Examples

Page 6: Object Oriented Apologetics

6

No Shapes, Cars, Fruit, or Bicycles

Page 7: Object Oriented Apologetics

7

<?php class myClass { public function myClass(){ } public function echoMe(){ echo 'me'; } } $mine=new myClass(); $mine->echoMe();

?>

No “Hello World” Scripts

Page 8: Object Oriented Apologetics

SO… WHY OOP?

Page 9: Object Oriented Apologetics

9

Polymorphism

I nheritance

E ncapsulation

Page 10: Object Oriented Apologetics

10

Polymorphism

Page 11: Object Oriented Apologetics

11

• Making things that are not the same look the same

• Relies on a defined interface• Inheritance is probably the most used method

• The ability of type A to be used like type B• Think: Interchangeable types or components

Polymorphism

Page 12: Object Oriented Apologetics

12

Real World: Different Implementations

Page 13: Object Oriented Apologetics

13

Procedural - Inline

Page 14: Object Oriented Apologetics

14

Object-oriented – Polymorphic Interface

Page 15: Object Oriented Apologetics

15

Inheritance

Page 16: Object Oriented Apologetics

16

• Extend from a parent class– “is-a” relationship

• Creates hierarchal relationship• Get functionality for free• Global changes are easier

• Inherits all functions and properties from parent• Think: A is a B, with a few differences

Inheritance

Page 17: Object Oriented Apologetics

17

Controller: Zend Framework

Page 18: Object Oriented Apologetics

18

Model: phpDataMapper

Page 19: Object Oriented Apologetics

19

Warning: Keep Hierarchy Shallow

Page 20: Object Oriented Apologetics

20

Encapsulation

Page 21: Object Oriented Apologetics

21

• Hide specific implementation details• Reveal only methods and properties required to

interact with the object

• Limits interdependencies between components• Think: Separation of responsibilities

Encapsulation

Page 22: Object Oriented Apologetics

22

Payment Interface – Exposed Methods

Page 23: Object Oriented Apologetics

23

Planetoids (by Micah Jones)

Page 24: Object Oriented Apologetics

24

• Asteroids responsible for their own movement• Different: velocities, sizes, shapes, rotations, color,

and fragment pieces• All the code and math calculations for movement are

encapsulated behind ‘move()’• Allows different types of objects and asteroids to be

treated the same in code – “polymorphically”

Planetoids: Code Abstraction

Page 25: Object Oriented Apologetics

OTHER OOP-ONLY FEATURES?

25

Page 26: Object Oriented Apologetics

Lazy-Loading

Page 27: Object Oriented Apologetics

27

• Uses __get() “magic” method in PHP5 object model

• Also uses SPL interfaces to fire query on:– count()– foreach()

• Used as a hook to retrieve related rows on call• Caches results so only 1 query is fired• Can eliminate N+1 query problem by mapping

Lazy-Loading: OOP Only

Page 28: Object Oriented Apologetics

28

• Classes are actually custom types• Can type-hint for classes or interfaces

• PHP Standard types:– string, int, float, boolean, array, object, null– resource

Custom Type Creation & Type-Hinting

Page 29: Object Oriented Apologetics

OTHER REASONS TO USE OOP?

Page 30: Object Oriented Apologetics

• Easily group related properties/data• Avoid using globals or passing/returning arrays• Suppress errors ala ‘undefined index’• More?

Convenience (a.k.a. Laziness)

30

Page 31: Object Oriented Apologetics

31

• Request object: Why not $_POST?– Data comes from multiple sources• POST/GET, XML, JSON, etc.

– Other functions• isAjax(), isPost(), etc.

– Sanitizing user input

• Session object: Why not $_SESSION?– More options for saving/storing• Database, separate server, memcached, etc.

Request / Session Objects

Page 32: Object Oriented Apologetics

32

Request Object: Convenience, too!

Page 33: Object Oriented Apologetics

NEED AN EXAMPLE?

Page 34: Object Oriented Apologetics

E-commerce Cart: Work Scope• Basic categories (1-level)• Simple products, no options, stock, etc.• Simple checkout, no user accounts• Authorize.net integration• UPS rate quotes• Admin backend• Order fulfillment• Invoice/packing slip printing

Page 35: Object Oriented Apologetics

35

Simple Cart

Page 36: Object Oriented Apologetics

36

Simple Checkout

Page 37: Object Oriented Apologetics

37

Simple UPS Integration

Page 38: Object Oriented Apologetics

38

• So far it’s OK• It works• We finished and worked quickly

Status Check

Page 39: Object Oriented Apologetics

39

Client MessageI talked to my next door neighbor’s cousin’s

brother’s niece yesterday, and he says all the serious online stores have regular sales. That’s something I can do too, right?

- Bob

Page 40: Object Oriented Apologetics

40

Product Sales

Page 41: Object Oriented Apologetics

41

New Code for Product Sale

Page 42: Object Oriented Apologetics

42

• We also have to add this code to the admin backend for customer invoices.– And to the email reciepts

• Sin of code duplication– Code smell

Thoughts

Page 43: Object Oriented Apologetics

43

Client MessageHey, I was at the grocery store yesterday and

my daughter got 2 candy bars for $1, when they were originally $0.75 each.

I know that if I am able to do this, I’ll get a lot of sales and it will make me rich. I need to be able to do this.

- Bob

Page 44: Object Oriented Apologetics

44

Multi-Quantity Discounts

Page 45: Object Oriented Apologetics

45

New Code, Again

Page 46: Object Oriented Apologetics

46

• We also have to add this code to the admin backend and other places again.

• Sin of code duplication

• We could use procedural functions for this– Where would we put them?– What responsibilities do they have?

Thoughts

Page 47: Object Oriented Apologetics

47

What about the future?

Page 48: Object Oriented Apologetics

48

Employee Discounts

Page 49: Object Oriented Apologetics

49

Switching to FedEx

Page 50: Object Oriented Apologetics

Stock Checking

50

Page 51: Object Oriented Apologetics

51

Clearly, as the project grows, it will become amaintenance nightmare if we continue on thecurrent path.

We don’t want our code to be the running joke ofthe PHP community.

We need something better

Page 52: Object Oriented Apologetics

52

Page 53: Object Oriented Apologetics

53

Use the right tool for the right job

Page 54: Object Oriented Apologetics

54

OOP: Right tool for this job

Page 55: Object Oriented Apologetics

55

• Create a Cart class to store items• Encapsulate the pricing logic in an Item class– Single place to change the code– Item is responsible for knowing it’s price (?)• What does this imply?

Thoughts

Page 56: Object Oriented Apologetics

56

Possible Code Changes

Page 57: Object Oriented Apologetics

57

• Still storing cart in session, but now we can change it later when we need to scale

• Cart gets item price so it can check quantities– Cart is responsible for knowing other items in cart

• Better separation of responsibility– It’s not the job of the display logic to calculate the

item’s price or apply discounts• What about changing to FedEx?

Thoughts

Page 58: Object Oriented Apologetics

58

Re-factor it into two classes

Page 59: Object Oriented Apologetics

59

• Package is responsible for knowing it’s own dimensions and weight

• Quote is responsible for fetching a live rate quote from a carrier API service

• Always think in terms of responsibility– What code is responsible for what functions?– Where does it go in my app?– Is this code doing too much?

Thoughts

Page 60: Object Oriented Apologetics

60

Think about how an assembly line works

Page 61: Object Oriented Apologetics

OOP MYTHS AND MISCONCEPTIONS

Page 62: Object Oriented Apologetics

62

Myth #1:OOP is about code re-use

Page 63: Object Oriented Apologetics

63

Truth:Re-useable code is a by-product of good OO

Page 64: Object Oriented Apologetics

64

Problem:There are lots of ways to make re-useable code

that are not object-oriented nor good.It’s a bad goal.

Page 65: Object Oriented Apologetics

65

<Code with functions and includes – re-useable>Functions are re-useable

Page 66: Object Oriented Apologetics

66

Specific implementations are re-useable

Page 67: Object Oriented Apologetics

67

<UPS-Specific API Code>or<Payment Gateway-specific API Code>

Soft interfaces are re-useable

Page 68: Object Oriented Apologetics

68

• You must set goals that will help direct you to your desired outcome

• Goals narrow attention and direct efforts to goal-relevant activities, and away from perceived undesirable and goal-irrelevant actions

• Re-use as a goal does not help you write good OO code. Re-use is a by-product of good OO.

Point: Set Good Goals

Page 69: Object Oriented Apologetics

69

Myth #2:Objects should always be modeled after real-world

objects when possible

Page 70: Object Oriented Apologetics

70

Truth:Objects should be modeled and built based on

what you need to complete your task

Page 71: Object Oriented Apologetics

71

Problem:Real-world object models are almost never useful

in code

Page 72: Object Oriented Apologetics

72

Real-World Objects Change

Page 73: Object Oriented Apologetics

73

You are modeling things that don’t

exist

Page 74: Object Oriented Apologetics

74

Page 75: Object Oriented Apologetics

75

Myth #3:Everything should be objects

Page 76: Object Oriented Apologetics

76

Truth:Make objects for only what you need to. Most of

the time this is data. Don’t over-complicate your code when it’s not necessary.

Page 77: Object Oriented Apologetics

77

Problem:Not everything your code does can be easily

represented with an object

Page 78: Object Oriented Apologetics

78

Application Flow

MVC diagram forXEROX PARC 1978-79

Page 79: Object Oriented Apologetics

79

Page 80: Object Oriented Apologetics

80

• Programming PHP for over 10 years• Web: http://www.vancelucas.com• Twitter: @vlucas• Email: [email protected]• GitHub: http://github.com/vlucas

• Photo Set: http://www.flickr.com/photos/30728345@N05/galleries/72157622318592067/

Vance Lucas