Prototypes in Io language 0

For the last couple of days, I have been going through the “Seven Languages in Seven Weeks” book, by Bruce Tate. The second language of the book is Io, a programming language unknown to me before I picked up the book.

One of the challenges of the book, was to create a prototype for a two-dimensional list, and implement a method to return the transpose of the list. We will see how this can be very elegant under Io’s prototype based paradigm.

In Io, everything is an object, and you can interact with the objects by sending messages that correspond to slot names. Here is an example:

TwoDimList := Object clone

In this simple line of code, we send the message clone to the root-level object Object which returns a new object, which we assign to TwoDimList. Objects are simply collection of slots, that can hold other objects (a method is an object as well). Lets send a message to our newly created object, to check its slots:

TwoDimList slotNames
==> list(type)

As you can see, we have one slot named type. One might wonder, at this point, where did the slotNames message came from. Our TwoDimList object does not have a slot with that name, so he just forwards the message to the prototype from which he was created. If we send the type message, to both Object and TwoDimList, we get the following:

Io> TwoDimList type
==> TwoDimList
Io> Object type
==> Object

So, in practice, we have created a new type, by using the clone call. Lets make another:

twodimlist := TwoDimList clone
==>  TwoDimList_0x263f160

Now, we have created another Object as before, but there is a subtle difference:

Io> twodimlist slotNames
==> list()
Io> twodimlist type
==> TwoDimList

So, our twodimlist has no type slot, which means that it will forward the message to the prototype from which he was created. That is how we distinguish new types from instances of types in Io. By convention, if an Object begins with a capital letter, then Io will assume it is a new type, and add a type with its name. Otherwise, it does not.

Now that we have created a new type for our two-dimensional list, and an instance of it, we need to add some behaviour to it. In other words, we need to add slots with methods that allow us to create a two-dimensional list, and set/get values within it.

Fortunately, Io already provides a List prototype that we can use. We will consider a two-dimensional list to be an Io primitive list of lists. Here is the code:

TwoDimList dim := method(x,y,
    self dimx := x
    self dimy := y
    self matrix := List clone
    for(i, 0, x-1, 1,
        row := List clone
        for(j, 0, y-1, 1,
            row append(nil))
        matrix append(row))
    return matrix)
 
TwoDimList set := method(x,y,value,
    row := matrix at(x-1)
    row atPut(y-1,value))
 
TwoDimList get := method(x,y,
    row := matrix at(x-1)
    return row at(y-1))
 
TwoDimList print := method(
    for(i, 1, dimx, 1,
        for(j, 1, dimy, 1,
            value := self get(i,j)
            "#{value} " interpolate print)
        "" println))

Here is where Io starts getting really powerful: we are adding new slots to an object, at runtime, which will allow us to do some sophisticated programming.

The dim method will take two parameters, corresponding to the list dimensions, and store them into two new slots of the TwoDimList object (dimx and dimy). Our two-dimensional list will be stored in the matrix slot, and the two for loops will initialize all values to nil.

The set and get methods are also pretty simple. The set will receive two coordinates and a value to store there, while the get will retrieve the value at those coordinates. I am also considering that my two-dimensional list has coordinates starting in “1″, while the primitive list has coordinates starting in “0″.

For this exercise, I have also implemented a print method that will go through the list and print all the values, with a new line each time we change to another sub-list. Therefore, the following code:

twodimlist dim(3,4)
 
twodimlist set(1,1,1)
twodimlist set(1,2,2)
twodimlist set(1,3,3)
twodimlist set(1,4,4)
twodimlist set(2,1,5)
twodimlist set(2,2,6)
twodimlist set(2,3,7)
twodimlist set(2,4,8)
twodimlist set(3,1,9)
twodimlist set(3,2,10)
twodimlist set(3,3,11)
twodimlist set(3,4,12)
 
twodimlist print

Creates the following output:

1 2 3 4 
5 6 7 8 
9 10 11 12

Now, how do we create a transpose of a two-dimensional list? From wikipedia, we know that the transpose of a matrix has the rows of the original matrix as its columns. So, we do:

TwoDimList createTranspose := method(
    transposed := self clone
    transposed matrix := self matrix clone
    transposed dimx := self dimy
    transposed dimy := self dimx
    transposed regularGet := self getSlot("get")
    transposed get := method(x,y,
        self regularGet(y,x))
    transposed set := method(x,y,value,
        row := self matrix at(y-1) clone
        row atPut(x-1,value)
        matrix atPut(y-1,row))
    transposed)

Now, this is where we begin to really lift the power of Io slots and prototypes paradigm. We begin by creating a new object, as before, by cloning the existing one. Now, we know that the transpose will have its dimensions reversed, compared to the original two-dimensional list, and we assign them as such.

As the transposed matrix has the rows of the original matrix as its columns, we simply override the get slot, in order to reverse the order of the arguments! We do this by cloning the original method into the regularGet slot, and store a new method on the get slot that invokes it, with arguments reversed! At this point, at least for reading purposes, we have just created an abstraction that “creates” a transposed matrix in O(1) time, simply by redefining slots.

Now, when it comes to the set method, things get a little tricky: at first, I tried to simply invoke the set method, with arguments reversed, but there is catch: as we haven’t actually cloned the sub-lists inside the matrix, so the set modified the existing matrix, resulting in a leak of our abstraction. So, I had to guarantee that the sub-list was also cloned, and put into the transposed matrix, leaving the original one intact.

Lets try to create, and print our transposed instance:

transposedlist := twodimlist createTranspose
transposedlist print
1 5 9 
2 6 10 
3 7 11 
4 8 12
transposedlist set(4,3,13)
transposedlist print
1 5 9 
2 6 10 
3 7 11 
4 8 13
twodimlist print
1 2 3 4 
5 6 7 8 
9 10 11 12

As our print slot relies on the get slot to retrieve the values, no changes to it are necessary! I am looking forward to learn even more.

A new gem: simple grep in Ruby 0

At the moment, I am going through the book “Seven Languages in Seven Weeks” by Bruce Tate. It has been great fun and good brain teasing so far. One of the challenges, was to implement a grep in Ruby (simplified version: given an expression and a file name, print the lines on which the expression is found). How many lines of code would that take? Seven, with a blank line included, and the plus of printing line numbers as well:

def grep(expression,fileName)
    File.open(fileName,"r") do |aFile|
        aFile.each_line {|line| puts "#{aFile.lineno} : #{line}" if Regexp.new(expression).match(line) }
    end
end
 
grep(ARGV[0],ARGV[1])

Summary of how it all fits:

  • By using Ruby blocks, we don’t actually need to close the file or flush anything. The File.open call invokes the block between the do and end statements, passing the file as a parameter. When the block exits, the file is automatically closed
  • Inside the block, we use the each_line iterator to go through each line of the file, passing the block in { } to be executed. This block is like an anonymous function that takes each concrete line as a parameter
  • Finally, inside the block mentioned in the previous point, we print each line number by accessing the method lineno of the file description, as well as the line itself, if we have a match of the passed expression

And a little example output, using the following file:

Hello
World
This
is
Sparta!
 
$ grep Sparta testfile.txt 
Sparta!
 
$ ruby grep.rb Sparta testfile.txt 
5 : Sparta!

Bruce Tate’s book goes through the following languages: Clojure, Haskell, Io, Prolog, Scala, Erlang, and Ruby. Highly recommended reading.

Testing domain objects with Mean Bean 0

On a previous post, I elaborated on the equals and hashCode methods, and how to implement them more easily. Even so, if you are using TDD and want to be a perfectionist, how would you go on about testing them, and covering all cases? Plus, how would you cover all domain classes of your application?

If this sounds like too much work, especially if you are on a tight deadline, it can be done with three lines of code, using the MeanBean framework:

new BeanTester().testBean(Person.class);
new EqualsMethodTester().testEqualsMethod(Person.class);
new HashCodeMethodTester().testHashCodeMethod(Person.class);

On the background, the first line of code will trigger the framework to test if each getter returns the same data passed to the setter. The test data is generated randomly, to ensure a nice coverage of examples without extra effort.

