Archive for March, 2011

At the beginning of this month I have published a screencast about Elixir. For those who missed it, Elixir aims to provide simple Object Orientation and charming syntax on top of Erlang.

Based on my strong Ruby background, I was asked several times and finally decided to write a blog post about why Rubists should play with Elixir. Granted that most of Elixir’s syntax and a few features like method missing and module eval comes from Ruby, allowing you to achieve similar features when it comes to meta programming. However, Elixir is definitely closer to Erlang than anything else. Single assignment variables, immutability, easy communication between processes, lists, tuples, binaries and OTP behaviors are all available in Elixir. Therefore, you will be able to learn a lot by using Elixir, here are the things I have enjoyed the most learning:

Pattern matching

Pattern matching is one of the features I enjoy the most in functional programming. They provide an easy to extract information from a data structure. For instance, in Elixir, you would write:

[first, second] = [1,2]
first % => 1
second % => 2

You could definitely write something similar using Ruby assignment operator, but the gain in pattern matching comes from the fact you can use them in method signatures and, if a method signature does not match one specific pattern, the next method is tried. For instance, here is a method that iterates through a list of strings and print them:

module Printer
  % This pattern matches a list with at least one element.
  % The first element of the list is assigned to h, the remaining
  % is assigned to tail.
  def print([head|tail])
    IO.puts head
    print(tail) % Recursively calls print with the tail
  end

  % Eventually the list will be empty and the method above
  % won't match, causing this one to match instead.
  def print([])
    % Do nothing, we are done printing items
  end
end

Printer.print ["foo", "bar", "baz"]

Another cool example is a recursive method that checks if a list is a prefix of another list:

module Prefix
  % Iterate both lists. Check if the first element is equal then call itself again.
  % If the first element (i) is not equal, it won't match this method.
  def is?([i|prefix], [i|list]) is?(prefix, list); end

  % If the prefix is empty, is because everything matched, so return true.
  def is?([], _list) true; end

  % Else, return false
  def is?(_prefix, _list); false; end
end

Prefix.is?([1,2,3], [1,2,3,4,5]) % => true
Prefix.is?([0,1,2], [1,2,3,4,5]) % => false

Finally, pattern matching allows us to easily have key-value args, one of the features planned to Ruby 2.0. This examples comes straight from Elixir code (notice that symbols in Elixir start with a single quote instead of colon):

