practical object-oriented design in ruby ch7

Post on 24-Jan-2018

248 Views

Category:

Software

5 Downloads

Preview:

Click to see full reader

TRANSCRIPT

Sharing Role Behavior with Modules

Jerry - 2015.10

How many different ways can methods be implemented?

How many different ways can methods be implemented?

• Those it implements

How many different ways can methods be implemented?

• Those it implements

• Those implemented in all objects above it in the hierarchy

How many different ways can methods be implemented?

• Those it implements

• Those implemented in all objects above it in the hierarchy

• Those implemented in any module that has been added to it

How many different ways can methods be implemented?

• Those it implements

• Those implemented in all objects above it in the hierarchy

• Those implemented in any module that has been added to it

• Those implemented in all modules added to any object above it in the hierarchy

Some problems require sharing behavior among otherwise

unrelated objects.

Modules allow objects of different classes to play a

common role.

Trip Scheduling Problem

• Trip involve bicycles, mechanics, and motor vehicles

• Need to know whether bicycles/mechanics/vehicles are available for trip or not

• Downtime for bicycles are 1 day between trips, vehicles 3 days, and mechanics 4 days.

Remove dependency

str.empty?

or

StingUtils.empty?(str)

Let objects speak for themselves

Extracting the Abstraction

Looking up methods

Recognise the Antipatterns

• If using variables like type or category, look to classical inheritance.

• If checking the class of receiving objects to determine which message to send, duck typing.

Insist on the Abstraction

• Superclasses should not contain code that applies to some, but not all, subclasses.

• When subclasses override a method to declare that they do not do that thing they close to declaring that they are not that thing.

• This restriction also applies to modules

Honor the Contract

• subclasses agree to a contract, promising to be substitutable for their superclasses. Maintain that substitutability.

• Is a Square a Rectangle?

Template Method Pattern

• The abstract code defines the algorithms and

• The concrete inheritors overriding these template methods.

Preemptively Decouple Classes

• Avoid writing code that requires its inheritors to send super

• Use hook messages.

Create Shallow Hierarchies

top related