Tags

Great JVM news

April 8th, 2009

 The Google AppEngine opens up for Java. Python is a great language, but still a nice-language (compared to Java). A light-weight alternative to host Jav-applications in the cloud.

What some might have guessed is now official?: Twitter is doing its heavy lifting with Scala We don’t have to feel bad anymore to do write statically typed code:-)

Closure puzzler or enum references considered harmful

February 7th, 2008

SPOILER - don’t read this if you want to figure out the Neapolitan Ice Cream Puzzler by yourself!

Neal Gafter posted a Closure Puzzler that hasn’t too much to do with closures, but shows that Static initializers considered harmful is not limited to the old enum-pattern, but also applies to Java 5 enums. Here the Java 5 version of his code for those who don’t get the closures code or simply are too lazy:

import java.util.ArrayList;
import java.util.Arrays;
import java.util.List;

public class Compare {
	static <T, U> List<U> map(List<T> list, Transformer<T, U> transform) {
		List<U> result = new ArrayList<U>(list.size());
		for (T t : list) {
			result.add(transform.invoke(t));
		}
		return result;
	}

	public static void main(String[] args) {
	        List<Color> colors = map(Arrays.asList(Flavor.values()), new Transformer<Flavor,Color>(){public Color  invoke( Flavor f ){return f.color; }});
	        System.out.println(colors.equals(Arrays.asList(Color.values())));

	        List<Flavor> flavors = map(Arrays.asList(Color.values()), new Transformer<Color,Flavor>(){public Flavor invoke(Color c){return c.flavor;} });
	        System.out.println(flavors.equals(Arrays.asList(Flavor.values())));
	    }
}

interface Transformer<S, T> {
	T invoke(S s);
}

enum Color {
	BROWN(Flavor.CHOCOLATE), RED(Flavor.STRAWBERRY), WHITE(Flavor.VANILLA);
	final Flavor flavor;

	Color(Flavor flavor) {
		this.flavor = flavor;
	}
}

enum Flavor {
	CHOCOLATE(Color.BROWN), STRAWBERRY(Color.RED), VANILLA(Color.WHITE);
	final Color color;

	Flavor(Color color) {
		this.color = color;
	}
}

I think I have already seen such a backport already, but here it is again…

Java should stay Java (?|!)

December 16th, 2007

Josh Bloch’s talk at Javapolis caused quite a stir in the blogosphere, why is best summed up in a blogpost and its comments: Is Java a simple, less skill demanding language or is it - better can it be - also a home for programming geeks.There are two sides and a point can be made for both of them. As java had been need it was a geeky language - admittedly fueled by the internet hype - which attracted brillant minds. Thanks to these forerunners Java is now one of the top choices for mainstream programming. The ones of these who still stick around in the Java world now look with envy on Ruby, Scala and sometimes back on Smalltalk and want to use the ideas and techniques prevalent there in Java as well. But in practice - unless you happen to work at Google - most java programmers are not of this class. Big application written in Java are written and maintained by ordinary developers, not übergeeks that think in monads.The typical Java programmer in a large enterprise is more of the type of the VB programmer, perhaps he did some C or COBOL before. These people and their thinking about programming is deeply rooted in imperative style.A point could - and personally I think it should - be made if projects really require such large staff and if it weren’t better to use more advanced stuff to build it with fewer, but appropriately skilled developers (this is the Ruby claim), but face it, the enterprise world changes too slowly to accomondate for that.More than 10 years ago we evaluated some new development environments as a replacement for Oracle Forms 3. The most interesting candidates had been Forms 4.5 (obviously), Smalltalk (I don’t remember the vendor) and Franz Allegro CLOS (Ok, this had been the one I fancied). Java had been 1.1 or so in these days and the first looks at it were disappointing, C++ had been already in use, but there had been so many problems with it that it wasn’t ever really a consideration. Eventually we went for Forms because it would give our staff the easiest transistion. The main problem with Smalltalk and CLOS had been the paradigm shift. Neither the pure OO of Smalltalk nor the functional programming in Lisp were accessible to them.I think that the same could happen to Java if all the fancy functional programming (I love it!) would get into it. There are three problems

  • FP is not compatible with the mindset of the majority of enterprise programmers. Also FP programs are harder to debug - this is a problem for the prevalent trail-and-error programmer (aka debugging into existence)
  • Java is not Scala, one problem of BGGA is the non-local return. This isn’t an issue in true FP languages which are expression oriented, the statement oriented Java makes it awkward to deal with it
  • DSLs are in fashion and a powerful concept for layering a complex application, but they create as well new languages: You can’t hire a Lisp or C++ programmer and expect him to be immediately productive as they have to learn the DSLs of your projects first

