Archive

Archive for the ‘Blog’ Category

Is ‘final’ keyword always safe to add/remove?

January 14th, 2011 8 comments

If somebody asked me this question “Is it always safe to put/remote ‘final’ keyword on a read only local variable?”, honestly I would have answered “Yes”.

Until I read JavaPuzzlers by Joshua Bloch and Neal Gafter and realized what a little variant of puzzle #8 would look like:

What’s the output of this code?

public static void main(String[] args)
{
    int z1 = 0;
    final int z2 = 0;

    System.out.println(false ? z1 : 'X');
    System.out.println(false ? z2 : 'X');
}
Tags: ,

Soirée spéciale Tests Avancés au Paris JUG

December 23rd, 2010 Comments off

J’aurais l’honneur d’animer le prochain Paris JUG, le 11 janvier.

Triple honneur puisque qu’il s’agit non seulement du premier JUG de l’année 2011, de mon deuxième JUG en tant que présentateur et enfin d’une soirée exceptionnelle animée par moi seul. J’ai une grosse, grosse pression !

Voici le programme, que j’espère vous apprécierez:

Comment j’ai mis ma suite de tests au régime en 5 minutes par jour

Ecrire des tests, toujours plus de tests, une étape nécessaire à tout logiciel de qualité. Seulement, plus il y a de tests, plus le build est long. Plus le build est long, plus il faut de temps pour corriger un bug, plus il faut de temps pour déployer des nouvelles fonctionnalités.

Pour être efficace, un build complet devrait durer moins de cinq minutes. C’est le cas de votre build. Non ? Si tel n’est pas le cas, comment réduire la durée des tests ? Par où commencer ?

Plusieurs stratégies sont efficaces: rendre certains tests inutiles, convertir des tests fonctionnels en tests unitaires, exécuter les tests en parallèle, mettre en commun les lourdes initialisations… De nombreux outils peuvent vous aider en chemin. Partageons des dizaines de conseils pour accélérer vos tests de façon TRES significative.

Attention ! Cette présentations est destinée aussi bien aux fainéants et aux tricheurs, qu’aux courageux. Trois approches à explorer seules ou à combiner.

Techniques de test avancées

A part @Test, quelles fonctionnalités de JUnit4 utilisez-vous ? Les @Rules, les @Datapoints, les @BeforeClass, les @Theories, ça vous parle ?

Et pour rendre les tests plus lisibles, vous préférez les commentaires ou Fest Assert ?
Et pour rendre les test plus rapides, vous savez mocker une seule méthode d’un bean Spring dans les tests fonctionnels avec Mockito ?

Bref, du test, du lourd.

Bonne soirée.

Tags: , ,

Classloader dead-lock hell

December 10th, 2010 Comments off

My previous post presents a typical classloading dead-lock. Java classloaders are lazy by nature and when two different threads need to load two classes with a cyclic dependency (A references B, B references A), there is a good chance that the two threads end up being blocked one by the other.

Here is the simplest code I found to show the problem:

public class Main {
    static class A {
        static B B = new B();
    }

    static class B extends A {
        void hello() {
            System.out.println("Hello");
        }
    }

    public static void main(String[] args) throws InterruptedException {
        Thread thread = new Thread() {
            @Override
            public void run() {
                A.B.hello();
            }
        };
        thread.start();
        new B().hello();
        thread.join();
    }
}

You should be able to reproduce the problem. But sometimes, if one thread is for any reason slower than the other one, it will work ok.

I wonder if tools like Sonar, FindBugs or PMD can spot this kind of problem with static code analysis. It seems very easy to do. Any feedback on these tools?

Wednesday night puzzle

December 8th, 2010 2 comments

What’s the result of running this piece of code?

a) Done.
b) InterruptedException is thrown
c) It depends
d) Code doesn’t compile

import java.util.Vector;

public class Main {
  interface A {
  }

  static class AImpl implements A {
    static AImpl DUMMY = new BImpl();
  }

  interface B extends A {
  }

  static class BImpl extends AImpl implements B {
  }

  public static void main(String[] args) throws InterruptedException {
    final Vector<Object> values = new Vector<Object>();

    Thread thread = new Thread() {
      @Override
      public void run() {
        values.add(AImpl.DUMMY);
      }
    };
    thread.start();
    values.add(new BImpl());
    thread.join();

    System.out.println("Done.");
  }
}
Tags: ,

False warnings in IDEA Intellij, what a pain!

December 7th, 2010 3 comments

I’m a big fan of Eclipse, I’ve been using Visual Age and the very first version of Eclipse. It’s far from perfect but I’ve come to know its weaknesses and became quite efficient.

Every once in a while I take some time to evaluate Intellij IDEA, because, you know, its SOOOOO much better than Eclipse. Not using it only proves you are both stupid and tasteless. That’s what one can hear. I’d love to love this tool but each time I start using it, it looks like he doesn’t like me.

Here is the latest bug I’ve spotted while playing with the otherwise nice code inspection feature.

Let’s say you’ve got this piece of code:

class BugInteger {
    Integer sum(Integer numberOfLongTrades, Integer numberOfShortTrades) {
        return null == numberOfLongTrades ? numberOfShortTrades :
               null == numberOfShortTrades ? numberOfLongTrades :
               (Integer) (numberOfLongTrades + numberOfShortTrades);
    }

    public static void main(String args[]) {
        System.out.println(new BugInteger().sum(1, 2));         // prints 3
        System.out.println(new BugInteger().sum(null, 2));      // prints 2
        System.out.println(new BugInteger().sum(1, null));      // prints 1
        System.out.println(new BugInteger().sum(null, null));   // prints null
    }
}

IDEA warn me on this code, saying the (Integer) cast is redundant. Looks like it is indeed, so I click on the light bulb to remove the faulty cast. Guess what, my unit tests fails with a NullPointerException.

Looks like the cast was not so redundant! In fact it’s here to protect me from unboxing a null Integer.

This is the typical false warning you’ll get often with IDEA. The kind that makes you disable all the inspections because they are so unreliable. A warning should be an advice you can follow or not, but it should NEVER break the code.

If you think this an isolated bug, then let’s say I’ve seen dozens isolated bugs each time I test IDEA. For now, I’ll keep on testing seriously and will try to post some more positive/negative insights.

Tags: