Tags

Invoke on varargs

April 30th, 2006

The Java5 varargs feature is a nice one, something missing from the C/C++ world and eventually implemented in a much nicer way though with some caveats. I know what I am talking about - I encountered with a colleague a nasty bug in C++ code that was due to a misunderstand in the varargs feature. Eventually we removed all vararg calls in favor of a Java old-style call. This triggered me of course to look into Java’s varargs more deeply, especially when dealing with reflection.

To understand fully the scope let’äs look back to C/C++. In C varargs are used like this:

void myprintf(const char *fmt, …)

{

const char *p;

va_list argp; //declare the list

va_start(argp, fmt); // start iteration

while (…) {

i = va_arg(argp, int); // fetch next element as an int

}

va_end(argp); //cleanup

See for the full example and explication Steve Summit’s C Programming Notes Do you see where we determine that the list is exhausted? It must be somewhere in the while-condition. The problem is that you cannot do it without additional information. There is now way to tell wether they are 0, 5 or 500 parameters given. Even it was someone a second problem remains that might defeat this immediatly: va_arg() takes the type to be ready as an argument, so reading a long will take the data you could read with two ints. Type-safety - we have heard of it. Functions like printf() solve this by parsing the format string to find out which parameters have to be read (and how many), alternativly a count is passed (brr) or a 0 is by convention the last parameter (how to pass a zero-value then? In short: A dangerous tool.

Java Varargs are only syntactic sugar: myArgs(String … args) is equivalent to myArgs(String[] args) - try to declare thes methods within a single class and you’ll see the compiler complaining.

The compliance goes that far that these calls are all legal:

v.myArgs(); // passes a new String[]{}

v.myArgs(”d”,”e”,”f”);

v.myArgs(new String[]{”g”,”h”,”i”});

All work because args is a String[]. Should one rely on that? Say, is it really OK to write

void myArgs(String … arg) {

String[] args = args;

This is legal Java, but isn’t the equivalency vararg-array not just an implementation detail one must not rely on?

Difficult to tell from the short notes Sun provides with the JDK, but there are some hints that confirm the hypothesis:

  1. Many methods from reflect for example had been redeclared to accept varargs where an array had been used before, these methods can still be called from pre-Java5 code.
  2. The use of reflection on vararg-methods

To fiind the method defined above use v.getClass().getDeclaredMethod(”myArgs”, String[].class); this is the way reflection code can access such a method, so the argument is actually of this type.

A caveat is the invoke, it had been refactored to use varargs, but calling a vararg-method has some surprises left for you

m.invoke(v, “1″,”2″); // wrong number of arguments

m.invoke(v); // again

m.invoke(v, new String[]{”5″,”6″,”7″});

The last one shows a warning in Eclipse:

The argument of type String[] should explicitly be cast to Object[] for the invocation of the varargs method invoke(Object, Object…) from type Method. It could alternatively be cast to Object for a varargs invocation

m.invoke(v, new Object[]{new String[]{”5″,”6″,”7″}}); // this finally works

The last call is a bit quirky, the idea for refactoring the method invoke was that you can invoke foo(a,b) via f.invoke(o,a,b) - this does not work when using varargs if the only arguments are varargs, there you have to go back to the old style. In all other cases the reflection can distinguish varargs properly:

myArgs(String[] a1, String … args)

can be invoked as m.invoke(obj,new String[]{”a1″},new String[]{”5″,”6″,”7″}) (as expected ) but not by m.invoke(obj,new String[]{”a1″},”5″,”6″,”7″) which will throw again wrong number of arguments.

Conclusions

So why is this so much better than the C-style? An array provides the length member so you can tell how many parameters are in the call. Also an array is typed and even if it is just and Object[] you can use reflection on each element individually.

Another thing is if the varargs should be used at all. Frankly, during 10 years C/C++ I implemented a single function accepting varargs, I mostly relied on passing collections. So as varargs in Java are collections they provide a syntactically cleaner alternative to the new Object[]{} clutter.

As reflection code requires the clutter any way should the calls be implemented using arrays? I don’t think so for two reasons:

  1. The clutter (cosmetic issue, although I met many programmers that were surprised to see that you can instantiate an array the way I did above)
  2. Future JVMs could exploit the varargs notations for optimizations by assuming that they receive a read-only array

Well, the last one could also be an argument against its usage…

(this article got reposted after being accidentally deleted)

Grail [was: Groovy On Rails]

April 30th, 2006

Yesterday I made my first steps with Grails, actually I wanted to get something started with RoR, but I decided otherwise.

What I like with Grails is that it is more suitable for Java-developers like me that have experience with the JavaSE/EE techniques, so you can build on that when you leave the scaffolding phase.

Things I like with Grails over RoR:

  1. You can deploy as a war
  2. Groovy leverages easily existing java-code
  3. Testing with a in-memory DB (this makes Unit-tests managable)

On the contrary

  1. It is less dynamic
  2. The ant-clutter
  3. The poor documentation

Well finally, I decided not to use any of this xRails at all. Perhaps the things that are of interest for me are not suited for this style of development or it is the general idea that doesn’t fit me.

I think Jason Hunter is right, xRails is eating the cake while we are struggling with the recipe. My long-term prediction is that all this stuff will have to evolve to grow up and becomes then equally or more complex than J2EE. Or it gets stuck because JavaScriptOnSkies will take over the low end. This will fit perfectly the general trend to mediocracy.

The wrapping aspect

April 30th, 2006

This is a follow-up to a previous post.

A thing super-packages address well is wrapping. By “crippling” a package to the parts you to be used in your project it is very effective, because no wrappers are needed. Nevertheless you still use the types of the (third-party) package and all the architectural features that will worm into your system. Nowdays IDEs make wrapping (if you like an API) a trivial refactoring process, so you save little work by wrapping everything, so the only thing that could possibly hold you back is that another call-layer is introduced (which should get eliminated/inlined by the compiler).

Something very common when implementing an API is the creation of Impl(?) types.

I have the habit to use adjectives for behavioral interfaces like Cloneable, Serializable and nouns for interfaces that represent entites like Policy, Customer. The canonical classes implementing these interfaces get “Impl” appended to their name. This strategy will get terrible when dealing with inheritance among classes without having a corresponding hierachy for their interfaces - when extracting an interface from a class I there prefix them with “I” to denote the interface.

The implementations usually have members that are not in the interface. When passing it within the library you refer to these member by downcasting the received type. This is something I find quite ugly. It is a bit the same as with Collections, with the difference that generics cannot help here.

An example, you have a factory that creates Nuts. Your users love nuts and somethime they like to make Cookies from them. So they pass their Nuts into the Bakery-instance to get hot nutty cookies. Well your implementation of Bakery is quite strict when it comes to the quality of nuts it uses - no traces of peanuts allowed, only the NutImpls will pass the quality exams. As Bakery.throwIn(Nut nut) is declared in your API, you cannot express this by just implementing Bakery.throwIn(NutImpl nut), because with just that method the interface Bakery is not satisfied.

So what are our options: Read the rest of this entry »

OSS 177 - Le caire nid d’espions (F 2005)

April 30th, 2006

Retro-Kömodie à la James Bond und Pink Panther

Handlung

Französischer Geheimdienst - OSS117 sucht den Mörder seines Freunds Jack in Kairo. Schöne exotische Frauen werfen sich um seinen Hals und Hubert tut was er kann die Situation zu verkennen.

Warum sollte man den Film sehen?

Wenn der Charme Seen Connery’s als James Bond etwas zu dicke  (geworden) ist - hier gibt es noch eine Lage drauf. Selbstironie ist der Schlüssel zur Komik dieses Film. Hubert ist so borniert französisch, dass er sogar noch stolz darauf ist.

Wirklich brillant ist auch der Stil der 50er umgesetzt. Die herrlichen Einstellungen im Cabrio, die Fahrerin dreht wie wild am Lenkrad - außer sie zündet sich eine Zigarette an - vor dem Hintergrund einer offensichtlich projezierten Landschaft.

Alte Motive aus Prügelszenen, wie hat man sie doch vermisst - alles kommt wieder!

Was nervt

Wahrscheinlich habe ich es versäumt die kleinen Fehler im Film zu zählen. Für Freunde des Spotting sicher eine Schatztruhe - allerdings allsamt sich absichtlich eingebaut.

Am Rande: Beim Kauf der Karten, habt sich meine Freundin versprochen und Karten füpr OSS118 verlangt - die ANtwort war prompt: “Das wird die nächste Episode sein”

Popetown

April 30th, 2006

Da freut man sich auf ein langes Wochende mit der “Zeit” und, bumms wirft man Azureus an, um eine der sagenumwobenen Popetown-Folge zu saugen.

Ich habe auf die Schnelle nur einen torrent aus Neuseeland gefunden, also bedurfte es etwas Geduld.

Pas grave, Samstag ist Putztag und einkaufen muss man ja auch.

Nachdem Bayern das Pokalfinale leider nicht verloren hatte (60′ lang bestand immerhin die Chance sich an neuen Ausfällen von Dieter H. aus M. zu erferuen),  freeplayer an und mal gucken.

Bof. Viel Wind um nichts. Popetown ist ein infantiles Pseudo-Satirestück für ein Publikum, das seine anale Phase noch nicht ganz hinter sich gebracht hat. Wer da “Wider-der-Blasphemie-Aktionen” wie stoppt/anti-popetown (ich werde einen Teufel tun, die auch noch zu verlinken) und ähnliche (mit Segen von Kath.NET, ROFL) hat irgendwie spezielle Probleme.

Den Produzenten von Müllsendungen gehen langsam die Szenarien aus. Diesmal musste der Vatikan dran glauben, aber ich denke dort ist man eher gelassen - es sind schon andere Stürme über die katholische Kirche hinweg gezogen.

Ich finde den kleinen dicken Papst auf seinem Pogostick ganz drollig und bin froh, dass die Macher der Senduing nicht gesteingt werden (OK, man sollte sie steinigen, aber nicht des Sujets wegen, sondern wegen des Lebenszeitdiebstahls sich den Blödsinn angucken zu müssen). Das war ja vor einiger Zeit ein Fest für “uns” Christen, dass wir ja so tolerant sind und “die Moslems” gleich zum Heiligen Krieg aufrufen, wenn eine dänische Eimerkopfpostille schlechte Karikaturen des Propheten veröffentlicht (Ich lasse die Frage wie ein Land wie Dänemark in die EU passt mal außen vor).

Meine Theorie zum Aufruhr in der islamischen Welt damals war, dass es nur darum ging den Zorn auf etwas externes zu schüren, um so von den eigenen Problemen abzulenken. Ich bin der Meinung, dass es bei den religiösen Eiferern nun nicht anders ist. Interessant etwas über diese Probleme zu erfahren.

Java has no friends

April 29th, 2006

The design of multi-level APIs in Java is not well supported and as it seems there is something going on to support it better in the future. It has also been a shoprt topic in the Java Posse PodCast recently.

Well, for me as for the java posse it boils down to have something in Java like friend in C++. What does friend do: A class can declare another class as friend (or just one method of it) to grant it a special access privilege. A typical application is the Visitor pattern, where the visitor can be granted the right to call some private methods.

The poor man’s replacement is the default visibilty, so instead of declareing members private you declare them with no visibilty modifier. This means that you have to arrange the package-structure of your code according to the required access rights. This is not feasible any more of if you have many classes that need only few “private communication”.

The discussion at Sun goes around a construct called superpackage. The superpackage is an aggrgator that list member package that can see each other (using the ordinary rules) and a list of exported members that are accessible from the outside. In short, I don’t like it. It feels ill to me that adding something global, outside the packages I or others have implemented excerts some control, even if it just tightens the system. It will be very hard to enforce and comprehend the desired or undesired effects. A good thing is that you can limit the use of a third-party library in your project by exporting the desired (or certified) members only without wrapping everything into your own classes and interfaces (which I would recommend for any project with an expected lifetime of more than a year anyway). Read the rest of this entry »

Camping (F 2005)

April 27th, 2006

Auf dem Campingplatz werden wir alle zu besseren Menschen

Handlung

Die grossen Ferien beginnen, die Städte verwaisen und alle Welt findet sich auf dem Campingplatz ein um Juli/August in einer Parallelgesellschaft zu verbringen. Eine Autopanne wirft den Schönheitschirurgen Michel und seine Tochter in diese Welt seltsamer Rituale.

Warum sollte man den Film sehen

Ein  purer Unterhaltungsfilm, der mit einiger Ironie franz. Lebensart, wie wir sie aus Büchern kennen mit der franz. Realkultur aufeinander treffen lässt.

Jede Menge Komik ohne jedoch in Albernheiten abzurutschen.

Highlight ist ein Auftrittt des Rallye(alt)stars Ari Vatanen (Ersagt ein paar Worte auf Finnisch, ich werde die Übersetzung nachrreichen sobald ich sie habe).

Was nervt

Ich werde mir jetzt wohl mal BNs und Benco kaufen müssen um den Witz ganz zu verstehen.

L’Iceberg (B 2005)

April 26th, 2006

Absurdes Theater zwischen Frittenbude und Nordmeer

Handlung

Fiona ist Manager in einem Fastfoodrestaurant, eines abends sperrt sie sich versehentlich im Kühlraum ein und überlebt. Das Erlebniserzeugt die fixe Idee einen Eisberg besteigen zu müssen. Mit einigen Wirrungen fährt sie mit Réné gen Norden, verfolgt von ihrem Ehemann.

Warum sollte man den Film sehen

Für Liebhaber von absurdem Theater und Filmen von Buster Keaton und Jaques Tati fast ein muss. Sehenswert: Der längste Gähner der Fimgeschichte und die langweiligste Familie.

Obwohl fast überhaupt nicht gesprochen wird sind alle Charaktäre fein gestaltet.  Die Rahmenhandlung sorgt für einen besondere Pointe. Ob der Film ein Happy-End hat bleibt dem Zuschauer überlassen.

Besonders gefallen hat mir die Bühnenhaft Bildaufteilung.

Was nervt

Nervig ist der Film, aber das macht hier den Reiz aus.

Fernsehserien (lieber nicht)

April 23rd, 2006

Für die Freunde von Java, die mit “24″ nichts anfangen können (ich hatte nach 3 Folgen genug): Das Java Programm, das die Episoden generiert

Im deutschen Fernsehen braucht man keine ausgeklügelten Programme um kein Proramm  zu machen. Stromberg z.B.: 80%* abgekupfert von der UK-Serie The Office, aber nicht weitersagen: Ansonsten müssten Doof7 und SattBlöd noch Tantiemen abdücken, dass ist nicht gut für den Aktienkurs.

* die fehlenden 20% setzen sich wie folgt zusammen: 10% britischer Humor (nicht übersetzbar für die deutsche Dialogverbrecher), 5% Wiederholungen von Motiven, die schon im Orginal eher schwach waren, 5% individuelles Talent der Darsteller in D gibt es kein Casting mehr - nur noch Play- und Preislisten.

Log & capture (and replay)

April 23rd, 2006

This is somewhat a follow up to my blog on (non-reusable) components. I advocated there small components with simple interfaces that get tied together to implement the actual feature.

On DI and how to implement this much had been written, so the composition and the necessary techniques are common.

The communication among the components is less stamdardized and becomes quite a problem when dealing with many components.

The component technology du jour is SOA. SOA is using BPEL in an Orchestration manager to define and execute a complex operation. As a backbone of SOA WebServices get mentioned the most (there are other options). So what the orchestration-manager practically does is sending SOAP-Messages to different machines and collecting the results, to form new call and so on. When you keep all messages send, you can replay them eventually to duplicate the process.

This is very interesting for the analysis of errors. A complex business-function uses millions of lines of code and you have to have a tool to replay the action to see what happened and what exactly went wrong. The hardest bugs are the phantoms, the bugs you cannot reproduce but keep popping up at you customer. Read the rest of this entry »