Java Tip #4: Switch comments

During testing, you often want to make things simpler. For example, if you want to test your new printing routines, you might want to see only the print preview instead of getting real printouts. You can switch between two code blocks by using the following pattern and by simply inserting or removing a single character:

//*
show_only_preview();
/*/
real_printing();
//*/

When removing the first slash, the second code block becomes active:

/*
show_only_preview();
/*/

real_printing();
//*/

Java Tip #3: Shorter code with static factory methods

Java code can look much cleaner and shorter when using static factory methods combined with import static. These are methods, which return a new (or reused) instance of a class. Let’s say we have a HashMap which should use instances of KeyClass for the keys and a tuple of ValueClass1 and ValueClass2 as its values. Instead of writing lengthy code like

HashMap<KeyClass, Tuple<ValueClass1, ValueClass2>>
  myMap = new HashMap<KeyClass,
      Tuple2<ValueClass1, ValueClass2>>();

you could just use

HashMap<KeyClass, Tuple<ValueClass1, ValueClass2>>
  myMap = map();

Therefor, we need to create a static factory method named map somewhere with the following code:

public static <T1, T2> HashMap<T1, T2> map()
{
  return new HashMap<T1, T2>();
}

And then, when filling the HashMap, you can again make use of factory methods. Compared to

myMap.put(myKey,
  new Tuple2<ValueClass1, ValueClass2>(
    value1, value2));

the following code is much shorter:

myMap.put(myKey, t(value1, value2));

Nice, how easy tuples (or triples, or quadrupels, …) can be created in Java! Remember, that import static is needed to make it really short. We do not want to write Tuple.t(...) everywhere where we instantiate a tuple, but really only t(...). This is nearly as short as in the programming languages which support tuples natively.

One other example, where we always use those methods, are fractions. Instead of new Fraction(1, 4); we always use fr(1, 4). Actually we made the constructor private, so that programmers must use the factory method. This leads to much cleaner code. One real example from Zong!: Instead of

new Chord(new Note(new Pitch(1, 0, 4)),
  new Fraction(1, 4))

we just have to write

chord(note(pi(1, 0, 4)), fr(1, 4))

Downloads: Fraction, Tuple2, Tuple3

Java Tip #2: foreach with index (2)

Time for another Java Tip. Last time I described the problem of losing a loop counter when using the foreach loop. I mentioned, that I have two solutions for this problem. Here is the second one:

I created a class named It (short for “iterator”). It is a Iterable Iterator (funny, but true: Not all Iterators are Iterable in Java…) which allows you to wrap any collection and use it within a foreach loop. Moreover, it contains the method getIndex() which returns the current value of the loop counter. For quick creation, there is the it factory method which you should import statically.

Here is an example:

It<Foo> fooIt = it(fooList);
for (Foo foo : fooIt) {
  //for each foo in fooList...
  foo.doSomething();
  //if you need the current index:
  System.out.println(fooIt.getIndex());
}

You can also write similar iterators, like ReverseIterator for an iterator which begins with the last element and ends with the first one. Enjoy πŸ™‚

Downloads: It, ReverseIterator

Java Tip #1: foreach with index

When you are working with Java some hours each day, you soon develop an own programming style and collect some ideas how to make your code nicer. From time to time, I’ll present some of my most favorite ideas here.

Today, let’s look at the foreach loop. I guess, you often use code like this:

for (int i = 0; i < list.size(); i++) {
  Element e = list.get(i);

Not really nice, is it? As Java programmers we are used to read and understand such code quickly, but there must be a better way, since what we want to say is only “For each element of the list…”. But hey, we have the foreach loop since Java 5:

for (Element e : list) {

Very nice, isn’t it? Unfortunately we have lost the index of the current element now, which was stored in the variable i before. For this, I’m using two solutions. The first one is using a custom iterator, which I will explain in a later Java Tip. The second one is using an index together with foreach, that runs over a Range (use import static of the Range.range method):

for (int i : range(list)) {
  Element e = list.get(i);

Though we do not get a one-liner, we get rid of the increment at least. The Range class is also very useful for other cases, for example when counting from 1 to 10:

for (int i : range(1, 10)) {

Downloads: Range

1229 errors left to solve for iteration 50

Although it was a little quiet in this blog during the last weeks, this doesn’t mean that we aren’t working hard on the next iteration. Haydn (Iteration 50) is really a hard nut to crack! Currently we are completely replacing the core of Zong! which allows to store and manipulate musical data. While this core part was heavily relying on side effects and mutable data, we are now moving to a core that contains only immutable, persisent data structures and embraces a much more functional style.

The idea to do that arised when I was learning Clojure. Although we do not use Clojure (yet), since it is still too complicated to call from the Java side, it is always a good idea to learn new languages and to gain insight into different programming concepts. This makes you even a better programmer in the language you are coming from! But now, what are the advantages of a functional core?

One good reason is the testability. Since there are no side effects, it is much easier to understand and debug the code. The same input always results in the same output, without influence of outer effects. Another reason is concurrency: Persistent data structures are thread safe by design, and it is never necessary to create defensive copies of your objects, because it is guaranteed that they can never be changed. But the biggest advantage from a user’s point of view is undo/redo functionality. While we wracked our brains how to undo side-effect based actions up to now, it is now trivial to undo each action: Just remember the root object before performing the action. This is brain-dead easy!

Unfortunately, Java was not designed for using immutable objects, so the code for implementing these classes is not as nice as it could be like when using Clojure for example. Neverless it is possible and often results in much nicer code when using these classes. We decided to use the pcollections library and it does a great job so far! Although it is still quite unknown, I am sure that it will get more attention soon, because the advantages of persisent data structures are really groundbreaking in my eyes.

How does the persistent core works? Basically, we have a tree of musical classes with the Score class as its root. It is immutable (nothing can be changed), so no backward links are possible. This is kind of a problem, since for example a chord belongs to a slur and a slur contains chords. This can not be directly modelled with immutable data structures. Therefor, we have a big hashtable at the root which save all Globals (beams, slurs, ties, attached elements like dynamics, musical positions of each element for very fast lookup, and so on). The staves, measures, voices and its element are represented in a tree structure like one would probably expect it.

Let’s say we want to add a note to an existing chord, which is beamed. Therefor, we create a new score, based on the old one (and of course sharing as much data as possible, which is never a problem since everything is immutable :)). When “changing” a chord, we also have to “change” its voice, then the measure the voice belongs to, then the staff the measure belongs to, and so on, up to the root. After that we have to update the Globals since our chord now has a new reference of course. This sounds more complicated at first, but the hierarchy of the elements in the tree is quite flat, and we are not using (much) more memory than we would need for the side-effect
based solution. Remember: While it is more efficient to work with side effects when performing some action, it may be a nightmare to undo it again! This is absolutely trivial using persistent data structures: Just remember the Score instance, perform your changes, and if you want to undo them again, just take the old Score instance. Cool, isn’t it? 8)

The changes are so radical, that I’m already working for more than 50 hours to integrate them into the other Zong! projects. There are still 1229 compile errors to solve… But I’m sure that the new core will bring Zong! a very big step forward – also because we solved the tremendous undo/redo problem by the way.

Tracker moved to new server

The exams are over – now it’s time to work on Zong! again. Since today, the bugtracker runs on our new homeserver and we also moved the private git repository to there. Thanks again to Phil for hosting them the last months (or even years)!

We are amazed how many people are interested already in this early stage of the project. Thanks to all the contributors that have sent us ideas, code and example files so far. I hope I’ll catch up soon and integrate them. If anyone would like to join the project, don’t hesitate to contact us πŸ™‚

Exam break

Due to our exams in the winter semester, we have currently no time left for developing Zong!. We are planning to continue in March. Our next big steps are the complete rewriting of the core (now only using persistent data structures, which makes for example undo/redo dead easy) and the setup of our own home server (running git and redmine for the tracker).

Clojure Concurrency

For a seminar at university I had to write about parallel programming on the JVM with Clojure. Because I am new to Clojure and did not believe all the euphoric statements about Clojure, I did not only prepare a paper and presentation slides, but also a little demo application called Clojure Sheep.

Clojure Sheep is actually based on Rich Hickey’s ant simulation he presented in his Clojure Concurrency talk, but I removed some logic to concentrate more on the concurrency features and to make it easier to also create a version written in Java. My experiences:

  • It’s quite easy to write the code in Clojure (I have to admit of course, that I had the ants source, which made it even easier ;)). You can fully concentrate on the application logic and don’t have to worry about locking. Instead, you are forced to use transactions at the right places.
  • But instead of thinking about locks, you have to think about for which data you want to use which concurrency primitives. For example, if I had used a single ref for the whole 2d vector of cells (instead of using a ref for each cell), this would probably decrease performance a lot.
  • The Java version was much harder to implement. I could not find a good locking strategy that guarantees maximum thoughput but still doesn’t worry me. So, to make the code as easy as in Clojure, I decided to use a global lock for everything. Of course, this destroys performance! (If you have better ideas, tell me. I already got some ideas from the Clojure mailgroup).
  • When testing on a quadcore machine with 1000×1000 cells and 1000 sheep, the Clojure solution performed about 50 times faster (!) than the Java implementation. This is not surprising given the bad locking strategy I have chosen – but it is cool when you think about the programming complexity of both solutions, which are about the same.

Overall, these results encourage me to try out Clojure for Zong! now. I think, I’ll begin to port some of the core code (basic data structures) to Clojure. Because of the immutable and persistent structures, this could already solve our tremendous open problem how to realize undo/redo in a fast and memory-saving way.

A little present

Merry Christmas πŸ™‚ As a little present, we are happy to announce the release of the alpha versions of the Zong! Viewer and Zong! Player, which are both licensed under the GPL.

Interested developers can check out the source code in our public Git repository. We have also prepared a demo for the Zong! Viewer. Notice, that you need Java 6 to run the applications.

We hope that this release encourages some people to join our development team. If you are interested, please don’t hesitate to contact us.