Sonntag, 29. Juni 2014

Do the Proc! ... a Ruby closure

First of all, a Proc (short for procedure) is technically nothing more than a block. And since a block is a Ruby way of implementing a closure, a Proc is a closure too. That means a anonymous function, which stores its environment on creation time and has access to those referenced variables, even when invoked outside.
The original code example using a simple block:
class Array
  def aggregate
    self.inject(0) { |result, number| result += yield(number) }
  end
end
and using it like:
numbers = [1, 2, 3]
numbers.aggregate { |number| number ** 2 }
=> 14
but if the very same object has to return the same result somewhere else too, the logic (block) has to be duplicated:
numbers.aggregate { |number| number ** 2 }
=> 14
Procs solve this issue, because Proc objects can be saved like:
squaring_proc = Proc.new { |number| number ** 2 }
=> #
The Array#aggregate has to be made ready for Procs by adding the new parameter and sending the Proc#call message:
class Array
  def aggregate block
    self.inject(0) { |result, number| result += block.call(number) }
  end
end
aggregating it the Proc way:
numbers = [1, 2, 3]
numbers.aggregate squaring_proc
=> 14
and this Proc object can be reused as many as ...
The domain of a Proc is:
  1. wherever a block is required
  2. the block logic has to be duplicated (reused)

Further articles of interest:

Supported by Ruby 2.1.1

Sonntag, 22. Juni 2014

Block it! ... a Ruby closure

A closure is a anonymous function together with referencing environment and it has access to those non-local variables even when invoked outside.
The Ruby block is one of the Ruby ways of implementing a closure. And it is the most trivial.
Its domain is:
  1. Preventing code repetition by extracting its unique part.
  2. Moving logic into objects (it is about responsibility).
  3. Hiding internal object design by restricting its API to be more qualified.
The original code example:
class Stack
  attr_reader :store
  def initialize *elements
    @store = elements
  end
end
is a simple stack class, offering a reader method, which returns a collection of objects. It can be used like:
stack = Stack.new 'Ruby', 1, { language: 'Ruby' }
stack.store.map { |element| 
  element.to_s + ": " + element.object_id.to_s
}
=> Ruby: 14531380
   1: 3
   {:language=>"Ruby"}: 14531340
stack.store.map { |element|
  element.to_s + ": " + element.public_methods.join(', ')
}
=> Ruby: <=>, ==, ===, eql?, ...
   1: to_s, inspect, -@, +, ...
   {:language=>"Ruby"}: rehash, to_hash, to_h, to_a, ...
The code duplication is obvious. Not tot mention the exposure of the internal storage. Furthermore the public reader method can be more specific about its intention:
class Stack
  def initialize *elements
    @store = elements
  end

  def stringify
    @store.map { |element|
      element.to_s + ": " + yield(element).to_s
    }
  end
end
The reader method has been removed and the new stringify method offers a stringification of the stack object. The key word yield is a placeholder for the block, where it is processed. The iterating element is assigned to yield as the parameter (the number of parameters for yield in general can vary from zero to whatever).
The stringifying messages to the stack can be sent like:
stack = Stack.new 'Ruby', 1, { language: 'Ruby' }
stack.stringify { |element| element.object_id }
=> Ruby: 13656480
   1: 3
   {:language=>"Ruby"}: 13656440
stack.stringify { |element| element.public_methods.join(', ') }
=> Ruby: <=>, ==, ===, eql?, ...
   1: to_s, inspect, -@, +, ...
   {:language=>"Ruby"}: rehash, to_hash, to_h, to_a, ...
The messages results are analog to the original example, but the refactored code is more intentional and DRY.

Supported by Ruby 1.9.3

Sonntag, 15. Juni 2014

Privatize Javascript variables with closures!

Some developers consider Javascript as a poor designed language. Maybe it is true. Though the bias oftentimes mixes bad practices with the language design. One of the bad practices is to reveal "private" variables as real public. For example:
function User(name){
  this._name = name
}
User.prototype.name = function(){
  return this._name
}
The User object shall contain a private variable name. One of the accepted notations is to begin the private variable name with underline character ("_") like "_name".
That still does not make the variable private yet. The HTML:


and some Javascript, which binds the behaviour onto the button:
$(document).ready(function(){
  $("#20140615").click(function(event){
    var user = new User( $("#20140615_text").val() )
    user._name = user._name.split('').reverse().join('')
    alert(user.name())
  })
})
Please note, that it is still possible to change the "private" value in _name from outside. Finally the users name is printed for inspect. Examine it:

Refactoring

