Archive for the ‘English’ Category.

Escript under Windows

Escript is a tool for executing simple scripts written in Erlang. It's a nice tool, but the manual page is too much "Unix oriented":if we try to run the example script under one of the funny and exotic operating systems of the Windows family, we get something like this:

C:\temp>escript factorial.escript 5
escript: Failed to open file: C:\temp\escript.escript

Ouch! The solution to the problem comes reading the sources of escript.exe. Under Windows it takes the program name used to call it (in our example escript): if it doesn't end with the exe suffix it takes it as the name of the script, then it adds the escript suffix ant tries to run it: so it looks for as escript.escript which doesn't exist. Obviously it's a bug, but to overcome it, we can add the exe suffix to our command line:

C:\temp>escript.exe factorial.escript 5
factorial 5 = 120

Another note for Windows users: the first line cannot contain Erlang (it's the place for the Unix # line).If you try to run this script

main(Args) ->
	print_args(Args). 

print_args([]) ->
    ok;
print_args([FirstArg | Rest]) ->
    io:format("~s~n", [FirstArg]),
	print_args(Rest).

You'll get this result:

C:\temp>escript.exe x.escript Hello World
x.escript:2: syntax error before: '.'
escript: There were compilation errors.

You must add a line before the main in order to run it.

Bowling game Kata in Erlang

In the last meeting of the Extreme Programming (XP) User Group of Milan, Gabriele Lana, after an introduction to Erlang, guided us in doing the Fizz-Buzz kata in this language. The experience was exciting, so I tried to execute a kata on my own. I chose the Bowling game Kata by Robert C. Martin because I did it many times in Java. I wrote the same tests of Mr. Martin, adding just one to cover a corner-case of my implementation. Here there are:

I defined an include file for some macros which helped me to make the code more speaking (I hope)

And here is my solution:

This solution, like the ones proposed by Gabriele, seems simpler than the classical Java code showed by Mr. Martin.
I think that functional languages like Erlang are more suited for small algorithmic problems like this. I wonder if these languages

  • can scale for larger problems
  • can handle situations where the algorithmic component is not so preeminent, while the real issue is managing changes


My first impression on Erlang is positive: it's a great Domain Specific Language, where the domain is parallel and distributed computing. It's syntax is simple (far simper than the Scala one), even if this does not imply that writing Erlang programs should be simple. It has some negative issues too: string handling is difficult; the flat name space could be a problem for large projects; the error messages are often obscure (at least for a newbie like me); and, above all, it has no static typing, so the programs need lots of comments to explain the communication protocol between modules.
These lacks in the language are also evidenced by the presence of macros: in my humble opinion, a language that needs macros has a poor syntax. But macros could turn in a great value if they are used to expand the language in the direction of literate programming. A small example of this is the macro ?is_spare I created to make guards clauses more speaking. I'll do some explorations in this direction in the future.

I don’t like infixes

All this stuff began with a tweet of mine in response to @unclebobmartin. While Mr. Martin said "I am becoming ever more convinced that clojure is the functional language to use", I argued that Clojure is the opposite of Literate Programming as (+ 1 2) is very far from my natural way of thinking 1 + 2.

My opinion is that the prefix notation of Clojure, and the resulting parenthesis pollution, makes this language very hard to read.

Then @fogus pointed out that there is nothing literate about the infix way of representing (< a b c d e f g). That's true, if we think of a C like implementation such as:

a<b && b<c && c<d && d<e && e<f && f<g

But, fortunately, we have Scala:

 
package net.fl.clojure
 
object ClojureDemo {
 
  case class RichList (list : List[Int]) {
    def isOrderedBy(f: (Int, Int) => Boolean) : Boolean = list match {
      case Nil => true
      case x :: Nil => true
      case x :: y :: xs => f(x, y) && listConverter(y :: xs).isOrderedBy(f)
    }
 
    def isAscendingOrdered = isOrderedBy(_ < _)
  }
 
  implicit def listConverter (list: List[Int]) = new RichList(list)  
 
  def main(args : Array[String]) : Unit = {
    println(List(1, 2, 4).isOrderedBy(_ < _))
    println(List(1, 20, 4).isOrderedBy(_ < _))
 
    println(List(1, 2, 4).isAscendingOrdered)
    println(List(1, 20, 4).isAscendingOrdered)
  }
}
 

So the lispish (< a b c d e f g) becomes List(a b c d e f g).isAscendingOrdered or, if you want to be more flexible List(a b c d e f g).isOrderedBy(_ < _)

Unit testing with the Saff Squeeze

Yesterday I read an interesting post of Kent Beck about a testing technique called Saff Squeeze. The idea is that, when you have to fix a bug in your code, first of all you need to write an "high level" test (hit the bug high) that shows the problem, then, instead of stepping in your debugger looking for the bug, you try to write a test which goes deeper and deeper in the code, in-lining method calls, until you get to the root of the problem (hit the bug low). It's like the Tai Otoshi Judo throw.


Waterfall

A real world example

As I had to find a bug in my code, I decided to try this technique.

I'm working at an ERP that exports a list of tasks to Microsoft Project. If the user chooses to create a plan scheduled from the finish date, that date has to be the maximum value of the deadlines of each task. Unfortunately there was a bug in this piece of code, so I wrote this test. (Note that, for compatibility issues, I use Java 1.4 and JUnit 3 for the project.)

 
  protected void setUp() throws Exception {
    converter = new XMLConverter();
    projectBean = new ProjectBean();
  }   
 
  public void testIfScheduleFromFinishProjectFinishDateIsTheMaximumValueOfTasksDeadlines() {
    MyDate maxDeadline = new MyDate();
 
    ProjectTaskBean task1 = createTask(1);
    task1.setDeadline(maxDeadline.addDays(-1));
    projectBean.addTask(task1);   
 
    ProjectTaskBean task2 = createTask(2);
    task2.setDeadline(maxDeadline);
    projectBean.addTask(task2);   
 
    ProjectTaskBean task3 = createTask(3);
    task3.setDeadline(maxDeadline.addDays(-2));
    projectBean.addTask(task3);   
 
    projectBean.setScheduleFromStart(false);
 
    String xml = converter.toXML(projectBean);
    TestUtils.assertContains(
		xml,
        "<FinishDate>" +
			new DateProjectConverter().toString(maxDeadline) +
        "</FinishDate>"); //Fails
  }
 

This was my "high-hit" test. As converter.toXML is a full tested method that simply creates an XML from objects via reflection, I supposed that the problem was in projectBean.setScheduleFromStart, so I wrote this new test.

 
  public void testSaffSqueezeExample() {
    MyDate maxDeadline = new MyDate();
 
    ProjectTaskBean task1 = createTask(1);
    task1.setDeadline(maxDeadline.addDays(-1));
    projectBean.addTask(task1);   
 
    ProjectTaskBean task2 = createTask(2);
    task2.setDeadline(maxDeadline);
    projectBean.addTask(task2);   
 
    ProjectTaskBean task3 = createTask(3);
    task3.setDeadline(maxDeadline.addDays(-2));
    projectBean.addTask(task3);   
 
    projectBean.setScheduleFromStart(false);
 
    //projectBean.finishDate is now public for testing purposes
    assertEquals(maxDeadline, projectBean.finishDate);   //Fails
  }
 

The test failed: I was right. Then I tried to modify the test in-lining the code of the failing method.

 
  public void testSaffSqueezeExample() {
    MyDate maxDeadline = new MyDate();
 
    ProjectTaskBean task1 = createTask(1);
    task1.setDeadline(maxDeadline.addDays(-1));
    projectBean.addTask(task1);   
 
    ProjectTaskBean task2 = createTask(2);
    task2.setDeadline(maxDeadline);
    projectBean.addTask(task2);   
 
    ProjectTaskBean task3 = createTask(3);
    task3.setDeadline(maxDeadline.addDays(-2));
    projectBean.addTask(task3);   
 
    //projectBean.scheduleFromStart is now public for testing purposes,
    //and the setScheduleFromStart method is inlined
    projectBean.scheduleFromStart = false;
    if (projectBean.scheduleFromStart) {
      projectBean.finishDate = null;
    } else {
      //projectBean.maxDeadline() is now public for testing purposes
      projectBean.finishDate = projectBean.maxDeadline();
    }
 
    //projectBean.finishDate is now public for testing purposes
    assertEquals(maxDeadline, projectBean.finishDate);   //Fails
  }
 

Then I simplified the test.

 
  public void testSaffSqueezeExample() {
    MyDate maxDeadline = new MyDate();
 
    ProjectTaskBean task1 = createTask(1);
    task1.setDeadline(maxDeadline.addDays(-1));
    projectBean.addTask(task1);   
 
    ProjectTaskBean task2 = createTask(2);
    task2.setDeadline(maxDeadline);
    projectBean.addTask(task2);   
 
    ProjectTaskBean task3 = createTask(3);
    task3.setDeadline(maxDeadline.addDays(-2));
    projectBean.addTask(task3);   
 
    //projectBean.finishDate is set to private again
    assertEquals(maxDeadline, projectBean.maxDeadline());   //Fails
  }
 

So this was time to inline the projectBean.maxDeadline() method.

 
  public void testSaffSqueezeExample() {
    MyDate maxDeadline = new MyDate();
 
    ProjectTaskBean task1 = createTask(1);
    task1.setDeadline(maxDeadline.addDays(-1));
    projectBean.addTask(task1);   
 
    ProjectTaskBean task2 = createTask(2);
    task2.setDeadline(maxDeadline);
    projectBean.addTask(task2);   
 
    ProjectTaskBean task3 = createTask(3);
    task3.setDeadline(maxDeadline.addDays(-2));
    projectBean.addTask(task3);   
 
	//projectBean.tasks is set to public
	ProjectTaskBean maxDeadlineTask =
      (ProjectTaskBean) Collections.max(projectBean.tasks, new DeadlineComparator());
 
    //projectBean.maxDeadline is set to private again
    assertEquals(maxDeadline, maxDeadlineTask.getDeadline());   //Fails
  }
 

Well, at this point I saw that the problem should be in the DeadlineComparator class, so I could get rid of the intermediate tests, rollback the changes to the ProjectTaskBean class and write a test against the buggy class (my "high-low" test).

 
  public void testDeadlineComparatorFindsMaxDeadline() {
    MyDate maxDeadline = new MyDate();
 
	Collection tasks = new ArrayList();
 
    ProjectTaskBean task1 = createTask(1);
    task1.setDeadline(maxDeadline.addDays(-1));
    tasks.add(task1);   
 
    ProjectTaskBean task2 = createTask(2);
    task2.setDeadline(maxDeadline);
    tasks.add(task2);   
 
    ProjectTaskBean task3 = createTask(3);
    task3.setDeadline(maxDeadline.addDays(-2));
    tasks.add(task3);   
 
	ProjectTaskBean maxDeadlineTask =
      (ProjectTaskBean) Collections.max(tasks, new DeadlineComparator());	
 
	//All fields and methods in projectBean are set to their original visibility
	assertEquals(maxDeadline, maxDeadlineTask.getDeadline());   //Fails
  }
 

So this was time to fix-up my code! ;-)

