Guilhermesilveira's Blog

as random as it gets

Posts Tagged ‘ruby

REST from scratch

with one comment

This is the first post on a series of examples on how to use Rails and Restfulie on the server side and Restfulie and Mikyung on the client side to create REST based architectures.

On this 10 minutes video you will learn how it is possible to make several representations of one resource available on the server side (xml, json, atom and so on) and one line of code access and parse it on the client side.

This video shows how to access those basic REST api’s as Twitters, CouchDB which are based on http verbs and multiple URIs. The following videos shall demonstrate how to access more advanced REST API’s.

If you have any questions, join us at our mailing list.

Written by guilhermesilveira

April 29, 2010 at 8:43 am

Restfulie at RailsConf 2010

leave a comment »

Fabio Akita, from Locaweb, is presenting a session on Restfulie and becoming truly REST in Rails.

With the help of Caue Guerra, George Guimarães, and many others, Restfulie is growing and implementing new features that we still expect from REST client apis.

For those who are going to RailsConf this year and want to create consumer and servicing systems with lesser coupling, do not miss Fabio’s talk.

Everything started when we decided to stop pretending…

Written by guilhermesilveira

February 22, 2010 at 8:55 pm

Posted in restful, ruby

Tagged with , , , ,

RESTEasy: Where did the hypermedia go to?

with 15 comments

Some friends have asked what are the major differences between Restfulie and RESTEasy client frameworks.

Strong coupling and hypermedia awareless

As of today, Resteasy requires you to create an interface mapping every resource operation to a specific method, using @VerbName and @Path annotations to specify the desired target URI.

RESTEasy is ignoring the power of hypermedia content on the client side, thus being level 2 according to Leonard Richardson, and not matching Roy Fielding’s description.

RESTEasy is not Roy’s REST

According to Roy Fielding:

But hypertext as the engine of hypermedia state is also about late binding of application alternatives that guide the client through whatever it is that we are trying to provide as a service.

And any effort spent describing what methods to use on what URIs of interest should be entirely defined within the scope of the processing rules for a media type

Guess what? Java interfaces with @VerbName + @Path annotations means early binding, means an effort trying to describe which methods to use on which URI’s: tighter coupling, less space to evolve your server systems.

Going further:

It is fundamental to the goal of removing all coupling aside from the standardized data formats and the initial bookmark URI.

Restfulie provides a way to access only the initial bookmark URI, everything else is derived from navigating through your resources and its states.

Roy’s dissertation puts his believe quite clear in hypermedia being an important point of the web in chapter 5, his first paragraph: “Representational State Transfer (REST) architectural style for distributed hypermedia systems”.

RESTEasy got it right when it allows the user to access multiple URIs and the http protocol as the application protocol. But it still helps creating strongly coupled systems. Those who use JAXB (JAX-RS required) and fixed xml schemas do not allow server to evolve without prior notice to their clients. Ian Robinson has written about links in his blog and – another option – contract based systems in ThoughtWorks Anthology.

Back in 2007, there was a nice discussion on SOA allowing the users to create strongly coupled systems, where Mark Baker cleared it: SOA is constraintless, therefore one can create strongly and loosely coupled systems.

RESTEasy not supporting hypermedia content by default matches Roy’s definition of unrestful:

In other words, not RESTful at all. REST without the hypertext constraint is like pipe-and-filter without the pipes: completely useless because it no longer induces any interesting properties.

Although RESTEasy supports atom feeds, which is a good point, if the client wants a real hypemedia aware resource, he has to work on the deserialization process on his own.

RESTEasy does not provide the class generation mechanism that Restfulie (both Java and Ruby) provides so end users are able to transverse your resource’s tree and states without prior knowledge of every other URI.

According to Roy, one of the key benefits of the REST archicture style is its visibility through out the entire layered system:

REST is an architectural style that, when followed, allows components to carry out their functions in a way that maximizes the most important architectural properties of a multi-organizational, network-based information system. In particular, it maximizes the growth of identified information within that system, which increases the utility of the system as a whole.

By fixing all URI’s on the client side, along with not supporting hypermedia content by default, RESTEasy provides less information to layers contained between the server and the client: thus less visibility.

Server side

The same issues arrive when talking about the server side: RESTEasy does not provide any default interface for hypermedia content, but JAX-RS default support to JAXB: plain xml. It is up to (good) programmers to know how to make use of hypermedia systems in order to create a loosely coupled system.

