04-Yield-RSpecIntro-SaaSArchIntro.pdf - yield(Engineering...

This preview shows page 1 - 15 out of 66 pages.

yield() (Engineering Software as a Service §3.8) © 2013 Armando Fox & David Patterson, all rights reserved
Inelegant, This ArrayList aList ; Iterator it = aList . iterator() ; while ( it.hasNext() ) { Object element = it.getNext() ; // do some stuff with element } Goal of the code: do stuff with elements of aList But iterator logic is all jumbled up with the code
Blocks (Anonymous λ) (map '(lambda (x) (+ x 2)) mylist ) mylist.map { |x| x+2 } (filter '(lambda (x) (even? x)) mylist) mylist.select do |x| ; x.even? ; end (map '(lambda (x) (+ x 2)) (filter '(lambda (x) (even? x)) mylist)) mylist.select {|x| x.even?}.map {|x| x+2 }
Turning Iterators Inside-Out Java: You hand me each element of a collection in turn I will do some stuff Then I will ask you if there’s any more left Ruby: Here is some code to apply to every element of the collection You manage iteration or data structure traversal Give me each element to do stuff to Let’s do an example...
Iterators are Just One Nifty Use of yield # in File class def open(filename) ...open a file... end def close ...close a file... end # in your code def do_everything f = File.open( "foo" ) my_custom_stuff(f) f.close() end Without yield(): expose 2 calls in other library # in some other library def open(filename) ...before code... yield file_descriptor ...after code... end # in your code def do_everything File.open("foo") do | f | my_custom_stuff(f) end end With yield(): expose 1 call in other library
Blocks are Closures A closure is the set of all variable bindings you can “see” at a given point in time In Scheme, it’s called an environment Blocks are closures: they carry their environment around with them Result: blocks can help reuse by separating what to do from where & when to do it We’ll see various examples in Rails
7 END
closure; iteratorblock; iteratoriterator; blockyield() statement; iterator 8 In Ruby, every _____ accepts a(n) _____, but not vice-versa.
9 END
Summary Duck typing encourages behavior reuse “mix-in” a module and rely on “everything is a method call—do you respond to this method?” Blocks and iterators Blocks are anonymous lambdas that carry their environment around with them Allow “sending code to where an object is” rather than passing an object to the code Iterators are an important special use case
Summary (cont.)
12 END
Intro to RSpec & Unit Tests (Engineering Software as a Service §8.1) © 2013 Armando Fox & David Patterson, all rights reserved

  • Left Quote Icon

    Student Picture

  • Left Quote Icon

    Student Picture

  • Left Quote Icon

    Student Picture