The original User can be refactored to have a real private variable:
function User(name){
  this.name = function(){
    return name
  }
}
with the behaviour attached to the DOM:
$(document).ready(function(){
  $("#20140615").click(function(event){
    var user = new User( $("#20140615_text").val() )
    alert(user.name())
  })
})
There is no way to modify the value of the name variable.
The concept behind is the oftentimes underrated closure (also read: Have a Javascript closure!). It "freezes" the name variable in the moment, the user object was instantiated.
Please note that using closures for private variables is pretty static, but secure.
Try it:

Further articles of interest:

Supported by jQuery 1.10.2

Sonntag, 8. Juni 2014

Have a Javascript closure!

A closure is an important feature of the Javascript language. Basically a closure is an inner function that has access to the outer (enclosing) function’s variables. In other words, the function defined in the closure 'remembers' the environment in which it was created.
Consider the following outer function (initNames) containing an array (names) and an inner function (pushName):
function initNames(){
  var names = []
  function pushName(name){
    if(name.length > 0) names.push(name)
    alert(names.join(', '))
  }
  return pushName
}
Calling initNames initializes the array names and defines the function pushName in the scope of its enclosing function initNames and returns the same. That inner function pushName expects one parameter for pushing it into the names array (if it is not blank) and alerts all stored names.
The closure pushName can be used like:
$(document).ready(function(){
  var pushName = initNames()
  $("#20140608").click(function(event){
    var textInput = $(this).prev()
    pushName( textInput.val() )
    textInput.val('')
  })
})
and the HTML:


After the DOM was loaded, the defining function initNames returns the closure and assigns it to the variable pushName. And that is the key point. While initializing the closure, it has three scope chains:
  1. it has access to its own scope (variables defined between its curly brackets)
  2. it has access to the outer function’s variables
  3. it has access to the global variables
Furthermore a click event is observed to the button, which picks the input value and assigns it to the closure function pushName.
Try it out yourself:

Although only the inner function pushName was called, it has access to its outer function's variables.

Further articles of interest:

Supported by jQuery 1.10.2

Sonntag, 1. Juni 2014

Meaningful Ruby blocks: do...end vs. {...}

Ruby blocks are the things that do something and can look like:
[1, 2, 3].inject(10) do |sum, number|
  sum += number
end
=> 16
or can have curly brackets:
[1, 2, 3].inject(10) { |sum, number|
  sum += number
}
=> 16
The only syntactic difference between both is the higher precedence of the {} (curly brackets) compared to do...end blocks. And as a side note therefore this is syntactically wrong:
[1, 2, 3].inject 10 { |sum, number| sum += number }
# SyntaxError: compile error
while this one is correct:
[1, 2, 3].inject 10 do |sum, number| sum += number end
=> 16
Besides that meaningless syntactic difference, using only one over the other misses the chance to write meaningful blocks.
Even using the convention to use {} (curly brackets) for one liners and do...end blocks for multi liners does not add any more sense to the code. Everyone can distinct between a one liner and multi liner without that convention. It is just meaningless noise.
But you can add sense by using {} (curly brackets) for functional blocks and do...end blocks for procedural blocks.
The primary purpose of functional blocks is to return a value:
[1, 42, 1024].map { |number| number.to_s.rjust(4, '0') }
=> ["0001", "0042", "1024"]

Dir.glob('*.txt').inject('') { |text, file_name| 
  file = File.open file_name, 'r'
  text << "#{file_name.chomp('.txt')}:#{file.read}"
}
=> "en:Hello! fr:Salut! es:Hola!"
whereas the primary purpose of procedural blocks is to change the state of the system in some way:
numbers = [1, 42, 1024]
numbers.map! do |number| 
  number.to_s.rjust(4, '0')
end
=> ["0001", "0042", "1024"]

Dir.glob('*.txt').each do |file_name| 
  file = File.open file_name, 'w'
  file.write file_name.chomp('.txt')
end
=> ["en.txt" , "fr.txt", "es.txt"]
Both examples look like doing almost similar things. Especially the first example (Enumerable#map and Enumerable#map!) does the same task inside the block, but differs in the way it effects the "outer world". Enumerable#map! not only returns the result, but also changes the state of the numbers array itself.
The second example (Dir#glob) opens a bunch of files in both versions. But while the first one only reads from each file and returns a string, the second writes to each file. And that is exactly the point.
Some points, why this convention makes totally sense:
  1. No need to change the block style from {} to do...end or vice versa, when the number of lines change
  2. Visual cue about the intent of the code that wouldn’t otherwise be there (quick information if the block has side effects or not)
  3. Method chaining onto a functional block (curly brackets) is quite natural (read Chain your Ruby methods!)
And like anytime: a convention is not a rule. It is just a matter of a good coding style.
A big salute goes to Avdi Grimm and Jim Weirich for bringing up this convention.

Supported by Ruby 2.1.1

Chain your Ruby methods!