Conclusion

Kent Beck says: "Squeezing encourages good design. If inlining creates too big a mess, back up, clean up the called method, and inline again. Even if I received no other benefits from squeezing, the design improvement would be worth it."

Well, if it's definitely true that you need a good design (or, at least, a not so bad one) for squeezing, I think that it could be difficult to refactor your code when you're doing it: after all, you have a red bar.

Anyway, it seems a nice technique to explore your code without digging in the debugger too much and, this time, it worked fine. :-)

A TDD side effect

All you know that TDD has god side effects. One of them is testing your application :-) Another one is to force you to write less verbose code.
Sometimes (only sometimes ;-) ) when you write production code not writing tests (oh, well I do not do that, ehm) you accept that the code is not as concise and "speaking" as it should be: after all you are writing code that does its dirty work (maybe), that's enough!!! But when you write tests, you know that the goal of test code is to speak to other people. In other words, my attitude when I write production code is to write code that speaks to the machine, while when I write test code I'm trying to speak to people, and you know, when you're speaking to human beings you can't bore them. So your writing must be clear and concise. In order to do that, sometimes you're forced to write some helper classes that, after a short while, you'll find useful on the production side too.

Presentation on Scala

I translated in English the presentation on Scala I gave to the XP User group of Bergamo:

Fantom vs Scala: semicolon inference and something more