The EqualsMethodTester will ensure the equivalence properties of the equals method, as described on the java.lang.Object equals() API. All object properties are assumed to be significant (as in, if a property differs between two objects, then the equals method should return false.

You can also specify non-significant properties. In the following example, we declare that a Person’s address will not be significant:

new EqualsMethodTester().testEqualsMethod(Person.class, "address");

With the corresponding class:

public class Person {
 
	private String name;
	private int age;
	private String address;	
 
        ....
 
	public boolean equals(Object object) {
		if (object == null) { return false; }
	    if (object == this) { return true; }
	    if (object.getClass() != getClass()) {
	        return false;
	    }
 
	    Person person = (Person) object;
	    return new EqualsBuilder()
	    	.append(name, person.name)
	        .append(age, person.age)
	        .isEquals();
	}
 
	public int hashCode() {
		return new HashCodeBuilder(17, 37)
        .append(name)
        .append(age)
        .toHashCode();
	}
}

The HashCodeMethodTester will test if two logically equivalent objects have equal hash codes, and that the hashcode remains the same between invocations. I also noticed that this class does not perform property significance tests, as its EqualsMethodTester cousin does, but there is a feature request for it, so hopefully it will be added in future versions of the framework.

Even with some limitations, this framework is quite useful and can increase the code coverage of your tests with almost no effort. It is completely test-framework agnostic, so the integration of Mean Bean with JUnit or TestNG is as simple as creating a test method and invoking the framework’s methods within it (example in JUnit):

public class PersonTest {
 
	@Test
	public void testProperties() {
		new BeanTester().testBean(Person.class);
	}
 
	@Test
	public void testEqualsMethod() {
		new EqualsMethodTester().testEqualsMethod(Person.class, "address");
	}
 
	@Test
	public void testHashCodeMethod() {
		new HashCodeMethodTester().testHashCodeMethod(Person.class);
	}
}

For more information, including a fairly complete user guide, visit http://meanbean.sourceforge.net/.

TDD revisited: Using stubs 0

In my last post, I elaborated a bit on Test-driven development and unit testing. In the last few days, I have been reading “The art of unit testing” by Roy Osherove. According to it, here is the definition of a “unit test”:

A unit test is a piece of a code (usually a method) that invokes another piece of code and checks the correctness of some assumptions after- ward. If the assumptions turn out to be wrong, the unit test has failed. A “unit” is a method or function.

The problem is, in the real world, testing a single unit that belongs to a complex system in isolation is not immediately trivial. A class is coupled with many other components, many times it fetches data from a database, or a file system, or a web-service. How do we deal with this without making our tests very complex? The answer lies in using stubs. Here is the definitions, from Martin Fowler:

Stubs provide canned answers to calls made during the test, usually not responding at all to anything outside what’s programmed in for the test. Stubs may also record information about calls, such as an email gateway stub that remembers the messages it ‘sent’, or maybe only how many messages it ‘sent’.

In other words, if an object is only used by another one to break dependencies and nothing is tested on the behavior of it, that object is a stub. With this new knowledge now in my head, I realized that the unit tests that I have done on the previous post were dependent on the existing of actual files on disk. Here is the original test setup:

@Before
public void setup() throws FileNotFoundException {
	this.katabank = new Katabank();
 
	this.testFileBufferReader = new BufferedReader(new FileReader("files/testFile.txt"));
	this.testFile2BufferReader = new BufferedReader(new FileReader("files/testFile2.txt"));
 
	lines = new ArrayList<String>();
	lines.add("    _  _     _  _  _  _  _   ");
	lines.add("  | _| _||_||_ |_   ||_||_|  ");
	lines.add("  ||_  _|  | _||_|  ||_| _|  ");
	lines.add("                             ");
}

In order for your BufferedReader instances to work correcly with our tests, we need actual files. Let’s leverage that by using the mockito framework:

@Before
public void setup() throws IOException {
	this.katabank = new Katabank();
 
	this.testFileBufferReader = mock(BufferedReader.class);
	when(this.testFileBufferReader.readLine()).
		thenReturn("    _  _     _  _  _  _  _ ",
		           "  | _| _||_||_ |_   ||_||_|",
			   "  ||_  _|  | _||_|  ||_| _|",
			   "                           ",
			   "    _  _     _  _  _  _  _ ",
			   "  | _| _||_||_ |_   ||_||_|",
			   "  ||_  _|  | _||_|  ||_| _|",
			   "                           ");
 
	this.testFile2BufferReader = mock(BufferedReader.class);
        when(this.testFile2BufferReader.readLine()).thenReturn("sadasfassssssssssssssssssssssssssasddddddddddd");
}

With this code, we are creating on-the-fly a stub instance of the BufferedReader class, and defining what should be returned by it when calling the readLine method. The thenReturn method of the framework supports multiple arguments, which allows us to define all the lines that should be returned by the readLine method, just like if we were using the BufferedReader to read an actual file from the file system, with the same structure.

Using this technique, we can isolate the object that we are currently testing by instantiating all its dependencies with stubs. We can also assert the way calls are received by using mocks, but I will leave that to another post. If you are really interested, “The art of unit testing” provides several insights into this, as well as clear examples. The mockito framework is also nicely documented.

Code kata with TDD 0

Doing a Kata is always a nice way to improve your skills a little or try some new methodology. So, when I heard about the Red-Green-Refactor description for Test-driven Development I decided to give it a go by solving a code Kata. The problem description can be found here (at the time of this post, only user story 1 got implemented):

http://codingdojo.org/cgi-bin/wiki.pl?KataBankOCR

While solving, I started by implementing a basic single character conversion, followed by the parsing of a single entry, and at last, the parsing of an entire file. At first, its kind of hard because the method forces you to take “baby steps” and refactor, and I have a tendency to want to settle a nice design “up front” and put it together. Its sounds counter-intuitive and not “future proof” to just do enough for a single bit of functionality, but that is the best thing about it. I found that, by using unit tests, I felt comfortable to keep refactoring while not “breaking anything”, and an adequate design ends up emerging at the same time that you add more functionality. My code just evolved like a living thing, and could keep evolving by investing more time into it.

During development, I also wondered if it was possible to use the JUnit framework to test if the final output is correct. I found out an unknown to me pattern on stackoverflow, that I applied on my code for testing the final output:

private final ByteArrayOutputStream outContent = new ByteArrayOutputStream();
private final ByteArrayOutputStream errContent = new ByteArrayOutputStream();
 
@Before
public void setUpStreams() {
   System.setOut(new PrintStream(outContent));
   System.setErr(new PrintStream(errContent));
}
 
@After
public void cleanUpStreams() {
   System.setOut(null);
   System.setErr(null);
}
...
@Test
public void testTranslateFile() {
	try {
		katabank.translateFile("files/testFile.txt");
		Assert.assertEquals("123456789\n123456789\n", outContent.toString());
	} 
	catch (InvalidFileException e) {
		Assert.fail(e.getMessage());
	} 
	catch (IOException e) {
		Assert.fail(e.getMessage());
	}
}

Now, I am aware that using I/O is not a recommended practice for unit testing (Michael Feathers does not even consider those tests to be “unit tests”). I could do a code rewrite for this Kata in order to isolate the System.out completely and leave that bit “untested”, but I find it hard to always keep this in mind with a “real world” application. Maybe those kind of things should be tested with different tools I am not aware of? Or maybe those tests should simply belong to a different test package, that is run separately? I will try to work it out in the future.

The source for this solution can be found on github and it can certainly be improved. Feel free to do so.

CSS wonders: Simple progress bar 0

In many applications, desktop or web-based, you have certainly seen a progress bar. This UI element provides a simple way to give feedback to the user, and with todays technology of CSS3 and JavaScript it is possible to integrate animated progress bars that work fine in several browsers. Here is a simple progress bar you can experiment with:

Now, to implement this, I picked up the CSS3 files from the Red Team Design blog (great professional work, btw :) ), and added two buttons from the CSS button generator. The animation is done with jQuery. Using the animate function, I simply expand the progress bar span width to 100%. You can check out the JavaScript source below:

$(document).ready(function(){
	$('.fillButton').click(function() {
		$('.progress-bar').find('span').animate({
    			width: '100%'
  		});
		return false;
	});
 
	$('.emptyButton').click(function() {
		$('.progress-bar').find('span').animate({
    			width: '0%'
  		});
		return false;
	});
});

A curious observer might notice that both click event handlers return false. As the buttons here are simple links with CSS on top, this is done to prevent the default action of scrolling to the top of the page when clicking on a link. Feel free to reuse all these components on your website as well (crediting the original authors).


The power of jQuery selectors 0

jQuery is now the most popular Javascript framework. It gives the developer great flexibility to implement dynamic behaviors, respond to a user’s interaction, animate changes being made and also retrieve information from the server using Ajax. In this post, I am going to focus on jQuery capabilities for transversing the DOM and selecting any element, without writing many lines of code.

To understand better how it works, I am following the book Learning jQuery, Third Edition, by Jonathan Chaffer and Karl Swedberg. The HTML used for these exercises is given here. Let’s proceed to the examples:

/* Add a class of special to all of the <li> elements at the second level of the
nested list */
$(document).ready(function() {
	$('#selected-plays > li > ul > li').addClass('special');
});

The first thing you should notice is, I am using the $(document).ready(…) construct and passing an anonymous function to be invoked. This will allow jQuery to schedule the function to be invoked once the DOM is actually loaded. To select an item, we always use the $() function of jQuery, which accepts a CSS selector as a parameter, returning a new jQuery object pointing to the corresponding elements on the page. As an example, this one is pretty straightforward, I start from the nested list id and transverse to the second level of li element, adding the class.

/* Add a class of year to all of the table cells in the third column of a table */
$(document).ready(function() {
	$('td:nth-child(3)').addClass('year');
});

Besides the standard CSS selectors mentioned in the previous example, jQuery also adds custom selectors, making it more powerful. This one uses the nth-child selector, which allows us to select the td element that is the third child of his parent tr.

/* Add the class special to the first table row that has the word Tragedy in it */
$(document).ready(function() {
	$('tr:contains(Tragedy)').first().addClass('special');
});

This example uses the very useful contains selector, which looks for a string of text. The first selector will restrict the result to the first table row.

/* Challenge: Select all of the list items (<li>s) containing a link (<a>). Add the
class afterlink to the sibling list items that follow the ones selected. */
$(document).ready(function() {
	$('li:has(>a)').next().addClass('afterlink');
});

This is the example I found the most challenging in this series. You can use the jQuery selector has, but I wanted to have just the li items that have a link as the immediate child, not as any descendant. After playing around for a bit, I found that one can combine a CSS Selector as well, returning the correct elements. The next() selector will then return the siblings that follow each item.

/* Challenge: Add the class tragedy to the closest ancestor <ul> of any
.pdf link. */
$(document).ready(function() {
	$('a[href$=".pdf"]').closest('ul').addClass('tragedy');
});

For the last one, I constructed a selector that looks for all elements a with href attribute ([href]), ending in .pdf ($=".pdf"). The closest ancestor might look dauting at first, but there is a jQuery closest selector that gives us exactly what we need.

And this completes our series of examples on jQuery selectors. To learn more, get your hands on Learnign jQuery, Third Edition and start experimenting with some code. jQuery also provides a very good API documentation that should clarify any doubts.

Wrapping input with rlwrap 0

If you are using GNU/Linux, you might have noticed that not all shell applications have functional arrow keys. As an example, here is what happens when you try to use them in ruby interpreter:

$ ruby
puts "some staring^[[D^[[C^[[D"

Not exactly pretty isn’t it? Using the command line interpreter is useful for testing some lines of code, but we would like to move back and forward in case we make any mistake, or use the up and down arrow keys to view the history of commands, similar to what we do all the time on the shell. You can do this by using the rlwrap utility:

$ rlwrap ruby

In addition, you can also search through the history of commands using Ctrl-R, similar to what is done on Bash.

Prototype your Java web app with appfuse 0

Developing a new Java web application? Want to try out new technologies? Don’t have an ideia how to split your application and organize it into packages? Dependencies and adding libraries looks like too much work? Use Maven, and create a skeleton application:

mvn archetype:generate -B -DarchetypeGroupId=org.appfuse.archetypes
-DarchetypeArtifactId=appfuse-basic-spring-archetype
-DarchetypeVersion=2.1.0
-DgroupId=com.mycompany
-DartifactId=myproject
-DarchetypeRepository=http://oss.sonatype.org/content/repositories/appfuse

This will create a prototype application with , using Spring MVC and Hibernate (Struts2 is also supported).

In the end, you will have a basis for your next web application, and you can start coding right away. To give an idea, here is a glimpse of the Spring MVC structure:

Here, the test folders will have the  unit tests, and the main folders your web application. The webapp folder will hold the .jsp files, along with the CSS and Javascript. If you are interested in experimenting with it, check out the nice Appfuse quickstart guide to get you going.

Happy easter with a ruby 0

To make sure you will never forget Easter date, here is a small quark in ruby:

require 'date'
 
def easter(year)
    a = year % 19
    b = (year / 100).floor
    c = year % 100
    d = (b / 4).floor
    e = b % 4
    f = ((b + 8) / 25).floor
    g = ((b - f +1) / 3).floor
    h = (19*a + b - d - g + 15) % 30
    i = (c / 4).floor
    k = c % 4
    l = (32 + 2*e + 2*i - h - k) % 7
    m = ((a + 11*h + 22*l) / 451).floor
    month = ((h + l - 7*m +114) / 31).floor
    day = ((h + l - 7*m + 114) % 31) + 1
    print "Easter is on ",day," of ",  Date::MONTHNAMES[month],"\n"
end

This one is pretty straightforward, but you if you don’t know much about Ruby, notice how “everything” is an object, even numeric values (where you invoke the floor method). Also, if you are curious, you can check out the basic algorithm for computing Easter date on wikipedia

Happy Easter to all.