blog.smart-java.nl
Ordina J-Technologies – Java Blog

Archief voor April, 2009




Oracle neemt Sun over

Door: Stephan Oudmaijer, 20 April 2009

Oracle en Sun hebben een akkoord bereikt over de overname van Sun door Oracle. Lange tijd leek het erop dat IBM een van de belangrijkste kanshebber was om Sun over te nemen. Echter konden IBM en Sun het niet eens worden over de voorwaarden waaronder de deal door zou gaan en de prijs per aandeel. Oracle betaalt de aandeelhouders van Sun $9.50 per aandeel, hetgeen neerkomt op een deal van $7.4 billion dollar. Dat is  $0.10 per aandeel meer dan IBM bereid was om neer te tellen.

De overname van Sun door Oracle levert wel een aantal interessante vraagstukken op, wat gaat Oracle bijvoorbeeld doen met Java? Op dit moment is er nogal wat onenigheid over het Java Community Proces (JCP), het standardisatie proces voor Java. Velen hopen dat Oracle de JCP nu echt open zal maken. Anderen zeggen dat er geen sprake van een inspraak proces is. Aan de andere kant, misschien is het wel niet in het belang van Oracle om Java nog opener te maken om het zodoende concurrent IBM lastiger te maken?

Verder zijn er nog NetBeans en  GlassFish? Aangezien Oracle BEA heeft overgenomen, bekend van o.a. de applicatie server WebLogic, is er bij Oracle een overschot aan applicatie servers ontstaan. Zelfde geldt voor ontwikkelomgeving NetBeans vs JDeveloper, zullen beide naast elkaar blijven bestaan of worden ze samengevoegd?

Daarnaast is Oracle plotsklaps eigenaar geworden van MySQL, door velen gezien als het open source alternatief voor Oracle. Moeten we ons nu gaan verdiepen in PostgreSQL? ;)

Voor het orginele persbericht zie: http://www.oracle.com/corporate/press/2009_april/018363.htm




Singleton Smells

Door: Jan-Kees van Andel, 19 April 2009

I really hate the Singleton pattern. It makes code hard to test, it has nothing to do with general OO principles and the Singletons I see daily (written by others of course :) ) usually look very procedural.

People who use Singletons in Java all the time have more fundamental problems (I’m not talking about singleton scope in Spring btw), so I’m not gonna rant about that problem here, but I do like to show you an alternative which makes it easier to unit test Singletons.

Neal Ford published a talk on InfoQ called: “10 Ways to Improve Your Code”. Item 4: “Good citizenship” is about static methods and especially the Singleton design pattern. Static methods have their usage, for example simple stateless utilities like: int Math.sqrt(double) or Apache Commons. But when you’re going to add state into the mix, things get messy.

Singleton usage

Let’s step back. Why are we using Singletons in the first place?

  1. First, as the name says, because you want to guarantee that there is only one instance. Typical examples in the Java libraries are java.awt.Toolkit and java.io.Console.
    For those of you interested, Console doesn’t have a static getConsole method, but can be accessed through System.console() and – in the Sun implementation – SharedSecrets.getJavaIOAccess().console(). In these cases, a Singleton is needed because there may NEVER be two instances of these classes. Otherwise strange things will happen, because you never know which instance contains the state you need.
  2. Second, and depending on the circumstances this is a good or a bad thing, Singletons are the Object Oriented equivalent of globals. Almost everybody agrees that (non-immutable) globals are very bad, but for some reason, many developers still use Singletons. But, for certain objects, it’s useful to be able to access them from everywhere, without needing parameters all the time.

And of course, there are plenty of myths regarding Singletons, for example because singletons can be lazily instantiated on first use. Well, guess what? Classes are lazily initialized by the ClassLoader, so unless you’re messing with cyclic initialization dependencies you don’t need any custom lazy loading mechanism.
By the way, lazy initialization is a bad thing that should be avoided if possible. See Joshua Bloch’s Effective Java for more details.

An example Singleton

Below is a snippet with an example Singleton. You probably see Singletons like this all day.

public final class BadSingleton {
    private final String prop1;
    private final String prop2;
 
    private BadSingleton() {
        this.prop1 = System.getProperty("prop1");
        this.prop2 = System.getProperty("prop2");
    }
 
