Monday, September 26, 2011

Groovy: Reuse of Helper Test Methods in a Spec

There are a lot of message transformers in a lot of the projects I work that work primarily with XML. I want my tests to take a source XML document and verify the output transformation. The example input and output messages live on the classpath, say in directory src/test/resources, and their contents are accessed through the classloader.

Take this example spec written for the Spock framework for Groovy:

    class XmlTransformerSpec extends Specification {

XmlTransformer transformer = new XmlTransformer()

def "transforms xml messages for some business goal"() {
given:
def inputXml = textOf("input.xml")
def expectedOutputXml = textOf("expected-output.xml")
when:
def actualOutputXml = transformer.transform(inputXml)
then:
areIdentical(expectedOutputXml, actualOutputXml)
}

def areIdentical(String expected, String actual) {
XMLUnit.setIgnoreWhitespace true
new Diff(expected, actual).identical()
}

def textOf(resource) {
getClass().getClassLoader().getResourceAsStream(resource).text
}

}

The retrieval of the messages in the form of resources is contained within the textOf() method where it can be resued by additional tests within the spec. What if I wanted to reuse it other test classes? One option I found was to move the method to an abstract class that extends spock.lang.Specification:

    abstract class ResourceAwareSpecification extends Specification {

def textOf(resource) {
getClass().getClassLoader().getResourceAsStream(resource).text
}
}

Now my test spec, along with any others that need to retrieve the contents of classpath resources, can extend the new specification:

    class XmlTransformerSpec extends ResourceAwareSpecification {
// method textOf() has been removed...
}

I wonder if others find themselves loading resources in this way and may make use of an approach like this if it were builtin to a framework like Spock in this or some other form, like a mixin. The helper method comparing the XML using XMLUnit would be another candidate in my mind for such an addition. Thoughts?

Tuesday, September 20, 2011

Openbox: Defining a Keyboard Shortcut

The Openbox Window Manager has quickly become my favorite way to use my computer. It use it almost exclusively on all the machines that I use (Ubuntu at work, Mint at home).

Here I'll describe how to add a keyboard shortcut so that we do not have to reach for the mouse to do something common. As I spend most of my time in the terminal, one shortcut I make the most use of is Alt+T to open a terminal program, mrxvt.

The keyboard shortcuts, along with many other things, are defined in ~/.config/openbox/rc.xml. The keyboard element is a child element of the root openbox element. Below is a snippet of an example showing the default shortcut for switching to the desktop to the left. The shortcut C-A-Left describes pressing the Ctrl, Alt, and left arrow keys with the default mappings:

<?xml version="1.0" encoding="UTF-8"?>
<openbox_config xmlns="http://openbox.org/3.4/rc">
<!-- some config omitted... -->
<keyboard>
<chainQuitKey>C-g</chainQuitKey>
<!-- Keybindings for desktop switching -->
<keybind key="C-A-Left">
<action name="DesktopLeft">
<dialog>no</dialog>
<wrap>no</wrap>
</action>
</keybind>
<!-- some keyboard config omitted... -->
</keyboard>
<!-- some config omitted... -->
</openbox>

To add our terminal shortcut, we add a keybind entry with the Execute action, followed by the command to execute. The key of A-t corresponding to pressing the Alt key along with the t key:

<?xml version="1.0" encoding="UTF-8"?>
<openbox_config xmlns="http://openbox.org/3.4/rc">
<!-- some config omitted... -->
<keyboard>
<chainQuitKey>C-g</chainQuitKey>
<!-- my keybindings -->
<keybind key="A-t">
<action name="Execute">
<execute>mrxvt</execute>
</action>
</keybind>
<!-- some keyboard config omitted... -->
</keyboard>
<!-- some config omitted... -->
</openbox>

We can reload the new configuration from the command line with:

  $ openbox --reconfigure

Or by right-clicking on the desktop and selecting Reconfigure from the Openbox menu.




Note: In order to take the screenshot with the menu shown, I ran gnome-screenshot with a delay of 5 seconds:

  $ gnome-screenshot -d 5

During the delay, you can right click on the desktop to get the menu in the picture.


Installing Clojure 1.2 on Ubuntu

If you're looking to install the latest stable version of Clojure on Ubuntu or a derivative, below are a few options. Currently, I'm running Ubuntu 10.10, whose package list contains Clojure 1.1.0. We can install this version using apt-get:

  $ sudo apt-get install clojure