module Record
  def retrieve(name, 'from: file)
    % Implementation ...
  end
end

The fact that neither Elixir nor Erlang provides conditional loops like while forces you to think differently and use pattern matching in different occasions. Thinking differently about a problem that you are frequently solving in Ruby and coming up with a completely different solution is in general a very insightful and enjoying process.

Also, notice that both Elixir and Erlang do tail call optimization, so the methods above will perform nicely while you could get huge stack traces if you implemented such methods in Ruby in a similar fashion.

Single assignment variables and immutability

What I haven’t showed in the example above is that variables in Erlang are single assignment, therefore, the following will raise an error:

[first, second] = [1,2]
first = 10

The above raises a bad match error because, since a value was already assigned to first, the second expressions first = 10 is actually comparing 1 to 10, which obviously fails. The fact variables are assigned just once is what allows us to implement our prefix method above, ensuring the value assigned to i matches in both lists.

Also, both in Elixir and Erlang, objects/data structures cannot be modified in place. They are immutable. Every modification generates a new object/data structure. Immutability removes the shared state internal to the language (you still have shared state if you have to do external operations) and play a key role on Erlang’s and Elixir’s concurrency.

Personally, I have found immutability to be a blessing and a curse at the same time. Mutability is not commonly an issue when working with Rails applications, but while working on Rails itself and other gems, we need to be frequently thinking about mutability. Sometimes you pass an object (like a hash or an array) to a method that modifies it in place and then you have to spend some time tracking how that new element ended up in your object.

When working in Elixir, since everything is immutable, I don’t need to worry about such cases and yes, it feels good! It feels like going from C to Java and then I suddenly don’t need to worry about memory management. However, such benefit comes with an obvious downside that some code just becomes more verbose.

To show this downside, consider a possible create action for PostsController similar to Rails, but where we have rewritten it to consider both immutability and single assignment variables:

def create
  post0 = Post.new(params[:post])
  post1 = post0.set(:published, false)
  post2 = post1.save

  if post2.persisted?
    redirect_to post2
  else
    render :new
  end
end

In such cases, the ORM could likely provided better APIs, but that is a pattern that would repeat over and over again. For instance, modifying the response cookies would require an explicit change in the response object:

response1 = response.cookies.set "tracker_code", "123456"

In any case, just working with a language that provides immutability and single assignment variables is worth the experience. You will learn a lot by trying it out that I could ever mention in a blog post. As pattern matching, it frequently forces you to handle problems through a different perspective which is extremely challenging and rewarding.

UPDATE: As some pointed out in the comments, Elixir can remove single assignment and still play properly with Erlang’s foundations. For this reason, Elixir now allows you to assign to the same variable more than once and has more flexible rules related to the variable scope (similar to Ruby) when compared to Erlang.

Communication between processes

Pattern matching, single assignment variables and immutability provides a good foundation for communication between processes. If you are interested to learn more about this one and see all these things working together, watch the screencast from previous week!

A different Object Model

Elixir has a different Object Model from Ruby. The Object Model is prototype-based like Javascript, in the sense there are no classes, but it is also different from Javascript and Self in the sense an object can still dictate how its children is going to look like, not necessarily being an exact copy from the parent. There is plenty more information about it Elixir’s README, including some other cool features like real private methods (maybe it will also be included in Ruby 2.0?) and local method calls.

You can always learn a lot by using other Object Models and this tip is not restricted only to Elixir. For instance, if you are not familiar with Javascript’s Object Model or other prototype based languages, I recommend you to learn it now!

Just learn

As I mentioned in the screencast and in the README, contributing to Elixir is quite easy because both the Standard Library and tests are written in Elixir itself. Now, imagine that you had to implement something like Ruby’s Set in Elixir. You would not learn about Ruby’s Set more, but also think about the best structure to use, which algorithm would be the best to update the Set and what would be a good API to access those objects.

Besides, there are other basic tools that are required in any language, like packaging system, documentation parser and test libraries that are currently missing in Elixir and you could be the one to implement it!

Wrapping up

I hope I have convinced you to try out Elixir. You can learn much more about the language itself by checking out its README.

Finally, if you need some inspiration to do crazy things, I recommend the Forking Ruby talk by Dave Thomas. As he said, we love Ruby and we are not moving away from it anytime soon, but forking it or trying out new things is a great way to improve the language and its ecosystem, and I hope Elixir helps you think more about that.

NOTE: Elixir has changed since this screencast was made and the code built on the screencast no longer works.

In the last couple of months I have spent some time learning and improving my skills in other languages besides Ruby. This time, I had the opportunity to know Erlang much better and I was impressed by the Erlang VM and the Abstract Syntax Form it provides. As a result of my first experiments with such tools, a new language was born: Elixir.

The main focus in Elixir is to provide a charming syntax and method dispatching on top of Erlang. Most of Elixir’s syntax and a few features like method_missing and module_eval comes from Ruby, allowing you to achieve similar features when it comes to metaprogramming. However, Elixir is definitely closer to Erlang than anything else. Single assignment variables, immutability, easy communication between processes, lists, tuples, binaries and OTP behaviors are all available in Elixir.

This weekend I made a screencast that builds a simple chat client/server with Elixir. In the screencast, you will be able to learn more about Elixir’s syntax and see how easy it is to make communication between processes:

Building a simple chat client/server with Elixir from PlataformaTec on Vimeo.

The code produced in the screencast is also available in Elixir’s repository on Github.

One thing to keep mind though is that the screencast is only for learning purposes. In real life, you would build such servers using one of the several behaviors provided in Erlang OTP. Currently, Elixir supports only gen_server, but adding new behaviors is quite easy and will be done on demand. If the overall reaction is positive, I plan to do another screencast later doing the same example using OTP behaviors.

PS: Sorry about the strong key strokes in the video, but I was using Macbook’s internal microphone to do the audio recording. If doing screencasts becomes frequent, I should probably buy an external microphone or learn how to treat my keyboard better. ;)

There are only two hard things in Computer Science: cache invalidation and naming things. — Phil Karlton

What is cognitive load?

When I had Human-Computer Interaction classes in college, I got acquainted with the concepts of Cognition and Cognitive Load. My teacher showed us a very simple example to explain what are those concepts, compare the following examples:

  1. 551153219421
  2. 55 11 5321 9421

