Archive for the ‘Java’ Category.

Communicating Sequential Processes in Java

Oft kann man die Probleme von Multithreading umgehen, indem eine hoehere Abstraktionsebene einsetzt, z.B. CSPs . Es gibt da auch eine halb offene Java Implementierung.

Parser- und CST-Generator verfügbar

Den Rest des Tages habe ich auf nerdischere Art und Weise genutzt und meinen Parser- und Syntaxbaumgenerator MetaGen in einen präsentablen Zustand gebracht.

Es gibt ein Beispiel für die Auswertung einfacher algebraischer Ausdrücke und ein hübsches Tutorial am Beispiel einer Konfigurationsdatei.

Das Ding erzeugt Java Quelltext und der erzeugte Code benötigt die antlr Laufzeitumgebung.

Top four Java Problems

* The literal syntax is much too meagre. Ther is no Map, no Collection, no List, no multiline String,
no expression substitution in Strings.

* The standard libraries provide poor abstractions and little convenience.

* There is no clean systax for block closures.

* It’s statically typed without providing proper generics or some kind of double dispatch.

Broken Java

This morning I had to write the code to initialize a field to one year before today. It was *four* lines. And it is not type safe, but using magic int constants.

Java Quiz

Suche elegante Möglcihkeit das untenstehende Idiom in generischer Form zu implementieren, da ich insbesondere das put gerne vergesse. Any Ideas?

map = ....;

//probably a loop here:
key = ....;

Element element;
if (map.containsKey(key)){
    element=(Element)map.get(key);
}
else{
    element=new Element();
    map.put(key,element);
}
//work with element

Beyond Java

After my recent post about the advent of the sunset of java I’ve read Bruce Tate’s “Beyond Java”, which seems to fall into line with my argument.

What I did particularly like about the book was the statement that Java is a language for system programming (which cached in on a lot of shortcomings of C/C++), but not an application language.
He tries to give us an idea of the things to come. As examples he points to Ruby on Rails and Seaside. What I miss in his book is the non-web perspective, because currently we see a trend towards real multi tier apps, that have a web(service) tier and a richclient (AJAX, Flex, Laszlo whatever) tier. The real richclient is gathering steem driven by IBMs Eclipse RCP endeavour.

And what I see currently is that the Java community itself is falling apart into different camps:
* The Webapps folk (Spring and friends)
* The Swing folk
* The Eclipse folk

They all employ their own utilities and modelling/ meta-approaches.

Another thing that Bruce does not mention is the integration power of dynamic languages. Ruby has excellent support to wrap C libs (not comparable to the average JNI-nightmare) and so has Python. Both languages provide bindings to dynamically support windows OLE automation in a natural way (by calling methods).

Commons Collections

Today I had a glance at commons collections. I’m convinced, that the more mature parts of the commons are what sun forgot about. If you know and use them you’ve definitely got a competive advantage.

But now for the code:

public class CollectionsDemo {
    public static void main(String[] args) {
        List list= Arrays.asList(new String[]{"Hund","Katze","Huhn"});
        List hList = (List) CollectionUtils.select(list,new Predicate() {
            public boolean evaluate(Object object) {
                return ((String)object).startsWith("H");
            }
        });
        System.out.println(hList);

        List upperList=(List)CollectionUtils.collect(list, new Transformer() {
            public Object transform(Object object) {
                return ((String)object).toUpperCase();
            }
        });
        System.out.println(upperList);
    }
}

It’s quite terse, isn’t it. The typecasts make the whole thing a bit awkward (but generics to the rescue). Just feel the power of closures. And of course I don’t want to deprive you of the output of the lines above:

[Hund, Huhn]
[HUND, KATZE, HUHN]

It’s been around for almost 30 years, but nobody told us! Martin Fowler recently wrote about these idioms in ruby/ smalltalk.

Exit mit throw statt return

Wie hier schon zu lesen war bin ich ein großer Freund der Exception, auch als Kontrollstruktur (für den Ausnahmefall). Eben hatte ich wieder so einen Fall, in dem ich besser eine Exception geschmissen hätte ,statt mit false zu “returnen.” Das ging etwa so:

public boolean myOperation(){

  if (!preconCheck1){
    log("precon 1 failed")
     return false;
  }

  if (!preconCheck2){
    log("precon 2 failed")
     return false;
  }

 performActualOperation();
 return true;
}

Jetzt war es so, dass die Prüfung der Vorbedingungen immer umfangreicher wurde.

Nun wollte ich den Code etwas aufräumen, da noch einige Modifikationen notwendig geworden waren. Mein Instinkt sagte mir “Extract Method”, aber leider hat der Vorbedingungscheck mehrere Exitpoints. Ich müsste den boolean als Rückgabewert der Methode verwenden und nach aufruf prüfen und ggf. mit return false abbrechen.
Problem ich hatte auch noch einen echten Wert zurückzugeben, ganz abgesehen davon, dass mir meine IDE die Sache nur ohne das Flag geschenkt hätte.

Stilfrage

Ich habe folgende drei Variante einer Methode implementiert und hatte einen erbitterten Streit, welche denn die klarste und wartungsfreundlichste sei. Daher würde ich gerne mal wissen, wie Ihr das seht. Also kommentiert recht eifrig!

Variante 1

private void updateActions(){
		boolean kundeSelected = kundenAuswahl.getSelection()!=null;
		removeKunde.setEnabled(kundeSelected);
	}

Variante 1a

private void updateActions(){
		removeKunde.setEnabled(kundenAuswahl.getSelection()!=null);
	}

Variante 2

	private void updateActions1(){
		if(kundenAuswahl.getSelection()!=null){
			removeKunde.setEnabled(true);
		} else {
			removeKunde.setEnabled(false);
		}
	}

Velocity Alternative

Da bin ich gerade drübergestolpert: StringTemplate

Sieht sehr interessant aus, für die Freunde der Codegenerierung…