...
$ clojure
Clojure 1.1.0
user=> (System/exit 0)

The most recent stable release is 1.2.1 (see Clojure Releases). It looks like while there was a request to have the available package updated to 1.2 (Ubuntu Bug #731979), but it looks like it won't be included by default until the 11.10 release of Ubuntu.

If we want to use the most recent stable release, the bug report has a link to the package set to be included in 11.10, clojure1.2, which we can install with dpkg:

  $ sudo dpkg -i clojure1.2_1.2.1+dfsg-3_all.deb

This links the clojure.jar as:

  $ ls -l /usr/share/java/clojure.jar
lrwxrwxrwx 1 root root 29 2011-09-20 10:39 /usr/share/java/clojure.jar -> /etc/alternatives/clojure.jar

Alternatively, we can download the source from the releases page and build it with ant ourselves: Clojure 1.2.1 Source.

  $ unzip clojure-1.2.1.zip
$ cd clojure-1.2.1
$ ant
...
BUILD SUCCESSFUL
Total time: 1 minute 57 seconds

If the build succeeds, we can just copy the built jar to the install location:

  $ sudo cp clojure.jar /usr/share/java/clojure.jar
$ clojure
Clojure 1.2.1
user=> (System/exit 0)

This approach should also work if we want to run the most recent development versions as well.

Thursday, September 15, 2011

Fantom: Constructors, Required Fields, and More

This post is part of a series of sorts where I write about what I find while exploring the Fantom language. This time I'm going to share what I find out about declaring and using classes as I go. I imagine I will only scratch the surface.

To give you the chance to devote some of your valuable reading time elsewhere, below is a summary of some of the highlights covered below:

  • Declaring class fields that are required at object creation and throughout the lifetime of the object
  • Default class field values
  • Automatic getters and setters

A class can be declared using the class keyword as we're all probably used to. Let's declare a (boring) class Person with a name field and add a main method so we can try and create an instance.

Assignments in Fantom are done via the use of := instead of an equals sign. Here we'll start by simply creating an empty object and printing out to the console that we've succeeded:

    class Person {
Str name

static Void main(Str[] args) {
Person p := Person()
echo("Person created.")
}
}

The variable p is given what looks to be the result of a call to a default constructor. We can run the above with:

   $ fan Person.fan

Our first run gives us the following error:

   Non-nullable field 'name' must be assigned in constructor 'make'

The error hints that the call to Person() results in a call to a constructor named make. Also, the error descrption seems to go against what we may be used to in Java, where class properties can be null. Right of the bat to me, this could demonstrate a potential strength of Fantom as, as given the class definition above, a user cannot create an incomplete Person. If we want to create a Person without assigning a value to the name field, we can append a '?' to the field declaration:

    class Person {
Str? name

static Void main(Str[] args) {
Person p := Person()
echo("Person created.")
}
}

This time we'll get the "success" message indicating we've created a Person. Let's keep the name field required and assign a value to it when the Person is constructed. To do this, we can add a constructor and in the main method create a Person named 'Cosmo':

    class Person {

Str name

new make(Str name) {
this.name = name
}

static Void main(Str[] args) {
Person p := Person("Cosmo")
echo("Person created with name: " + p.name)
}
}

As you can see, the main method now also reports the name of the created Person via a call to the name method. Although it looks like we are accessing the field directly, getters and setters are automatically created for each field which helps us cut down on the amount of boilerplate code our class might contain, not unlike some of the newer JVM langauges. Running things through the interpreter again gives us:

    Person created with name: Cosmo

To demonstrate the generated setter, we can add the following:

    p.name = "George"
echo("Person renamed to: " + p.name)

The output of our program is now:

   Person created with name: Cosmo
Person renamed to: George

One question I now have is now that we have declared the name field as non-null at construction time, can we assign the value to null after the object has been created? Let's add the lines below to the main method:

    p.name = null
echo("Person with null name?: " + p.name)

With the above in place, we now get an error:

   'null' is not assignable to 'sys::Str'

Again, this restriction should in practice help keep our class instances safe and remove the usual null-checking concerns.

Now some might say a class with one field might be pretty boring (if not useless). Lets add another field, age, but not require a user of the class to do a Person's age at construction time by allowing a default value (since age can be a touchy subject anyway). Let's try adding another constructor to be used when both the name and the age of the Person are known:

    class Person {

Str name
Int age := 1

new make(Str name) {
this.name = name
}

new make(Str name, Int age) {
this.name = name
this.age = age
}

static Void main(Str[] args) {
Person cosmo := Person("Cosmo", 40)
Person marshall := Person("Marshall")
echo("Person " + cosmo.name + ", aged " + cosmo.age)
echo("Person " + marshall.name + ", aged " + marshall.age)
}
}

Here will create two Persons with an declared age and one with the default of 1, and report on both:

    Duplicate slot name 'make'

Ah, we get an error... are we not allowed to have two constructors? Turns out in Fantom, constructors are treated like methods, with the new keyword out in front, and can be either be named make or start with make. Since we will likely prefer for our users to fully populate the class fields, let's name the two parameter constructor make and rename the original:

    new makeNamed(Str name) {
this.name = name
}

new make(Str name, Int age) {
this.name = name
this.age = age
}

Here though, how do we differentiate between which constructor is used for each assignment? The Persons we create are made through a call to Person(...)? Turns out we can call the constructors by name by referring to them through the class definition:

    Person cosmo := Person.make("Cosmo", 40)
Person marshall := Person.makeNamed("Marshall")

We cannot it appears make calls to Person(...) like we did before and have the compiler infer with constructor to use asin:

    Person cosmo := Person("Cosmo", 40)
Person marshall := Person("Marshall")

This results in the error:

   Invalid args (sys::Str, sys::Int), not (sys::Str)

Back to the explicit calls, our class now reads:

    class Person {

Str name
Int age := 1

new makeNamed(Str name) {
this.name = name
}

new make(Str name, Int age) {
this.name = name
this.age = age
}

static Void main(Str[] args) {
Person cosmo := Person.make("Cosmo", 40)
Person marshall := Person.makeNamed("Marshall")
echo("Person " + cosmo.name + ", aged " + cosmo.age)
echo("Person " + marshall.name + ", aged " + marshall.age)
}
}

Giving this attempt a shot gives us...

   Person Cosmo, aged 40
Person Marshall, aged 1

...output for both Persons, with the second making use of the default age.

This looks like enough to cover for now in one post. Looking at the documentation further, there's looks like there's a lot more to cover at a later date. If I find I misstated any of the terminology or made things more difficult then they need to be, I'll be sure to come back and make corrections.

Tuesday, September 13, 2011

Creating a Marco in Vim

I'm a fan of the vim text editor, and try to use it as much as possible. I have hard time though making the effort to learn more than I already know. While I think I can use it pretty effectively, I know I've truly only scratched the surface.

Often I find myself retyping the same commands over and over to repeatedly accomplish the same task. I then make a mental note to learn about creating macros, which would of helped me out. I then proceed to forget about immediately.

Not today though. Today I'm going to create my first macro.

A macro is a series of commands that can be replaced. Marcos can be assigned to buffers so they can be saved and recalled. Buffers have single- character names in the ranges:

  • 0-9
  • a-z
  • A-Z

To start the definition of a macro in command mode, type 'q' followed by a single character in one of the ranges above.

I'm going to start with the text below and think of some reason to create a macro:

hello my name is george
hello my name is george
hello my name is george

How about we try and replace every occurence with "name" with "first name". We could do a global substitution by typing a colon followed by 's/name/first name/g' and hitting enter, but I want to try out a macro.

A marco could simply:

  1. Search for the next occurrence of name.
  2. Replace "name" with "first name" (or insert the text "first ")

Let's try it out. With my cursor on the first character in the file, if I:

  1. Type 'q' to declare I want to define a macro
  2. Type 'a' to assign the macro to buffer 'a'
  3. Type '/' followed by "name" then Enter to find the first occurence of "name"
  4. Type 'cw' followed by "first name" then Esc to change the word
  5. Type 'q' to complete the macro definition

The text should now have one occurrence of "first name" in place of "name":

hello my first name is george
hello my name is george
hello my name is george

Now we can run the macro typing '@a'. Running it twice will complete the remaning two substitutions, giving us:

hello my first name is george
hello my first name is george
hello my first name is george

We could also run the marco a number of times with one command. Say, given the text above where the first substitution was done, if we wanted to run the marco twice in one shot, instead of invoking it two separate times, we can type '2@a'.

Thursday, September 8, 2011

Exceptions for Control Flow: Always Wrong?

It is generally accepted that exceptions should never be used for control of flow and should only be used for exceptional conditions. On face value, that assertion seems to make sense. For instance, given a method that iterates over an array, the user of the method should not be expected to catch a NoSuchElementException because the method does not make use of a hasNext() method.

If a state checking method is available to help determine if another method can be called, we would all assume it should be used. However, what about cases where a series of methods must be called in sequence to accomplish a larger overall task? In a scenario I'm thinking off, a series of individual methods must be called, where each in the sequence is called only if the previous call succeeded.

Would disobeying the exceptions rule possibly make for cleaner code in such a case?

To work out my thoughts, I thought of a home building example. Let's simplify building a house to three steps: laying a foundation, putting up the framing and walls, and then adding the roof.

Let's also imagine a contractor who's job is to build a house, ensuring its marked as condemned is any of the construction fails. If the contractor attempts to add the framing without the foundation, or the roof without the framing, a catastrophe would surely happen. To avoid the catastrophe, the builder must check the house to ensure the previous step completed before moving on to the next.

Like an Iterator with a hasNext() method, the House class has methods or state variables indicating whether it has the requirements for the next phase of construction and something similarly for its overall state: whether or not its livable or condemned.

    class House {
boolean hasFoundation
boolean hasFraming
boolean hasRoof
boolean isCondemned
}

The Contractor classs has one public method, buildHouse(), that returns a House, livable or not, and a private method for completing each step in the construction process:

    class Contractor {

public House buildHouse() {
def house = new House()

addFoundationTo(house)

if (house.hasFoundation) {
addFramingTo(house)
if (house.hasFraming) {
addRoofTo(house)
if (!house.hasRoof()) {
house.isCondemend = true
}
} else {
house.isCondemned = true
}
} else {
house.isCondemned = true
}

house
}

private def addFoundationTo(house) {
//...
}

private def addFramingTo(house) {
//...
}

private def addRoofTo(house) {
//...
}
}

This contractor is overly cautious as he wants to condemn the house as soon as possible if one of the constuction steps fails to avoid a catastrophe. Another implementation may wait till the building process is completed before condemning the house:

    class Contractor {

public House buildHouse() {
def house = new House()

addFoundationTo(house)

if (house.hasFoundation) {
addFramingTo(house)
if (house.hasFraming) {
addRoofTo(house)
}
}

if (!house.hasRoof()) {
house.isCondemned = true
}

house
}
}

This contractor only looks at the roof and the end of the process to determine if the house should be condemned, which may lead to a lawsuit if the someone where to change the order in which the steps were executed. The contractor's check at the end could include looking at the foundation and framing as well, but he is overly trusting of his workers not to proceeded and the extra checks may be costly.

What if a different contractor required a complaint be raised by a worker if any of the home building steps fails and condemns the house if he receives the complaint before attempting the next step?

    class Contractor {

public House buildHouse() {
def house = new House()

try {
addFoundationTo(house)
addFramingTo(house)
addRoofTo(house)
} catch (ConstructionComplaint complaint) {
house.isCondemned = true
}

house
}

private def addFoundationTo(house) throws ConstructionComplaint {
//...
}

private def addFramingTo(house) throws ConstructionComplaint {
//...
}

private def addRoofTo(house) throws ConstuctionComplaint {
//...
}
}

Here, a specific, but uniform, exception is given to the builder if any of the steps fail, ensuring the next step in the process is not attempted, avoiding a catastrophe.

An argument for this procedure may include that adding another step, like adding a garge, does not increase the complexity of the building process by adding more evaluation (branching), or require the builder to explicitly check that a garge can be added. Conversely, this approach may be overly trusting in that it requires a each worker method properly files a complaint.

I think it's safe to say we've all seen complex code as least as complex as the first implentation of the buildHouse() method. Is it worth asking that the use of exceptions would make the code cleaner? On the other hand, such cases usually present a situation where the user is required to code around what may be a poor design.

This topic and discussion may be nothing new, but I think it should help give thought to reasoning about the rule stated earlier regarding using exceptions for only exceptional conditions. Here were not talking avoiding programmer errors, such as trying to access a non-existent array element, but using exceptions to simplify a process.

While I'm not trying to suggest generally that using exceptions to control flow makes for better programs, I do think it is worthwhlie to consider such rules and understand why they may exist in the first place.