As I said in a previous post, even if Scala is at the moment the best candidate to become the Next Big Language, I think that many things in its syntax are Byzantine and error prone. The examples in Klaus' comment are very explanatory in this sense.
In my search of the Holy Graal of the programming languages, I met Fantom (previously known as Fan), a very interesting attempt to create a language simple yet powerful.
First of all, let's have a look at a Fantom version of the semicolon inference example of my previous post. Note that, since I'm an absolute beginner in Fantom programming, the use of the language I made is far from optimal: any suggestion will be appreciated.

class GoodFantom {  

  static Int subtract1(Int a, Int b) {
    a -
    b
  }  

  static Int subtract2(Int a, Int b) {
    a
    - b
  }  

  static Void main() {
    echo(subtract1(10, 2))      //Prints 8
    echo(subtract2(10, 2))      //Prints 8 too!
  }
}

The Fantom way to handle statements ending seems pretty good. Anyway, I'm not sure that there are not drawbacks to this approach: again, any suggestion is welcome.
Now let's see how this example of creating a DSL fragment in Scala could be translated in Fantom.
So, let's define a Loop class:

class Loop {
  //Constructor that accepts a function without parameters that returns Void
  new make(|,| body)
  {
    this.body = body
  }  

  Void unless(|->Bool| cond)
  {
     body.call()
     if (!cond()) unless(cond)
  }  

