be aware of side effects

Post on 07-Jul-2015

299 Views

Category:

Technology

0 Downloads

Preview:

Click to see full reader

DESCRIPTION

RubyFuza 2013 talk slides

TRANSCRIPT

be aware ofside-effects

@ryanlemmer / gmt+2

(thinking even more functionally in Ruby)

you can do this in Haskell

a = "greetings!"

and this

a = "greetings!"b = a + " rubyfuza"

and this

a = "greetings!"b = +("greetings!"," rubyfuza")

but you can’t do this in Haskell

a = "greetings!"a = a + " rubyfuza"

but you can’t do this in Haskell

a = "greetings!"a = +("greetings!"," rubyfuza")

value

a = "greetings!"a = a + " rubyfuza"

a = "greetings!"b = a + " rubyfuza"

variable

(immutable) (mutable)

value

a = "greetings!"a = "greetings!"

variable

(immutable) (mutable)

b = a + " rubyfuza" a = a + " rubyfuza"

... other stuff ... other stuff

value

a = "greetings!"a = a + " rubyfuza"

a = "greetings!"b = a + " rubyfuza"

variable=

value

a = "greetings!"a = a + " rubyfuza"

a = "greetings!"b = a + " rubyfuza"

there is no variable

value variable

val a = "greetings!";val b = a + " rubyfuza";

var a = "greetings!";a = a + " rubyfuza";

!=

def add(a, b) a + bend

def add_freaky(a, b) z = a*b a + b * zend

@a = 11

def incr_by(n) @a += nend

@a = 11EXTRA = 10

def incr_by(n) @a += n + EXTRAend

class Calculator attr_reader :balance

def initialize(balance) @balance = balance || 0 end

def incr_by(n) @balance += n end ...end

def test num = Calculator.new(0).incr_by(10)  assert_equal 10, numend

class Calculator attr_reader :x, :y, :z, :w, ... attr_accessor :v1, :v2, :v3, ...

def initialize(obj, b, c, ...) obj.set_something(w,y,z, ...) end

def wicked_calc(p1, p2, ...) x/y/z/w/v1/v2/v3 end ...end

class MoreFunctionalCalculator attr_reader :balance

def initialize(balance) @balance = balance || 0 end

def incr_by(n) @balance = self.add(@balance, n) end

private def add(a, b); a+b endend

upcased = [] arr.each do |s| upcased.push(s.upcase) end # use upcased

arr.map do |s| s.upcase end

u = arr.map do |s| s.upcase end u.collect do |s| s ++ “zzzz” end

upcased = [] arr.each do |s| upcased.push(s.upcase ++ “zzzz”) end

taming side-effectsLIMIT them

extract maximum purity (through composition)use functional forms

CONSTRAIN them, make them EXPLICIT, use CONVENTIONS

Haskell => Monads/STM

Erlang => Messages

Active Record

why bother?

cost TIME => $$$cost ENERGY

cause ULCERS

because side effects...

top related