2011
10.27

So, it’s more than two years since I started to use Groovy.
At the beginning I solved couple Project Euler problems and moved to scripting. I still love Groovy, but couple months ago I started to look at Scala. What can I say about it?

IT IS AWESOME

Until I started using it, I was thinking that dynamic typing is just a hidden cost of all the features I get with Groovy. Errors at run-time were painful, but I quickly learned the patterns to follow when developing dynamically typed code.

With Scala I found out that static typing can be used together with all those higher order functions, functional programming etc. And it makes me much more comfortable.

I approached Scala the usual way. I solved first problem from Project Euler. It worked fine, but I didn’t like the style. There was too much Java in my Scala code and I knew it can look better, more functional. And the only functional language I had been using so far was Haskell.
So, I took a Haskell tutorial from and started to look for similarities in Scala. Rewriting Project Euler’s solutions in functional style was a lot of fun and training for my brain. Now it’s more natural.

Since I posted solution for the Problem 024 in Groovy. Here’s one in Scala:

object Problem024 extends App {
  val nums = (0 until 10).toList.permutations
  val result = nums drop(999999) next() map(_.toString) reduce(_+_)
  Console.println(result)
}

It’s a simple bruteforce. What is beautiful about it? The List.permutations method returns Iterator. In Groovy similar method returns a Set which makes it almost useless. There’s an alternative method in Groovy Collection.eachPermutation, but it takes a closure as a parameter. The third option is using PermutationGenerator which returns an Iterator, which I didn’t know of two years ago.

What I see is that Scala’s type system is really well thought. If there are or were any glitches, they were quickly fixed (from small version to small version). It’s not four two years development cycle like in case of Java.

So far, I’ve solved more than 40 problems in Project Euler. You can see sources at https://github.com/bibix/euler. And many of them are one-liners thanks to Scala.

And you can always follow me on Twitter

2011
03.07

Build files tend to grow in time. New tasks are added, some customizations are made and you end up with several pages of groovy code. Gradle is based on Groovy, so many constructs can be really simplified, but often it’s not enough. That’s where Gradle comes in. You can split your build files into logical pieces:

// in build.gradle
apply from: "libraries.gradle"
apply from: "subprojectsTasks.gradle"
// in libraries.gradle
versions = [
  abc: "1.6"
]

libraries = [
  abc: "org.abc:abc:${versions.abc}"
]
// in subprojetsTasks.gradle
subprojects {
  apply plugin:"java"

  dependencies {
    compile libraries.abc
  }
}

And that’s it. You can safely split your build file into logical parts.

2011
01.20

I believe you’ll find this in every gradle project you can download from the net. Since it’s groovy it’s best to just declare a map with your external dependencies in root project. You can then use it in your subprojects just by accessing a key from map.

Let’s see a sample configuration:

// def versions would create script local variable
versions = [
        camel: "2.5.0"
]

libraries = [
        camel: [group:"org.apache.camel", name:"camel-core", version:versions.camel],
        camelBindy: "org.apache.camel:camel-bindy:${versions.camel}"
]

You can see two maps actually: versions and variables.
First one defines versions used for particular libraries. Since camel version is used in multiple places, you can just extract it and keep outside the libraries definitions.
Libraries is a map of our dependencies.

Usage is also simple:

// somewhere in root project or subprojects
dependencies {
  compile libraries.camel
  compile libraries.camelBindy
}
2010
11.28

It’s good to have project separated into modules. It encourages separation of functionalities and simplifies code. Fortunately gradle supports multiple projects very well.
Having a project with 2 modules like this:

- awesome-project-root
-- build.gradle
-- settings.gradle
-+ persistence
---- build.gradle
-+ processing
---- build.gradle

Next thing is to add to settings.gradle several lines with subprojects:

include "persistence"
include "processing"

Since now you have 3 build.gradle files in your repository. They are configured as subprojects. You may read more about subprojects in gradle’s documentation. It may be confusing when your projects grows up and you’ll have more of them.

Really nice thing I’ve found in hibernate’s configuration (see https://github.com/hibernate/hibernate-core), is renaming of all these build.gradle files.

rootProject.children.each { project ->
    project.buildFileName = "${project.name}.gradle"
    assert project.projectDir.isDirectory()
    assert project.buildFile.isFile()
}

This little code snippet lets gradle know that your project’s structure will be:

awesome-project-root
-- build.gradle
-- settings.gradle
-+ persistence
---- persistence.gradle
-+ processing
---- processing.gradle

And this really simplifies navigation. I think it’d be nice if gradle supported both naming conventions.

2010
02.22

In previous post I mentioned about the visitor pattern and how to use it in Java. I also use groovy in my projects and there’s a much better way to solve the problem with processing collections.

I have found a site about shortcomings of the visitor pattern.
The proposed solution in Nice programming language are, so called, multimethods.
I asked myself if I could use similar solution in groovy. The answer is yes, fortunately. Multimethods (or multiple dispatch) can be used in groovy.

In groovy you don’t have to implement visitor pattern and extend your domain objects. The following code will work just as you would expect:

// Base class
class Feature {
    String name

    public String toString() {
        return "Feature{" +
                "name='" + name + '\'' +
                '}';
    }
}

class BooleanFeature extends Feature{
    boolean value

    public String toString() {
        return "BooleanFeature{" +
                "value=" + value +
                '}';
    }
}

class StringFeature extends Feature{
    String value

    public String toString() {
        return "StringFeature{" +
                "value='" + value + '\'' +
                '}';
    }
}

// Class that processes Feature and its descendants
class Multimethod {
    def printFeature(Feature feature) {
        println "printFeature: $feature"
    }

    def printFeature(BooleanFeature feature) {
        println "printBooleanFeature: $feature"
    }

    def printFeature(StringFeature feature) {
        println "printStringFeature: $feature"
    }
}

Feature feature = new Feature(name:'feature')
Feature booleanFeature = new BooleanFeature(name:'booleanFeature', value:true)
Feature stringFeature = new StringFeature(name:'stringFeature', value:'Hello world')
List<Feature> features = [feature, booleanFeature, stringFeature, otherFeature]

Multimethod multimethod = new Multimethod()

features.each { multimethod.printFeature it}

The output is:

printFeature: Feature{name='feature'}
printBooleanFeature: BooleanFeature{value=true}
printStringFeature: StringFeature{value='Hello world'}

You can see the Feature class and some simple hierarchy. They represent domain classes. The Multimethod class is our processor. It would have to be a Visitor in java, in order to correctly process the collection of Feature elements. It’s not the case in groovy, as it dynamically resolves the type of parameters during runtime.

It saves a lot of coding. Now there’s no need to create class hierarchy only to process a collection properly. This also means, that there’s no need to overload a method for all classes that extend the Feature class.

2010
02.14

This is a really nice and simple pattern. Imagine having a collection of objects. Let’s have a class Feature with single method String getName(). Of course the class hierarchy grows in time and here come two additional features: BooleanFeature and StringFeature. They override the original getName() behaviour.
And it looks like that:

class Feature {
    public String getName() {
        return "Feature";
    }
}

class BooleanFeature extends Feature{

    @Override
    public String getName() {
        return "BooleanFeature";
    }
}

class StringFeature extends Feature{
    @Override
    public String getName() {
        return "StringFeature";
    }
}

That’s a common hierarchy. I’m sure you’ve seen bigger trees.

So, you get a list of Feature objects and you know that some of them are BooleanFeatures, others are StringFeatures. Something similar to:

List<Feature> features = new ArrayList<Feature>() {{
    add(new Feature());
    add(new BooleanFeature());
    add(new StringFeature());
}};

Nothing fancy. Three elements, each of different type. Now, you’re to process each element in different way. It’s java, it can’t be difficult. The processing is the printIt(...) method, which prints the type it processes and the name returned by getName().

class Printer {
    public void printIt(Feature feature) {
        System.out.println("Printing Feature: "+feature.getName());
    }

    public void printIt(BooleanFeature feature) {
        System.out.println("Printing BooleanFeature: "+feature.getName());
    }

    public void printIt(StringFeature feature) {
        System.out.println("Printing StringFeature: "+feature.getName());
    }
}

public class PrintNames {
    public static void main(String[] args) {
        List<Feature> features = new ArrayList<Feature>() {{
            add(new Feature());
            add(new BooleanFeature());
            add(new StringFeature());
        }};

        Printer printer = new Printer();
        for(Feature feature : features) {
            printer.printIt(feature);
        }
    }
}

Logic is simple, but does it produce what we expect? The expected output looks like this:

Printing Feature: Feature
Printing BooleanFeature: BooleanFeature
Printing StringFeature: StringFeature

and actual result:

Printing Feature: Feature
Printing Feature: BooleanFeature
Printing Feature: StringFeature

WHOAAA, the override worked fine, but what happened to the printed types? It looks like the printIt(Feature feature) has been called for each element. What about the other two methods?

If you have been playing java for some time, you know why that happened. Java resolves types at compile time. It means that it sees a list of Feature elements. During compilation, Feature is the only known type kept in the list, so the printIt(Feature feature) method is being used. Advantage of this is faster execution, as there are no type checks during runtime. Above you can see a disadvantage of compile-time type resolution.

Here starts usage of instanceof operator. It hides in many forms. You can create a single method composed of consecutive if-elses and mentioned instanceof checking or create some external class hierarchy that processes Feature in per-subclass manner (using instanceof ;) ), etc.

There’s one solution, which doesn’t introduce the usage of instanceof operator. It’s the Visitor Pattern. How does it work? Well, the common ancestor (Feature in this case) and all its children have to implement function void accept(Visitor visitor>. The implementation is a one-liner: visitor.visit(this). And it’s the same for each class.

class Feature {
    public String getName() {
        return "Feature";
    }

    public void accept(Visitor visitor) {
        visitor.visit(this);
    }
}

class BooleanFeature extends Feature{
    @Override
    public String getName() {
        return "BooleanFeature";
    }

    @Override
    public void accept(Visitor visitor) {
        visitor.visit(this);
    }
}

class StringFeature extends Feature {
    @Override
    public String getName() {
        return "StringFeature";
    }

    @Override
    public void accept(Visitor visitor) {
        visitor.visit(this);
    }
}

The Visitor interface has three visit methods – one for each type it can visit.

interface Visitor {
    void visit(Feature feature);
    void visit(BooleanFeature feature);
    void visit(StringFeature feature);
}

All magic is behind this. The accept(Visitor visitor) implementation in each ...Feature calls the visitor.visit(this) method. During compilation, the type of this reference is known in each element, so the compiler can link it to correct method in the Visitor class.

The Printer class just implements the Visitor interface.

class Printer implements Visitor {
    public void visit(Feature feature) {
        System.out.println("Printing Feature: " + feature.getName());
    }

    public void visit(BooleanFeature feature) {
        System.out.println("Printing BooleanFeature: " + feature.getName());
    }

    public void visit(StringFeature feature) {
        System.out.println("Printing StringFeature: " + feature.getName());
    }
}

public class PrintNames {
    public static void main(String[] args) {
        List<Feature> features = new ArrayList<Feature>() {{
            add(new Feature());
            add(new BooleanFeature());
            add(new StringFeature());
        }};

        Printer printer = new Printer();
        for(Feature feature : features) {
            feature.accept(printer);
        }
    }
}

And the output is as expected:

Printing Feature: Feature
Printing BooleanFeature: BooleanFeature
Printing StringFeature: StringFeature

What’s worth noticing is that in opposite to previous calls, now the feature accepts the printer object.

Thanks to the Visitor Pattern, you can extend your classes with additional features. The main disadvantage is that any changes in class hierarchy (eg. introducing a class IntegerFeature), result in adding new methods to Visitor interface and all classes that implement it. But you can always create a default/abstract implementation: DefaultVisitor that will be a father for all implementations.

Think of it next time you start processing a collection using the instanceof checking.

2010
01.17

To take full advantage of groovy it’s good to know additional methods extending standard java objects. I often visit groovy jdk, to see what actually is new in groovy.

Operations on collections really speed up the work. In jdk you can see what operators are available for particular objects. For reference of methods used to override operators go here: http://groovy.codehaus.org/Operator+Overloading.

2009
12.14

Pressing Alt+Enter in Intellij in random places is sometimes beneficial. Today I’ve found a feature which has been built in Intellij since version 6.
So, Alt+Enter on String and I could inject a language… Nothing popped up in my mind.
inject… language… a list with languages is displayed… chose Java and I got Java validation in String literal.

That’s good. You can read more about it at JetBrains Confluence site.

2009
11.30

As recently I use Intellij most of the time due to fabulous Groovy support, I would like to use it also to play with JavaFX. There’s no planned support yet, so I played around with javafxc and javafx tools.

In Intellij there’s only support for syntax highlighting defined in Settings->File Types. There are two ways you can compile your files. First one is using External Tools. It’s good if you would like to compile only one file at a time. The second solution is creating an ant script.

I think that better solution is using ant build file to compile all *.fx files in your module. I used build file posted at stackoverflow.com:

<?xml version="1.1"?>

<project name="JavaFx" default="compile" basedir=".">
    <property environment="env"/>
    <property name="java.home" value="${env.JAVA_HOME}"/>
    <property name="jfx.home" value="${JAVAFX_HOME}"/>
    <path id="compile.classpath">
        <fileset dir="${java.home}/lib">
            <include name="**/*.jar"/>
        </fileset>
        <fileset dir="${jfx.home}/lib">
            <include name="**/*.jar"/>
        </fileset>
    </path>

    <taskdef classname="com.sun.tools.javafx.ant.JavaFxAntTask" name="javafxc">
        <classpath refid="compile.classpath"/>
    </taskdef>

    <target name="compile">
        <javafxc srcdir="${src}" destdir="${out}" includes="**/*.fx" executable="${jfx.home}/bin/javafxc.exe">
            <classpath refid="compile.classpath"/>
        </javafxc>
    </target>
</project>

Works perfectly.

Running is also simple. You need to create new External Tool for javafx.exe.
Go to Settings->External Tools and press Add button. After filling Name and Group there are three more fields needed:

  • Program:
    path to your javafx.exe
  • Parameters:
     -cp "$Classpath$" $FilePackage$.$FileNameWithoutExtension$
  • Working directory:
    $OutputPath$

The main disadvantage is that your fx file has to be placed in some package, but using packages is encouraged anyway, so it shouldn’t be a big issue.

You can run now your compiled fx class by right clicking on it and selecting external tool you just added.

2009
11.15

I had a problem with displaying correctly formatted code with this theme. The syntaxhighlighter decorates each token with <code> tag. It works fine unless something else defines style for code also. The theme does that. As the plugin is my primary formatter for the code, I just removed the style for the code tag from style.css file in pyrmont-v2 directory.
The removed code looks like that now:

 /*div#main div.post div.entry code{*/
 /*font-family: "Courier New", mono;*/
 /*background-color: #181818;*/
 /*border-left: 1px solid #2a2e2f;*/
 /*color: #197b30;*/
 /*padding: 5px 10px;*/
 /*display: block;*/
 /*}*/

Now any wp plugin based on syntaxhighlighter should work fine.