  |,| body
}

Then we use it in our code:

using fanExercise::Loop  

class Main
{
  static Void main()
  {
    Int i := 10
    Loop(|,|
	{
      echo("${i--}")
    })
    .unless |->Bool| {i == 0}
  }
}

We can see that the Fantom version is slightly more verbose than the Scala one (even if, as I said, maybe a good Fantom programmer could do better), but, as the dot is mandatory in method calls, I think it's less error prone.

Tomcat on AS400 (aka i-series, Systemi, IBM i, bla, bla…)

I know that AS400 gives its own native support to Tomcat and other application servers, but it does it in the IBM style: intricate and rigid. What if, for example, I need to use a version of Tomcat that it is not shipped with my operating system?
Here is one possible answer:

1) Download a copy of Apache Tomcat and unzip it in a directory of the Integrated File System of AS400.

2) In another directory of the Integrated File System Create a text file named tomcat with a simple script like this:

#The path of the JDK you want to use
export JAVA_HOME=/QIBM/ProdData/Java400/jdk14  

#The JVM option you want to use
#In this example -opt0 means 'no optimization'
export JAVA_OPTS='-opt0 -Djava.awt.headless=true'  

cd /path/to/my/tomcatdir/bin
catalina.sh %1

3) In a 5250 session (or in a batch job) execute this command

QSH CMD('/path/to/my/script/tomcat run')

Your Tomcat should be alive and kicking :-)

4) In order to shut down Tomcat, use this command

QSH CMD('/path/to/my/script/tomcat stop')

Enjoy with Tomcat and AS400!!!

Functional setter Java idiom

The way of organizing the code I will show in this post is very common, but, perhaps, it's useful to give it a name, and I will call it the "functional setter java idiom". Let's see.

In java there are no named parameters, i.e. parameters that I can pass to a method in the order I like calling them with their name. For example in Visual Basic for Applications we can sort some Excel cells this way:

 
SelectedSheets.PrintOut Copies:=1, _
    Preview:=True, _
    PrintToFile:=True, _
    Collate:= True
 

Note that the order in which I set the parameters is arbitrary, and that some parameters can be omitted, having it assigned with default values.

Now let's suppose we need to create an object with a long series of parameters (OK, I know, it's a code smell, but, please, close your nose for a while):

 
PrintType printType = new PrintType(1, true, true, true);
 

Well, not a good piece of code! Especially the sequence of boolean parameters is a mess. Moreover, sometimes I'd like to create my object with less parameters, having the others set with default values. I could create many constructors, but this would increase the complexity of my program.

I could solve the problem using some setters:

 
PrintType printType = new PrintType();
printType.setCopies(1);
printType.setPreview(true);
printType.setPrintToFile(true);
printType.setCollate(true);
 

Uhmm, better enough, but what if I need to assign my object to a constant, i.e. a final static field? I should write:

 
public final static PrintType DEFAULT_PRINT = new PrintType();
 