I initially found CICE (which Bloch promotes) to come a bit short, but now I am convinced that this is the right way to change Java as it keeps the characteristics of the language and can easily integrate into larger teams in any organization.This is the curse of being a mainstream language, you most not let out you users in the cold.For the other classes of problems languages like Scala that run on the JVM could be chosen. There some research has to be done by the system architect(s) how such code can integrate with Java code and how maintenance can be organized. This isn’t a trivial problem as not everything from another JVM language integrates seemlessly with Java code (i.e. you use this code as if it was written in Java), as well the question has to be answered (in each indiviual organization) if there is enough stability in the project to support an other language throughout the life-cycle - imagine a freelancer writing some core code in a language only known by him.

Scala lift-off with liftweb

April 4th, 2007

What Rails did for Ruby had been at least started by the Lift Web Framework for Scala! It is Version 0.1.0 but it looks promising. Their website runs on liftweb, too - in fact they are running the example you can download and deploy on your Appserver. Behind liftweb are David Pollak and (among others) Burak Emir how contributed the XML-handling to Scala.

I had a brief look at the code; liftweb is based on Scala-Actors (the Scala implementation of the famous programming model made widely known by Erlang) which promises that it will be quite scalable.

This gave my Scala engagement another boost. And a setback. I installed the latest plugin for Eclipse (it is and had been always quite shaky) - good news: It comes with the compiler/runtime, bad news: It is the 2.3.4 version (current version is 2.4.0) and the preferences page has a bug that prevents you to set the path of your Scala installation.

Scala is for me quite interesting as it also allows to compile to .NET IL-code. This gives Scala a quite unique position as a language that allows you to write code for the two platforms once and run it on both of them.

Another feature that is nice is actually the only pain-point I have yet identified: Scala requires only Java 1.4 - good for people which are still stuck with that version, but bad for the rest of us:

Using implicit functions you can write

val list:List[Any] = MyJavaClass.getCollectionOfString()

But even if getCollectionOfString returns Collection it is impossible to write a conversion that allows to give list the type List[String]. Reason is that the implicit functions for the conversion would need a type parameter and Scala rejects a declaration

implicit def JavaCollection2List[T](coll : java.util.Collection[T]) : List[T] ={…

because “java.util.Collection does not take type parameters”.

If you think this is not an issue: Try dealing with a Map,List>… all this casting gets pretty ugly as casts are rare in proper Scala code, consequentely you get punished for doing it anyway by nice syntax obj.asInstanceOf[String]…

DRM in consumer space is dying, good day for open software

April 2nd, 2007

Small note at the end of the news on TV: EMI sells its music unprotected via iTunes!

End of last century I’d been working in the DRM business and we sold actually some music - well not much actually. The content holder provided little interesting content and the DRM software you had to install was secure, but an overkill. I still think that most buys came from within the company (BMG) or its competitors. You had been tied to a media-player which was even worse than the Windows one - you get the idea: Very unsatisfying user experience.

Fast-forward 8 years. DRM is facing even more resistance. As the open-source movement gained much more momentum and virtually all DRM relies on closed source portions with sometimes hefty certification procedures for the final product - DRM is closing out Linux user and also developers which use open languages like Java where such software will never have a good chance to be integrated.

As it seems now that the idiotic notion that all people who buy electronic media are actually assisting in theft/piracy has been overcome; open platforms will prosper even more. Let’s face it. 90% of the computer user do nothing else than surfing and consuming media with their computer. The half of remaining 10% do this at least half of the time. Freely usable media open this large reservoir of users for free software. And as these user don’t want anything more than just what bthey are doing now, they don’t need Vista Premium Home Media Standard edition (Which version of Vista do YOU need?). Some light-weight OS on whatever sufficiently recent CPU will do. Some cross-platform software (written in Java or etleast running on the JVM) gives all what Joe Homeuser needs. And that software will be there when playing media with non-proprietary software is not only a challenging game for free-software evangelists.

Finally this could give Java on the Desktop the thrust it needs to (finally) take off. The improvements of Swing layed ground to compete with other UIs. I am curious what we will see in the next year or two.

BTW: I actually can see some good uses of DRM. Perhaps I’d been a bit indoctrinated back than (we used to make the brain-washed Intertrust-zombie in the office). What about have a documentation expire when the new version of a software is deployed and been redirected to the new documentation? Sending a message in a secured envelope where you can control where it gets forwarded to? None of these needs an unbreakable system, as it should simply help the user of media to use it correctly. When you don’t need certified hardware and software you can never secure the use perfectly, but some open DRM solution could provide the benefits without the hassle.

Java Generics and primitives

March 10th, 2007

There is many said about generics how bad and complex they are. The existence of the brillant Generics FAQ is used against generics. The point many people miss: Generics are always complicated and there will be always corner cases. Java Generics have at least the thing for it that it is possible to descibe this in a way non CS-PhDs can understand it. If some say they can’t, perhaps they are in the wrong business or belong to these people that stop reading after the third line if the text doesn’t say what they are already convinced of.

Someting really incovenient is the type erasure. In short type erasure prevents you from writing

T copy(T t) { return new T(t)}; // T is not known at runtime, so its ctor is neither

This is not the only example where it gets into your, but the one that I found the most interesting eventually.

For Java 7 lots of things get proposed, and reifiable generics are getting also on the list, some even propose annotations to add this. I had been bitten by type erasure more than once and despite of that I prefer to keep it like it is.

Point is that non-type erasure is not so simple as it seems, for example when passing an heteorogeneous array as vargrs things get messy as the type is not a class anymore but a composition of interfaces. Although I think that we are missing interface composition, passing such structures around at runtime won’t be funny or free.

And perhaps also useless.

What I think we would see is scary introspection code on the type, because this will be possible and simpler in most of the cases (alternative will be creation of a new generic type). The only point valid is the new T. This is something you cannot imitate without reified type. So the question of type erasure is not the point, the point is how to do virtual ctors.

Something missing from generics that is rarely mentioned is the lack of support for native types. Although I see them as the deadly sin of the Java programming language there are there and there are indeed the reason why we deal so much with array (which causes the problem above). As they are there support for them would cut some corners; implementing it is by far trivial thanks to the second C-heritage type coercion amoung the numeric types.

Bob Lee made the remark that the use of array in varargs would be better replaced by List. Nice try - but as List is not part of the language not really an option. Or List becomes part of the language … hello Lisp

Beyond Java [was: The Enhanced For-Loop]

December 8th, 2006

I have to say that I find the enhanced for loop useful as a chocolate teapot. I cannot count how often I refactored an iteration into a for just to redo it afterwards. Some times you want to delete via calling remove on the Iterator, sometimes you need an index, well it quickly gets ugly.

Triggered by http://kawagner.blogspot.com/2006/08/java-enhancements-i-would-like-to-see.html and learning C# I started playing with the idea to wrap Iterable to provide access to an index, remove and filtering (plus paired iteration). Well it became ugly. Java and the generics are bitchy sometimes, have a look at it, maybe you find it useful (I find it insane:-)
enumerator.zip

I don’t think it is finished and I don’t think that I will finish it ever. The reason why I put this is out was just a side-kick in Javaposse #94 where the index issue was raised with the remark that someone might implement it someday - well I already did.

The point why I stopped working on it and I really developped an aversion against this code (now you have to have a look at it) was that I started with Scala; a really nice language that has enough FP to write expressive code, enough OO to fit into today’s development mainstream and integrates into .NET and Java so that existing code can be leveraged. It is statically typed (I had too much hassle with JavaScript that I could ever consider dynamically typed code in larger scale development) that makes it strict enough to have powerful type inference. Of course it has it rough edges and limitations, but it addresses the problems I find hard to tackle with Java reasonably well - there are problems that can be solved more elegantly with Ruby, but I think I still need some more practice with Scala before I give up on them.
PS: I think the index in a loop is not needed in a pure OO-design, but where do you ever find a pure OO design

Some Golden Rules for object-oriented Java

September 3rd, 2006

There are millions of programmers and trillons of lines of code out there that use Java, but as Java is an All-purpose language, most of the code produced is procedural redump of what people did when they used C or Fortran.

I came up with a short-list of sanity checks that I use to benchmark my designs.

  1. No public method shall return null, this applies also to protected methods of non-final classes
  2. Never pass this as an argument
  3. Getters and Setters are evil
  4. A public method shall be declared by an interface (sometimes an abstract class is sufficient and more convenient)
  5. No switch / if-else if on class invariants (this includes instanceof)
  6. A class shall be either (conceptually)final or abstract
  7. No method declares a foreign exception (I am OK with some checked exceptions from the java* packages)
  8. An object that can be passed back to the API shall be immutable or a Builder
  9. Prefer delegation over inheritance (this makes 6. reasonable)
  10. The class skeleton shall fit on a single page, as do all methods (including the private methods that are used by a single method only)
  11. The number of ctors shall be much smaller than the number of instance methods
  12. All statics are in enums

This is no style-guide (most of them are a waste of time with as little impact as knowledge is required to contribute), this is what I distilled out of code that pleases me and that really works and has been proven to be maintainable and easy to integrate.
To be continued / comments and suggestions are welcome.

Actually I know of style-guide that focussed on more than indentation and the placement of whitespace: JSF air vehicle C++ coding standards

Update: I started some explainatory notes on each topic (1-6,10,11 for the moment) under Design Rules

Absence is a feature

August 19th, 2006

Dushan Hanuska posted an interesting claim:

One of the symptoms of object-oriented programming is the lack of switch or case statements

I’d prefer to say (OK, I am not a native english speaker, so perhaps I didn’t get the original intention)

One of the features of object-oriented programming is the absence of switch or case statements

His article shows ploymorphism at work while he is refactoring a simple class. In the end he comes up with 4 classes and one interface, well I am fine with that, but I know my co-workers, they don’t like it.

Nevertheless, the best part is at the end: He nicely lists in order the standard refactoring procedures applied to clean up the code. So read to the end, perhaps it is something you should do also when defining design guidelines: Showing how “old-school”-solution can be transformed using refactorings (thus preserving the functionality) might be more instructive than pages of prose and fuzzy reasoning on how some problem should be solved. This problem is not a concern for the most of us, but when you have to integrate (experienced) developers from a different background it could be a help.

To deprecate or to be deprecated

August 12th, 2006

I am using Java 6 as my only JVM installed. So far everything worked nicely, even in the early days of b42 where I started using Mustang.

I also really like JDBC 4, as it make many things much easier, but recently I had the strange situation that I couldn’t compile the development stream at work any more.

The class that failed was an implementation of RowSet which in turn extends ResultSet. With JDBC 4 ResultSet got a bunch of new methods.

As the class in question was a dummy for SQLServer-support, I tried the standard trick of letting Eclipse add the missing methods. Fine, everthing compiles, but unfortunately it will now fail to compile on older JVMs. Normally making an interface bigger is no problem (well see below for a corner case), but the interface ResultSet now also introduces new types, for example NClob. Outch. This type does not exist in version prior to Java 6.

Wouldn’t it have been a better idea to extend ResultSet instead?

Longer ago I crashed into another class augmentation problem:

void foo(StringBuffer bar) {
return new StringBuffer().append(bar);
}

Prior to Java 5 this called append(Object), which internally performed a toString on the argument and appended the result.

With Java 5 there is the method append(CharSequence) and StringBuffer implements CharSequence. In the presence of Java 5 libraries the code above binds to append(CharSequence) as this is the most specific type, resulting in a class-file that cannot execute in a pre Java 5 environment.

It would be a big help if the java-libs would make more use of the “deprecated” and “since”. “Since” should become an annotation, so that that compilers generating code for other versions can ignore this method/class; similarily “deprecated” needs to be augmented by a language-level attribute that say since then it is (or perhaps will be) deprecated.

This will enable the unuse of deprecated features, as many of this just stays in for backward-compatabilty reasons, which in turn force programmers to use them as the replacements are perhaps not yet implemented.

Of course many of this can be solved by proper code organization, but in reality this is often not feasible for various reasons. Also in the adent of JSR-199 the issues above might become much more pressing.

Is this something for Dolphin(Sun changed the naming scheme, now its JDK7)? The JSRs are yet to written…