    private static final BadSingleton INSTANCE = new BadSingleton();
 
    public static BadSingleton getInstance() {
        return INSTANCE;
    }
 
    // Other methods
 
}

It’s just a simple Singleton. It uses field initialization for thread safety and simplicity, but is still lazily initialized (by the ClassLoader). Further, initialization is done in the constructor where the environment is queried for some settings.

As you might know, this code is not testable, not even with reflection/setAccessible(true) hacking, since the field is declared static + final. See the following snippet for a misguided attempt to create a unit test:

public class BadSingletonTest {
    @Test
    public void testGetInstance_Fail() throws Exception {
        Constructor<BadSingleton> constructor = BadSingleton.class.getDeclaredConstructor();
        constructor.setAccessible(true);
        BadSingleton obj1 = constructor.newInstance();
        Field field = BadSingleton.class.getDeclaredField("INSTANCE");
        field.setAccessible(true);
        field.set(null, obj1); // Exception because INSTANCE is static + final
        BadSingleton obj1 = BadSingleton.getInstance();
        BadSingleton obj2 = BadSingleton.getInstance();
        Assert.assertSame(obj1, obj2);
    }
}

An alternative for this issue would be lazy initialization, but this has the disadvantages of not being thread safe when not synchronized correctly. Java Concurrency in Practice by Brian Goetz is a must-read when you are interested in thread safety issues.

Alternative using a factory

This is the alternative Singleton class. It’s a modified version of Neal’s example.

public final class GoodSingleton {
    private final String prop1;
    private final String prop2;
 
    private GoodSingleton(String prop1, String prop2) {
        this.prop1 = prop1;
        this.prop2 = prop2;
    }
 
    // Other methods
}

The responsibility of instantiating the Singleton is programmed into the Factory, which is shown below:

public class GoodSingletonFactory {
    private static final GoodSingleton INSTANCE;
    static {
        try {
            String prop1 = System.getProperty("prop1");
            String prop2 = System.getProperty("prop2");
 
            Constructor<GoodSingleton> constructor = GoodSingleton.class.getDeclaredConstructor(String.class, String.class);
            constructor.setAccessible(true);
            INSTANCE = constructor.newInstance(prop1, prop2);
        } catch (Exception e) {
            throw new RuntimeException("error initializing " + GoodSingletonFactory.class.getName(), e);
        }
    }
 
    public static final GoodSingleton getInstance() {
        return INSTANCE;
    }
}

As shown in the snippet, the factory uses reflection to access the private constructor. Note that this trick only works if there is no SecurityManager or if the active SecurityManager approves this action.

It’s also a little bit less “Singleton” since it is possible to have more than one instance. The same reflection trick we used, now works a bit against us. If this is not an issue for you, it doesn’t matter. After all, developers who want to abuse your API always succeed if they really want to.

But we do get the advantage of better testability, as shown in the following two snippets:

public class GoodSingletonTest {
    @Test
    public void testConstructor_Ok() throws Exception {
        Constructor<GoodSingleton> constructor = GoodSingleton.class.getDeclaredConstructor(String.class, String.class);
        constructor.setAccessible(true);
        GoodSingleton obj1 = constructor.newInstance("1", "2");
        // Assert stuff
    }
}
public class GoodSingletonFactoryTest {
    @Test
    public void testGetInstance_Only_one_instance() throws Exception {
        System.setProperty("prop1", "test value");
        System.setProperty("prop2", "test value");
        GoodSingleton instance1 = GoodSingletonFactory.getInstance();
        Assert.assertNotNull(instance1);
        GoodSingleton instance2 = GoodSingletonFactory.getInstance();
        Assert.assertNotNull(instance2);
        Assert.assertSame(instance1, instance2);
    }
}

As you can see, testing now becomes trivial.

Notes