The second example is obviously more simpler to comprehend and also may lead us to think that they are maybe telephone numbers. That means the second example has much less cognitive load, i.e., you need less mental work to give those numbers context and meaning.

What does it mean in code writing?

That also applies to naming things in our projects, and heavily. Imagine a new co-worker in your project having to learn all the names and concepts. If you can ease the burden by naming things well, your fellow colleague will be a lot more productive.

I’ve been working on my Outpost gem and there’s a part on it that verifies your system’s output in order to tell whether the system is failing or not. I called it “hooks”. This is a nice example on how bad naming can affect comprehension of a project.

Let’s give it a little bit of thought. What does “hooks” mean? It means, in computing, something that will be called back eventually. Ok, we got that part right. But what does it mean in Outpost? In order to fully understand the concepts, I have to:

  1. Understand the meaning of hooks in computing (not troublesome, since it is pre-acquired knowledge and it has a broad meaning)
  2. Understand what Outpost does
  3. Understand what a Scout does
  4. Apply the concept of hooks in the context of Outpost since the “hook” concept does not add much value to me
  5. Understand what hooks do in the context of Outpost.

Five “cognitive steps” in order to fully understand what the name “hook” mean in Outpost. But, after a while, during my work at Ruby Mendicant University, Gregory Brown suggested me to rename from “hook” to “expectation”. Expectation is also a common knowledge in computing, but even more, it has a very strong meaning for people used to TDD. So, now, to understand how “expectations” fit in Outpost, I have to:

  1. Understand the meaning of the word “expectation” in TDD
  2. Understand what Outpost does
  3. Understand what a Scout does
  4. Understand what an expectation do in the context of Outpost.

One less step. It is very hard to quantify how much did we gain in this simple name change, but we can feel there’s much less cognitive load involved. If you’re thinking the name you’ve chosen is good, try to think about the steps involved to understand the concept you’re trying to elucidate.

If you need more practical advices, Uncle Bob’s written a whole chapter about naming in his “Clean Code” book. In there lies a bunch of rules and tips on how to improve your naming by reducing the cognitive load involved in understanding code, getting closer to the path of having cleaner code.

Do you have this kind of philosophical thought about code as well? How do you make it practical and what are the improvements you’ve seen in your projects? Please share with us!

A while ago we were working on an application that had an entire version specially created for mobiles, such as the iPhone. This specific application was entirely tested with Capybara, Steak and Selenium Webdriver. Although the test suite wasn’t the fastest one in the world, the web application was very well tested, and to guarantee that we would also be testing the mobile version, we would have to simulate an iPhone user agent accessing the application.

But wait, you might be thinking that we are not able to change browser headers while dealing with Selenium. Capybara has a nice API to define new drivers and Selenium allows us to define different profiles with custom configurations for each driver. Lets see how we can put all this together to handle that:

Capybara.register_driver :iphone do |app|
  require 'selenium/webdriver'
  profile = Selenium::WebDriver::Firefox::Profile.new
  profile['general.useragent.override'] = "iPhone"
 
  Capybara::Driver::Selenium.new(app, :profile => profile)
end

Yup, it’s that simple =). We are creating a new driver for Capybara called :iphone, that will use Selenium with Firefox, but with a different profile, overriding the user agent string. This way you can pretend to your application that you are accessing through a “real” iPhone, by giving the “iPhone” string as user agent. You could also configure an :android driver, for instance, by simply changing the user agent string.

So now, how do we make use of that new driver in our specs? Here comes a simple example:

scenario 'access phone information using a modal box', :driver => :iphone do
  visit root_path
 
  page.should have_no_css "#fancybox-wrap"
  page.should have_no_content "0800 123456"
 
  within("header") { click_link "Telefones úteis" }
 
  within("#fancybox-wrap") do
    page.should have_content "0800 123456"
  end
end

We are just passing the :driver => :iphone option to our scenario. Remember that the latest Capybara versions use RSpec metadata options and will apply the :driver option automatically, changing the current driver to our registered :iphone in this case. For more info please refer to Capybara’s README.

You are now able to configure different user agents based on your application requirements, and test it in a full stack way. How about you, do you have any quick hint on how to test different user agents using another driver? Let us know in the comments :)