static {
	DEFAULT_PRINT.setCopies(1);
	DEFAULT_PRINT.setPreview(true);
	DEFAULT_PRINT.setPrintToFile(true);
	DEFAULT_PRINT.setCollate(true);
}
 

Mamma mia, this code is ugly! Maybe I could improve it just a bit using some functional setters, i.e. setters that have a return value, as a function. In the PrintType class I should write:

 
public PrintType setCopies(int copies) {
	this.copies = copies;
	return this;
}
 
public PrintType setPreview(boolean value) {
	this.preview = value;
	return this;
}
 
public PrintType setPrintToFile(boolean value) {
	this.printToFile = value;
	return this;
}
 
public PrintType setCollate(boolean value) {
	this.collate = value;
	return this;
}
 

Now the initialization of my static field becomes:

 
public final static PrintType DEFAULT_PRINT = new PrintType()
	.setCopies(1)
	.setPreview(true)
	.setPrintToFile(true)
	.setCollate(true);
 

This is not so bad, don't you think?

Implicit conversions in Scala are cool

Andy Warhol – Dollar sign

Sometimes I hear sentences like Domain Specific Languages (DSL) can be generated effectively only using dynamic languages, or This super-cool feature could not be possible in a static typed language. More and more, some people would transmit the idea that dynamic languages are agile and cool, while static ones are rigid and old. I strongly disagree! I think that in static languages lots of unit tests are generated and maintained automatically by the compiler, while in dynamic ones the programmer should create and maintain these tests. So static languages have lots more unit tests: isn't this agile programming? And what about cool features? Well, what do you think about a language in which you can write something like this?

 
(5.0 USD) + (2.0 USD) == (7.0 USD)

Cool DSL, isn't it? Sure, and I will show you that this is possible (and very easy) using a language with a strong and static type system: Scala.

As we are going to write yet another money example, we could begin with the definition of currencies.

 
abstract class Currency {
  def name: String;
  override def toString = name
}    
 
object Euro extends Currency {
  def name ="EUR"
}    
 
object Dollar extends Currency {
  def name = "USD"
}

Not very exciting. We simply define an abstract Currency class and two singleton objects that extend this class. Note that these objects are instances of anonymous subclasses of Currency. This does matter, as we'll see in a moment.

Now let's define money.

 
case class Money[C &lt;: Currency](amount: Double, currency: C) {
  def + (otherMoney: Money[C]) = {
    new Money(amount + otherMoney.amount, currency)
  }
  override def toString = amount + " " + currency
}

Our class is parametric in the type C, and we tell to the compiler that it must be a subclass of Currency. This way we have the nice consequence that the + operator can add only money of the same currency, and this test is done by the compiler before our code is running.

It's time to get to the cool feature: implicit conversion. So, in the same file Money.scala in which we defined the Money class, we create a Money object, which has the responsibility to convert doubles, let me say, "annotated" with a currency, into Money.

 
object Money {
  implicit def doubleConverter(d: Double) = new {
    def EUR = {
      new Money(d, Euro)
    }    
 
    def USD = {
      new Money(d, Dollar)
    }
  }
}

Uhm, it sounds a bit strange. How we can use it? Let's see an example.

 
import Money._    
 
object MoneyMainProgram extends Application {    
 
  val tenDollars = (4.0 USD) + (6.0 USD)     
 
  println(tenDollars)
}

Now some explanations are required.

In the first line we import the Money object. We can see it as a kind of static import, that, among other things, adds to the scope of our code all the implicit conversions defined in that object.

When we write 4.0 USD, we try to invoke the USD method on the 4.0 object, which is a double. Obviously there isn't such a method in the Double class, but the compiler, before giving up and throwing an error, tries to see if there is some way to convert the 4.0 in an object that does understand the USD method. Luckily we have imported the doubleConverter which takes a Double and transforms it in an instance of an anonymous class with a USD method: bingo! So the compiler transforms our code in something like this:

 
  doubleConverter(4.0).USD()

But what is the result of this expression? Well, it's an instance of the Money class expressed in Dollar. This class has the + method that we can use to add another Money in the same currency. Cool!

Let's take a look to our work. We needed to add some features to the Double class. In some dynamic languages we could monkey patch this class. In Scala we did it using a dynamic conversion from Double to a class with the methods we need, so we reached the same purpose in a static and safer way.

And so, an old fashioned static language could have such cool features? It seems....