Choosing the factory approach has some effects that may be important to you. Here’s a list of consequences and random thoughts.

  • When using the reflection approach, it is possible for developers to mess up the Singleton behavior using reflection. When they do this, you may end up with multiple instances, which may be undesirable. When using a Singleton and the instance field is declared as static + final, this is not possible. The importance of this point differs per situation.
  • You can choose to make the constructor package private (default) accessible. This way, you don’t need reflection to access it from the same package. If you put the Factory and the unit tests in the same package, this will make the code much more readable, especially for less experienced developers. It’s also less error prone, because the compiler isn’t capable of doing thorough checks on reflective code. On the other hand, if a developer put’s a custom class in the same package, it’s possible to invoke the constructor and thus create multiple instances.
  • There is a myth that reflection is slow. It’s true that reflection is not as fast as JIT optimized (plain Java) bytecode. But since about 2000, there have been massive improvements in reflective invocation performance. And of course, if you look at the snippets, reflection is only used the first time.
  • Using a static initializer block in the Factory and an immutable (all fields final, no lazy initialization) Singleton class makes the entire structure less sensitive to Concurrency hazards. Again, see Brian Goetz’ book for details.

If you ask me, the advantages outweigh the disadvantages by miles, especially when you consider that when developers misbehave (like in the first two bullets) in such a way that they break the Singleton principle, they should (and on my projects will) be ass whooped. :)




Can software developers build usable GUI’s?

Door: Vincent Hartsteen, 17 April 2009

Most developers would answer this question the same way that Bob the Builder would when asked if he can fix it. “Yes I can” would be the reply. And I’m sure that Bob can. Why? Because Bob does his building based on a blueprint that tells him exactly what to build and what to use for building it.

In construction the architect is responsible for producing the blueprint. The architect talks to the customer in order to get a list of requirements for the building. For instance is the building used as an office-space or is it used as a family-home. Should it be a single or multi story building and how many rooms should it have. And of course the amount of money the customer is willing to spend. Geared with the list of requirements the architect uses his design skills and his technical knowledge to make a first sketch of the building. The architect discusses this sketch with his team of electrical, mechanical and structural engineers to find out if it feasible from a technical point-of-view. For instance is the construction mechanically strong enough, are the selected materials useable, etcetera. This should all result in a blueprint for a building that meets the customer’s requirements, is usable with respect to the needs of the customer and is aesthetically pleasing. Finally the constructionworkers take the blueprint and start building the construction.

In software development some similar process takes place. In short the information analist and the customer discuss about the requirements for the system. What functionality should the system offer, what is the expected load etcetera. The information analist works in close cooperation with the software architect. The software architect is responsible for making the technical decisions (which frameworks to use, what platform, how many nodes, etc.) such that the non-functional requirements (scalability, extensibility, manageability, etc.) can be met. The UML-artifacts created by the information analist and the software architect (e.g. use-case model, software architecture document, use-case realizations, etc.) are input for the developers.

One major difference between the blueprint for the construction workers and the UML-artifacts for the developers is that the blueprint has usability embedded. The architect has knowledge about how to make a construction usable to its users. When there is a requirement that a house must have 2 bathrooms the architect knows that to make them usable he could place one on the groundfloor and the other on the first floor. He could have fulfilled the requirement by putting both bathrooms on the attic but that would not have made them very useable. Very often a developers gets a requirement which basically comes down to: “the application must have a web-interface or a GUI and it should be user-friendly”. That’s it. So now it is up to the developers to figure out what “user-friendly” is.

Most developers have a technical mindset and find it hard to step into the role of the end-user. It is the end-user that decides if the application is user-friendly. He does so when the application supports the end-user to do his job without problems. So in order to design a user-friendly interface it must be clear what the application is used for and how it is used. Very often user-friendlyness is misconceived as “protect the end-user from making mistakes”. If end-users use the application every now and then to do some work it can be valid to pop-up a confirmation dialog. Expert users that use the application on a regular basis get annoyed by such dialogs.

There are currently lots of tools/frameworks that allow developers to build goodlooking user-interfaces: JavaFX, Flex, SAF, JSF, Wicket, and the list goes on. But goodlooking is not the same as user-friendly. With the tooling mentioned before we could build a very nice 3D, animated, gradient color dialog box that is very annoying (remember the Office paperclip?). So basically we have the tools to create cool and goodlooking user-interfaces but most of us lack the knowledge of how to build usable ones.

My point is that there should be a role in the softwaredevelopment team, just like a information analist or a software architect, that is responsible for designing the interaction with the end-user. Just like the architect in construction. I haven’t come across a person with such a role in the many projects I’ve worked on over the past years. Until that time it is up to us developers to design user-interfaces and for that we need to broaden our horizon and try to place ourselves on the end-user seat.

A few years ago I read “About Face. The Essentials of User Interface Design” (first edition) written by Alan Cooper which got me interested on this subject (3rd edition is the most recent version). The book describes the problems that occur when developers start designing user-interfaces and give advice on how to improve on that, all illustrated with entertaining examples. If you get into the situation where you as a developer are responsible for the design of the user-interface this book might help you do a better job.

Vincent Hartsteen

N.B.: Currently I’m reading “The Inmates are running the Asylum”, also by Alan Cooper. This book describes the role of “interaction designers”. I’ll write my findings when I’ve finished the book.




Cyclische dependencies @ runtime

Door: Frank Verbruggen, 16 April 2009

In een gelaagd project zijn er meestal aparte lagen gedefinieerd voor services, domein logica en data access. Stel nu dat er een noodzaak is om vanuit een lager gelegen laag gebruik te maken van functionaliteit die thuis hoort in een hoger gelegen laag. Bijvoorbeeld omdat er in de domein objecten een noodzaak is om gebruik te maken van een service. Hoe zorg je er dan voor dat je nette object georienteerde code houdt, zonder dat je compile time dependencies krijgt tussen je projecten / lagen? Het hier gepresenteerde design pattern is een elegante object georienteerde oplossing voor het bovenstaande probleem.

Gegeven een DomeinObject als object uit de lagere laag, en een ServiceImplementation als object uit de hogere laag. De serviceImplementation heeft een een interface methode ’someMethod()’ uit de ServiceInterface die benodigd is om de methode ‘businessMethod()’ uit het DomeinObject te implementeren (zie figuur 1, originele klasse diagram).

N.B. Het design pattern is uitgewerkt met domein objecten en service implementaties, maar dat is slechts een invulling.

—————————————————————-

—————————————————————-
Figuur 1, originele klasse diagram
—————————————————————-

Los dit als volgt op. Trek de ServiceInterface uit de hogere laag, en zet deze in de lagere laag. Maak een RequiredInterfaceFactory die een instantie van de ServiceInterface kan bevatten. Initialiseer bij het opstarten van je applicatie vanuit de bovenste laag de RequiredInterfaceFactory met de ServiceImplementation (dit kan bijvoorbeeld goed met de Spring configuratie uit Listing 1, Spring configuratie). En implementeer de businessMethod door de aanroep naar de ServiceImplementation als volgt te abstraheren:

RequiredInterfaceFactory.getInstance().getServiceInterface().someMethod();

Het klasse diagram ziet er dan uit zoals weergegeven in Figuur 2, klasse diagram.

—————————————————————-

 

—————————————————————-
Listing 1, Spring configuratie
—————————————————————-

—————————————————————-

—————————————————————-
Figuur 2, klasse diagram
—————————————————————-

Voordelen en nadelen

Het gebruik van dit design pattern biedt de volgende voordelen:

  • Compile time dependencies zijn niet nodig
  • At runtime kunnen interface methoden van bovenliggende klassen toch gebruikt worden
  • Ieder object kan gebruik maken van de interface, ongeacht in welk package het zit, dus het ophalen van de interface kan in de code altijd op dezelfde manier gebeuren

Het gebruik van dit design pattern biedt de volgende nadelen:

  • Je moet de RequiredInterfaceFactory injecteren met de ServiceImplementation voordat de rest van de applicatie aangesproken wordt



Boekbespreking: Programming in Scala

Door: Hedzer Westra, 12 April 2009

Programming in Scala

Auteurs: Odersky, Spoon & Venners, publicatiejaar: 2008 (1e druk november, 2e druk binnenkort), uitgever: Artima, pagina’s: 736, ISBN-13: 978-0-9815316-0-1, website: http://www.artima.com/shop/programming_in_scala, prijzen: Jolt Productivity Award 2009 for Technical Books.

Belofte maakt schuld: het is tijd voor mijn eerder aangekondigde boekbespreking van “Programming in Scala”.

Ik vond het een prettig & helder boek. In 33 goed leesbare en goed geordende hoofdstukken worden (bijna) alle onderdelen van de taal en de bijbehorende bibliotheek beschreven.