Languages

Another key point on Restfulie’s approach is that it is Java-INdependent. Every month we see a larger number of integration software being developed in other languages: Restfulie can already help Java and Ruby developers.

Written by guilhermesilveira

December 3, 2009 at 6:05 am

Posted in java, restful, ruby

Tagged with , , , , , , , , ,

missing_knowledge: dynamically adding ruby methods

with one comment

While creating restfulie we have come across a few issues related to my complete lack of mastery of the ruby meta programming features.

The client’s code (hypermedia aware resource consumer) is based on ruby’s open classes and objects idea: while parsing a xml (or json) format, one can easily add specific methods to that particular object, and that is no news for anyone using ruby, but the interesting bit is that one can do it in several ways, each one with a complete different result.

statically defining methods

The first thought is to define a method for that just deserialized object:

object = self.from_xml
def object.pay
  // execute payment request here
end

This is the easiest approach and works really well if you know which method you want to define. In our case, the name of that method only become available during runtime and it is contained within an string so I can not execute:

object = self.from_xml
method_name = "pay"
def object.method_name
  // execute payment request here
end

In order to dynamically add methods to objects, the simple “def variable_name.method_name … end” path does not sound as a viable alternative.

missing a method?

The second approach was to use the method missing approach. By iterating over the possible state changes/requests of a resource, one can define whether a new method exists or not:

# keeps track of all possible state
# changes and requests
attr_accessor :state_changes
def method_missing(m, *args, &block)
  if state_changes.keys.include? m
    # execute the related http request
  else
    super(m, args, block)
  end
end

Whenever one redefines method_missing, he has to redefine the respond_to? method:

attr_accessor :state_changes
def method_missing(m, *args, &block)
  if state_changes.keys.include? m
    # execute the related http request
  else
    super(m, args, block)
  end
end

def respond_to?(m)
  state_changes.keys.include?(m) || super.respond_to?(m)
end

This is a great (and possibly only) approach to define new methods unknown to the developer at compile time which name is a composition of important strings as with ActiveRecord finders.

The keyword here is new. That’s the reason why method_missings is not the right approach for apis like restfulie. While retrieving a resource from the web, one of its actions might be named destroy, in which case the original destroy method will be invoked, without ever passing through the method_missing once the method does exist.

Appart from that, it is important to notice that this approach is highly valuable for those frameworks which supply dynamic method names for their users as mentioned earlier as ActiveRecord: in those cases, an infinite number of methods is made available for developers.

dynamically defining a method

Become more and more hardcore in the way to define a method, the following step was to check the define_method method. It seems to fit as it would receive a string as the method name and add that method to the object’s class.

class << self
  define_method("pay") do |payment|
    # execute payment here
  end
end

There is one issue here: define_method receives a block as an argument, and blocks cannot receive blocks as arguments in ruby 1.8. It is fine in 1.9, but not in 1.8, so I can not do:

class << self
  define_method("pay") do |payment, &block|
    # execute payment here
  end
end

Another important characteristic of using blocks with the define method, is that it can not access its local context (outter variables), unless you one uses the send method to invoke define_method:

self.class.send :define_method, pay do |payment|
  # access external variables
  # but no body support
end

module eval

The last approach is based on method aliasing. One can evaluate a block of code in a module using the module_eval method:

self.module_eval do
  def fixed_name_method(*args, &block)
    # now i can access the args
    # and the block
    # but the method name was fixed!
  end
end

So we are left with only one task: rename that method from fixed_name to the content of the variable method_name:

method_name = "pay"
self.module_eval do
  def fixed_name_method(*args, &block)
    # now i can access the args
    # and the block
  end
  alias_method method_name, :fixed_name
  undef :fixed_name
end

Note that we also undefined the fixed_name method after creating our desired alias. This is a known path to dynamically add methods to classes bypassing ruby’s 1.8 limitation with blocks receiving blocks as arguments.

Everything would be wonderful just prior to using the api in a multithread enviroment. In this case all those method definitions were added to all existing objects of that class. In this case, the use of instance_eval is indicated.

current method name

At last we come to the last challenge for the client side: once all methods are defined in the same way (within a loop condition) where the evaluation process does not give us access to outter variables, how come we know which method was invoked?

Googling around, the following method can be created in order to discover which method is being invoked:

def current_method
  caller[0]=~/`(.*?)'/
  $1
end

the next step

This is the path we went while creating restfulie as I had no prior hardcore experience with ruby’s metaprogramming techniques. It is clear that using such api allows one to dynamically extend classes and objects in order to achieve that “one extra dimension” of generalization to our code.

Written by guilhermesilveira

November 9, 2009 at 1:00 pm

quit pretending, use the web for real: restfulie

with 8 comments

Resource representation

A simple resource representation in xml could be

<order>
  <product>basic rails course</product>
  <product>RESTful training</product>
  <price>500.00</price>
</order>

It provides information on the order itself, as we are used to. But it lacks providing meta information on anything related to business process: from here, I am unable to go anywhere.

This resource is unable to lead its consumers through possible steps further on a business flow, i.e. creating a payment or cancelling it.

Looking at this resource, it is clear that it is just an usual “structural representation” of something that programmers would code in C: the data and it’s structure: but no possible actions.

Identifying resources

In order to access those resources, one needs to possess its address, its URI.

We use, for example, URIs to identify our courses at Caelum.

The advanced rails training can be accessed through the http://www.caelum.com.br/curso/rr-75-ruby-rails-avancado/ URI and also through http://www.caelum.com.br/curso/rr-75.

Note that there is no need to have an unique URI to resource or resource to URI mapping. In our case, the latter URI redirects to the first one through an http permanently moved response.

Web services

One can understand web services as services which use the web as its infrastructure. The basic step to create a web service is to use http requests to act.

Typical SOA applications will stop its evolution and its use of the web infrastructure here, not profiting from everything else that the web provides.

Resources accessed through the web

Once I have an URI in my hands, and a web service that provides me the resource representation through a web request (typically a GET request), one receives as output the requested resource representation.

Using different HTTP verbs and analyzing the request and result headers and codes, one makes and profits from further usage of the web infrastructures such as caching proxies and fault tolerance assurance due to idempotent methods.

Frameworks and applications, like the one from the spring blog, which provides the first level of web infrastructure usage would be called resource based web services (RBWS) if they were not lacking the use of the most common web aspect: hypermedia.

According to Roy Fieldings, “REST is defined by four interface constraints: identification of resources; manipulation of resources through representations; self-descriptive messages; and, hypermedia as the engine of application state.”

Web service based CRUD

Web service based cruds are those ressemblingthe spring tutorial, which maps URIs to resources and allows the usage of different HTTP Verb, headers and return codes to sign actions and return values.

Although being a sign of better usage of the web in order to create web-based services, it is still missing the very best part of our every day life: hyperlinks and hypermedia content.

Doing CRUDs is an everyday task, and doing service based CRUD implementation is a nice and cute functionality that frameworks as rails, spring and vraptor allows us to do.

According to Leonard Richardson model, one can roughly categorize his usage of the web infrastructure based on which use one makes out of it. CRUD over the web is just the first step, and hypermedia support is the following one.

Hypermedia aware resources

Resources supporting hypermedia provide consumers the next steps to follow on an application business flow. It allows the consumer to change the application state as web requests are stateless.

The following code shows an example of xml+hypermedia representation of the same order seen earlier:

	<order>
		<product>basic rails course</product>
		<product>RESTful training</product>
		<refresh>http://www.caelum.com.br/orders/1</refresh>
		<update>http://www.caelum.com.br/orders/1</update>
		<pay>http://www.caelum.com.br/orders/1/pay</pay>
		<destroy>http://www.caelum.com.br/orders/1</destroy>
	</order>

Note that this path is a simple yet powerful way of interacting with your clients. Although its a valid option, one can make use of the w3c atom format as nowadays there are hundreds of important tools atom-aware:

<order>
  	<product>basic rails course</product>
  	<product>RESTful training</product>
  	<atom:link rel="refresh"
          href="http://www.caelum.com.br/orders/1"
          xmlns:atom="http://www.w3.org/2005/Atom"/>
  	<atom:link rel="update"
          href="http://www.caelum.com.br/orders/1" 
          xmlns:atom="..."/>
  	<atom:link rel="pay"
          href="http://www.caelum.com.br/orders/1/pay" 
          xmlns:atom="..."/>
  	<atom:link rel="destroy"
          href="http://www.caelum.com.br/orders/1
          xmlns:atom="..."/>
</order>

Cutting a new gem

Both Jim and Savas have commented on the client simple javascript+html resource+hypermedia (restful?) client that we have created so one could easily test a restful application online.

So me and Caue Guerra at Caelum were ready to move to the next step: getting resource+hypermedia support to rails applications.

SOA applications, due to strange and dark forces, typically demand dozens of developers to built something complex and hard to maintain.

With this in mind, we have developed Restfulie, which is a rails based gem.

It works both on the server and client side making it easier to provide and consume such restful resources.

Requesting a resource

A resource based web services provider – another long name for a partial rest implementation based on roy’s dissertation – can access a resource through the api:

 order = Order.from_web ‘http://www.caelum.com.br/orders/1’

Now, one can request its content

 puts order.products

or even invoke those “methods”:

 order.pay payment
 order.cancel
 payment = order.check_payment_info

All those three methods are remote invocations (never forget it!) that access the server executing POST, DELETE, PUT and GET operations, serializing and deserializing xml+atom content (or json, …).

Thats about it. You have consumed a resource representation and acted upon it in two lines of code, moving your resource to another state on your business flow.

Meanwhile, on the server side

Those who want to provider RBWS can easily do it using restfulie by implementing the method following_states as follow:

class Order
 def following_states
 states = [ { : orders, :action => :show } ]
 states << : orders, :action => :destroy} if can_cancel?
 states << : orders, :action => :pay, :id => id} if can_pay?
 states
 end
end

And in a 6 lines long method, one has implemented a full RBWS provider: all invocations to to_xml and to_json will serialize atom or rel based links to those state transition services.

Live examples

You can try the server side ordering application online and a sample client side application live at heroku.

In order to fully test those systems, follow the “Try it online” directions on the Restfulie website.

Concluding

This post gives a basic idea on resources, web based services and how one can really use the web to profit from its already existing infrastructure.

While some RBWS providers already use all this knowledge, most of the frameworks that we see today focus on “restful” meaning “accessing a resource through its URI and http verbs”. There is more to the web than just getting, posting and uris. There is a whole world hidden behind links so… let’s quit pretending and start using the web infrastructure for real.

Written by guilhermesilveira

November 3, 2009 at 6:23 pm

Posted in restful, ruby, soa

Tagged with , , , , , ,

Fractals in cloud computing with Google App Engine

While studying math methods as a minor in my applied math course, I had a mentor, Eduardo Colli, who helped me teaching the math requirements to implement a desktop based discrete dynamical systems software, Pulga. In the dynamical systems area – usually non-linears – people started talking about caothic behaviour of particles and one of the most famous systems is the Lorenz attractor.

atrator de Lorenz

As most of those algorithms can be run concurrently, we have decided to send it to Google App Engine in order to test it in a highly demanded way, enjoying the benefits of running in a cloud enviroment to generate results quicklier, as in a cluster, but using the http and internet infrastructure as a cluster: Google App Engine would help not only with scalability and availability but also improving performance. The basic algorithm iterates a billion+ times through some mathematical functions. In the traditional, desktop, approach, this is run in a single thread, in a code which resembles:


for(int time = 0; time < 60*60; time++) {
  for(int initial=0;initial < 1000; initial++) {
    x0, x1 = intiialCondition[initial];
    for(int iteration = 0; iteration <= 100000; iteration++) {
      x0, x1 = calculate(x0, x1);
    }
  }
}

The code above is much simples than the original source, but illustrates how slow the software can be. A simple execution would be finding an attractor’s basin of attraction, a task which would take between 2 to 5 minutes to draw the Henon map.

In our machines, Henon’s bifurcations diagram, as the above image from wikipedia, would take 5 minutes:

diagrama de bifurcação do mapa de henon

At first sight, those results seem to be achieved in a short period of time, but once Henon’s map relies on two parameters, if we wish to create a movie by scanning one of those parameter’s domain (considering it the time), a one minute video would take about 3 hours of computer time. In real situations, with different strange attractors, some movies would take more than 7 hours to be created.

In order to run it in a parallel way, the new application has 3 parts: a client which sends a single request, a server written in ruby which receives this request and dispatches hundreds of requests to the cloud, using the well known http protocol, returning parts of the graphic.

The client will request the server for colors to paint the image through ajax/jsonp. The server app sends all requisitions using non blocking io and could be somehow enhanced through the use of ruby 1.9 fibers. This NIO api from ruby is similar to Java’s NIO.
Once the requests get to the Google App Engine, it will basically run a code quite similar to the original desktop client core. After each execution, those numbers are returned to the ruby server, which concatenates data and generates the final result.

Initial tests have shown response times 51 faster than running on a single client by using 100 parallel http requests to Google App Engine:

100 random points iterations per request

Requests Total time (seconds) Iteration time (miliseconds)
local 6 16.6
1 3 33
10 6.4 156.25
50 14 357
100 17 588
200 23.55 849

Using memcached, Google App Engine’s cache api, we achieved even faster results:


CacheFactory cacheFactory = 
       CacheManager.getInstance().getCacheFactory();
cache = cacheFactory.createCache(Collections.emptyMap());
String result = (String) cache.get(script);
if (result != null) { ... }

This simple modification helped us achieving 93 times faster response running in ~100 machines!
Of course, some machines did not answer properly and the server could deal with that by just using standar http protocol and further requests.

We could improve it even more by using the HTTP/internet provided infrastructure: proxies. By correctly configuring our proxies, many of those requisitions achieved the same task, resulting in absolutely amazing responses. That is why RESTFul webservice’s gurus consider Squid a great choice over a giant ESB system.

hiperboloide

For those who are interested, here are some examples of 2d dynamical system maps which can be easily implemented.

Batch processes and reports are tasks which usually take some long time to run and many of those could be breaken in many parallel processes.We, developers, will soon be running all our code in those cloud systems: not only in order to achieve higher and higher scalability and availability goals, but because this elastic infrastructure allows hosting companies to have less costs. Knowing how to profit from those systems is the role of a developer. Non-relational databases and languages with different approaches to concurrent programming than the traditional java/pthread one, are showing to be excelent ideas to chase.

Written by guilhermesilveira

September 4, 2009 at 5:27 am

Posted in java, mathematics, ruby

Tagged with , , ,

Comprehensible languages x Expressive code x The other side of the world

with 2 comments

One reason to care about expressiveness

Most developers agree nowadays that mantaining software is an important task, either refactoring it as a task is completed or one year later when new functionalities are added, the cost of maintainability should be kept as low as possible in most cases.

Mentioning most cases, i automatically exclude pieces of code or complete software written by any group who intentionally write in such a way that no common programmer is capable of understanding. I wrote this article only for those situations where the way you express your intentions becomes important in order to others – or even yourself – to understand it.

Lack of communication: a geek’s problem

Expressing ourselves was never the best of our abilities. As a stereotypical geek, I am a shy person whould only be able to freely express my intentions after a couple of beers. Being an uncommon practice to communicate with other type of people (not so much logical-driven thinking), does not give a geek a lot of knowledge on how to express his ideas in a more sensitive and human way.

Being also a hard task on its own to develop code without abusing from logical structures and tricks, everything contributes to make it a very difficult job for developers to write comprehensible code.

So why does your code looks comprehensible right now, but anytime later, completely uncomprehensible? And you just start to hate what you did? After refactoring it becomes, again, more comprehensible?

Its quite uncommon for one to get ideas quite clear in one’s head, prior to putting it on paper. How many times have we had those really bright ideas, and as soon as we write them down, the idea does not seem so clear? As we talk about it with other people, and come back to the same piece of paper, we can make our ideas more clear. It does not happen only with ideas being written on paper.

Artists face the same problem while painting, they do not know exactly what to paint, and may come back again and again in order to improve something they thought were ok, but later realized that was still not what they wanted to communicate through their art. The same thing happens with writers too, a book or an essay is not simply written. It is proof-read, re-writen, until the text passes to the reader the original idea that the writer wanted to pass.

Even great communicators may not achieve their best result on passing on their message on their first attempt. Why would a developer, sometimes a geek with dificulties to express himself as a person, would be able to express his idea in a great way at all?

So far, we have a few ideas on why is that expressing our ideas is important (maintaining software) and why is it hard for us developers to express our ideas (cultural issues, lack of practice, continuous improvement required).

Being born in a family of teachers and educators, I learned back home how important it was the ability to forget our current knowledge and talk to someone (express ourselves) as if the other end-point has no knowledge at all. This is the most important quality of a teacher… being able to level himself in such a way that his knowledge is exactly the same – nothing more – than his students.

Mindnote: it was not enough to lose my shyness, only enough to allow me (maybe) help some other people.

Being able to think in advance that our readers do not have the same knowledge that we do helps us to write (anything, not just code) text that can be easier understand by them. That is just a hint on the mindset one may have while writing.

Enough about communication skills, let me talk about what has been my passion for the past 2 years.

Koreans and japaneses

I still ask myself how do koreans and japeneses feel when they get a first glance at western grammar. Both languages share the same structure which is based on the “subject objects verb” sequence, in a completely different fashion of our’s commons “subject verb objects”. Furthermore, they share the notion of descriptive verbs and korean (I do not know any japanese) has suffixes to identify those objects in a much similar way that most languages uses prepositions or (german/latin) declinations.

We can illustrate the basic difference with a single sentence, when I would say “I went home late”, koreans would “I late home went”: “저는 늦게 집으로 갔어요”. Easy right?

Lets pick a daily life example with two phrases: “because i had no money with me, i went to the bank”. In korean? “with me money i had none because i to the bank went”. This single order change makes it really hard for us westerns to learn korean. But what about imperative sentences?

“you 1st room from 5th room until big room breakfast with rent!”

Maybe even for non-linguistics developers/fans, it might be easy to understand meaning hidden in the above paragraph. But might this change of order help us write better code? Should we start asking koreans and japaneses? Will it make it possible for me to write code which people will understand easier?

In the following paragraphs I will show what my mind went through to find out that:

  • I do not know the answer because korean is not my native language
  • It might be too late for korean developers to answer this question as they are already used to the way of thinking the programming languages oblied them to think
  • there is room for programming langauge improvement to allow us writing more expressive/easier to understand code

By the way, for those (if any) who did not understand, I gave an order to rent a big room checking in on the 1st and leaving on the 5th with breakfast inclusive.

Symbols x Language

Due to the obvious nature of this post, I am making no comments on languages as perl and haskell which appeals to (too many) symbols as a way to express one’s intention. Symbols are really great for defining abstract ideas. Symbols are hard to teach, to learn and to understand. And if someone makes just a small change to the set of symbols understood, your life becomes hell. Those languages go completely against what I – as a teacher/educator – think this is the right way of communicating one’s intention – in our case, express our code.

Symbols might achieve more results with less effort, but at the same time symbols are harder to understand. I will be glad to change my mind the day someone teaches a common person how to code in one of those languages faster than teaching someone how to code in ruby.

Our aim is not to create complex software or in cases where developing faster is not the only issue in game but keeping the code understandable is a issue, “too-much-symbols-based” languages do not offer what other languages do.

Coding, “korean style”?

This section will describe the problems I have faced while trying to do something similar to the way korean grammar expresses its sentences.

Because most languages were written with a western language mindset, they all only offer one way of declaring parameters, which describes them after what we recognize as the action being invoked. For example, in most languages, the rent order would be defined and invoked as:

invocation:
bigroom.rent (from: 1st, to: 5th, for: me, with: breakfast)

definition:
rent date from date to client for boolean with

I have chosen some type-definition-required-based language so the definition looks a little bit more natural to human eyes (yes, rent from to for with would be lesser compreensive).

But what if I wanted to use a language that values objects over actions. If you think about parameters as the objects, the object in which methods are invoked as the subject and methods/functions as verbs (this supposition might not always apply), one can see that our commonly used languages do value actions over objects. Actions define which objects they receive, instead of parameters defining which actions can be taken.

One simple change would be to write the invocation in a koren style:

invocation:
bigroom 1st부터 5th까지 ... rent

Soon, one starts to notice that 부터 (from), 까지 (until), 에서 (at) etc is not actually the variable type definition but something else! It is not the name of the variable itself, it is something else! What? Let’s come back to it really soon… but first,

What would be if things were completely written the other way around? In a way that parameters itreact with themselves and define the actions that can be executed with them? I have absolutely no idea how to define actions, given parameters, therefore I just left this question open and tried to think about other ways to improve what I write.

Language garbage

Note that if I define being garbage anything else that I would not require to express my idea to another human being, the above example if just full of it. Let’s remove some of the clutter:

invocation
bigroom rent from 1st  to 5th for me with breakfast
definition:
rent from checkin to checkout for client with optionalBreakfast

First of all, both sentences are much more natural, although the invocation could be written in a more imperative way as “rent the bigrrom from 1st to 5th for me with breakfast”, let me keep my exposition within OO based-languages.

We can also notice that I have removed type definition and added something else… that is still unclear what it is. And this is exactly what I think that we might try out. That is what I pointed out in the previous section.

Programming languages which do not allow us to invoke methods by using the parameter’s names are much less expressive than the ones which allow us (i.e. ruby):

invocation not using parameter names:
bigroom.rent(Date(1,7,2009),Date(5,7,2009), guilherme, true)

What??? What is the first, the second, the third and the fourth parameters? It is quite clear that the above piece of code lacks something in order to communicate what it really does. It lacks the parameter names (lets call them the parameter ID’s now, ok?).

But how do Java developers write expressive code without using named parameters? Easy, just extract variables!

invocation with “named” args:

from = Date(1,5,2009)
until = Date(5,7,2009)
client = guilherme
withBreakfast = true
bigroom.rent(from, until, client, withBreakfast)

Extracting variables was the refactor chosen in order to solve the problem or language limitation did not allow us to do it: use identifiers to our parameters. Now let’s see another example with a language which would accept parameter ids:

invocation in a language which uses named parameters:

bigroom.rent(from=Date(1,7,2009), until = Date(1,7,2009), client=guilherme, withBreakfast=true)

Its clear the same solution as with the Java language, but written in only one line. The disadvantage is that the line gets longer – and therefore more complicated. The advantage is that a language which obliges parameter ids to be passed forces our code to be more expressive and comprehensible. Unfortunately ruby does not (yet?) forces uses to write this way.

Note also that forcing parameter ids, one removes the need for creating tiny objects for developing small dsl apis. But this approach would not be recommended in a api which should be easily extended because tiny objects (used through their interfaces) are easier to extend.

Lets go further? The korean way of writing sentences showed me something that even the english approach does misses. Forcing parameter id’s was the first move and improves the ability to write invocations that are easier to comprehend. But what about the function/method definition? Can we improve something there?

current invocation:bigroom.rent(from=Date(1,7,2009), until = Date(1,7,2009), client=guilherme, withBreakfast=true)

current definition
rent from checkin to checkout for client with optionalBreakfast

But look, first of all the definition includes no parameter type definition, but does include the parameter id and something else. What is that something else?

If i rent, I have a checkin date, and the checkin date is identified with the from id. Therefore each parameter has actually “two unique identifiers”. An internal one which is used within the action/function/method definition, and an external one to be used when invoking the method. Our code would be implemented somehow as:

define rent from checkin to checkout for client with optionalBreakfast as

bookings add new Rent from checkin to checkout for client with optionalBreakfast

end definition

The above implementation invokes the Rent construction definition and invokes the add method in the bookings list.

Mindnote: symbols for adding items to lists and so on are, again, symbols, therefore not the most comprehensible feature of mankind.

Is it clear? Clear enough? Clearer than some other approaches? I can see it as a better way of writing codes but unfortunately I do not know any language so far that can help me this way. Let me try it a little bit further with a conditional statement:

if amUnavailable from checkin to checkout
then complain about unavailability
otherwise bookings add new Rent ...

Do I need to explain what is written here? Well, now ask your grand mother if she understands the above protocol. And yes, do not call it “logic” or “code”, call it a protocol… non-programmers would get it easier if you call it a procedure or protocol instead of “logic” or “code”… just a matter of names but allows people to better understand what you are saying.

Some languages would require the type definition, I understand those languages have reasons for thinking this is the best approach (yes, i am still a Java programmer and prefer defining variable types) and this could still be implemented in a more compreensible way using the above mentioned approach.

REST, URIs and experiments

Should URI’s express what they represent? What about the limitation on the Http methods when I am using web sites for human (not machine-to-machine) iteraction? That is what has been keep my mind busy yesterday, and will probably stick to mind while on the plane to Korea… it is just a pity I do not have access to Korean children so I could get their feedback on computer programming before they get a grisp of english.

Comprehensible languages

Summing up, I believe the code would be much more expressive and comprehensible if the language we use force us to use parameters with ids and IDEs helped us by given those names and not allowing us to change them. Simple changes, that would perhaps help others understand what we wanted to say.

Comprehensible languages would be programming languages which allow us as human beings to express ourselves in a way that we can understand each other instead of through abstract logical symbols.

Anyone willing to implement such language?

So what does Korea has to do with all this? Well, I always prefer telling people the history on how I come up with any idea.

Written by guilhermesilveira

July 12, 2009 at 11:51 pm