confident ruby: be a coding hemingway

Post on 26-Jun-2015

771 Views

Category:

Technology

4 Downloads

Preview:

Click to see full reader

DESCRIPTION

Book Report on Avdi Grimm's excellent 'Confident Ruby'

TRANSCRIPT

Confident RubyBe A Coding Hemingway

Confident Ruby

Avdi Grimmhttp://www.rubytapas.com/

● Application Design

● Object Modeling

● Patterns for writing confident Ruby code at the method level

Doesn’t: Does:

“CODE AS NARRATIVE”

Responsibilities

Collecting Input

Performing Work

Delivering Output

Handling Errors

Conversion Methods

Special Case Object

Receive Policies

Conversion Methods

Conversion Methods for Coercing Inputs

Checking for ‘nil’ (type checking)

Nested control structures(‘if/else’ blocks)

Type checking

● #to_a, #to_i, #to_s

● objects don’t resemble the target type

● Implemented by Ruby types but not called

Explicit Conversion

● #to_ary, #to_int, #to_str

● objects closely resemble the target type

● Called by Ruby but not implemented

Implicit Conversion

● Array(), Integer(), String()

● Try implicit and explicit conversions

● Bag o’ tricks

Kernel Level Conversion Methods

Flexible

Coherent

Confident ; )

Conversion Methods

Special Case Object

Conversion Methods

=>

Special Case Object● isolate the differences to a single object

● Leverage polymorphism by conforming to a protocol

=>

ConfidentExpressiveFlexible

“The foundation of an object oriented system is the message”

-Sandi Metz, Practical Object-Oriented Design in Ruby

Conversion Methods

Receive Policies Instead of Data

“Put the decision for how to handle test cases in the hands of the code best qualified to determine the appropriate response.”

Delegate Responsibility to Client Code

Passing data/flags

● Intent of the method is obscured

● Calling code is not self-documenting

● Little flexibility. What if we want more than 2 ways to handle errors?

● Pass policies as block/proc/lambda objects

● Stop handling edge cases from obfuscating the method’s intent

● Flexibility - let’s the client code handle decision making

Passing Policies

Example: Ruby’s Enumerable#detect

Write code that tells a storyConfident Ruby - Avdi Grimm

top related