De hoofdstukken zijn goed gebalanceerd – niet te lang en niet te kort, niet te simpel en niet te ingewikkeld. “Programming in Scala” is helder van structuur, bevat een uitgebreide woordenlijst en slechts een korte bibliografie.

De auteurs hebben het niet gedaan, maar je kunt wat mij betreft de hoofdstukken ruwweg in 6 delen onderverdelen: inleiding, basis, standaardelementen, gevorderd, extra’s en frameworks.

De tekst bevat veel vooruitverwijzingen en voetnoten. Het onderwerp van veel hoofdstukken wordt een aantal hoofdstukken later weer opgepakt, zodat dat onderwerp even wat tijd heeft gehad om te bezinken. De ‘fast tracks’ maken het mogelijk om lastiger of verdiepende stukken over te slaan.

Naast uitleg over wat Scala is, wordt ook veel duidelijk gemaakt over wat je er mee kunt doen; het verschil in programmeerstijl tussen Imperatief Programmeren (IP) en Functioneel Programmeren (FP) wordt diverse keren behandeld – er is veel voorbeeldcode die laat zien hoe je recursief, en in ’t algemeen in FP-stijl, kunt programmeren. Ook conventies die in de community ontwikkeld zijn, komen aan bod.

Het boek is tevens beschikbaar als eBook – ik had vanaf afgelopen september een preprint tot mijn beschikking. Ik was verbaasd over de leesbaarheid ervan – zelfs op een gewone laptop; niets eens op een speciale eBook reader. Ook is alle voorbeeldcode te downloaden.

Er wordt vrij weinig gerefereerd naar andere talen dan Java. Sowieso vind ik het boek goed leesbaar voor Javanen, maar of dit ook geldt als je kennis meer ligt bij andere talen, vraag ik me af.

Als tipje van de sluier wat betreft de inhoud volgt hier een (korte?) opsomming van de taalaspecten die behandeld worden: traits, closures, case classes, type parameters inclusief variance & erasure, implicits, pattern matching & extractors, for expressions, operator overloading, interne & externe DSL’s, lazy evaluation, currying, 1ste-klasse & hogere-orde functies, typehiërarchie en bibliotheken (onder anderen collecties, XML, Actors, parser combinator, Swing, testen).

Hoofdstuk 28 vond ik een vreemde: hierin wordt namelijk stap voor stap uitgelegd hoe je netjes equals() & hashCode() kunt implementeren. Inderdaad belangrijk, maar helemaal niet Scala-specifiek. Er wordt dan ook veelvuldig wordt gerefereerd naar Joshua Bloch’s “Effective Java.”

Het hoofdstuk over integratie tussen Scala & Java viel me wat tegen – het is erg kort. Nu is het wel zo dat Scala & Java naadloos integreren, en er dus niet al te veel aandacht aan besteed hoeft te worden, maar iets meer had geen kwaad gekund.

Het afsluitende voorbeeld vond ik wel erg interessant. In minder dan 200 regels code worden erg veel taalaspecten gebruikt, en de volgende technieken worden gecombineerd tot een spreadsheetapplicatie: Interne & externe DSL (Swing & formules), termevaluatie en separation of concerns – MVC en Pub/Sub (op 2 niveaus).

“Programming in Scala” is niet bedoeld als referentie of handleiding; dit is duidelijk een leerboek, onder anderen vanwege de grotere & kleinere codevoorbeelden, die de tekst extra verhelderen. Mijn aanbeveling is om ‘t van voor tot achter te lezen, en niet hapsnap, anders zul je details missen. Al met al biedt het boek op een toegankelijke manier een complete behandeling van de taalaspecten van Scala, en kun je – tijdens het lezen al – zelf aan de gang met deze erg interessante taal.

Kleurindicatie: Groen (3 op schaal van 3)

Nu ik toch jullie aandacht heb wat betreft Scala: op dinsdag 9 juni geef ik een TechSessie over Scala. Primair bedoeld voor J-Tech’ers, maar natuurlijk zijn alle Ordina-medewerkers welkom. Binnenkort kun je een uitnodiging in de mail verwachten!

Hedzer Westra

Hedzer Westra