Archive

Posts Tagged ‘Java’

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: ,

Google collections and enhanced JavaBeans

November 4th, 2009 7 comments

I’m a big fan of Google Collections. Functions and Predicates became my best friends to make Java’s syntax a bit functional-like. I like writing things like:

List<Contact> contacts = ...
List<String> toStrings = Lists.transform(contacts, Functions.toStringFunction());

and with the help of static imports:

List<String> toStrings = transform(contacts, toStringFunction());

If you use out-of-the-box Functions and Predicates, it’s a lot of fun. Now, let’s say, you want something more useful like:

List<String> names = transform(contacts, Contact.T0_NAME);

you need to accommodate with Java’s way of writing functions. That is write an inner class:

public class Contact {
...
public static Function<Contact, String> TO_NAME = new Function<Contact, String> {
    public String apply(Contact contact) {
        return contact.getName();
    }
}

It’s ok for one bean property, but writing functions for all of them is a lot of work.

What if we could write a JavaBean that would generate all these functions for us. Something like that:

public class Contact extends AbstractBean<Contact> {
public static final StringProperty<Contact> NAME = stringValue();
public static final IntegerProperty<Contact> AGE = integerValue();
public static final StringProperty<Contact> EMAIL = stringValue();

public Contact(String name, int age, String email) {
    super(NAME, name, AGE, age, EMAIL, email);
}

public String getName() {
    return get(NAME);
}

public Integer getAge() {
    return get(AGE);
}

public String getEmail() {
    return get(EMAIL);
}
}

Now, every property of my bean is also a Function converting a bean instance to it’s property value. To be clear:

Contact.NAME is a Function<Contact, String>
Contact.AGE is a Function<Contact, Integer>
Contact.EMAIL is a Function<Contact, String>

so that I can write:

List<Contact> contacts = ...
List<String> names = transform(contacts, Contact.NAME);
List<Integer> ages = transform(contacts, Contact.AGE);

Nice isn’t it?

Now, it can be even cooler. I can write something like that:

Iterable<Contact> david = filter(contacts, NAME.isEqualTo("david"));
... adults = filter(contacts, AGE.isGreaterThan(18));
... babies = filter(contacts, NAME.isEqualTo("baby").and(AGE.isLessThan(1)));

My bean properties are also Predicate factories!

With a custom utility class, I can even use a clearer syntax that Google Collection’s:

... ages = with(contacts).keep(NAME.isEqualTo("david")).to(AGE).list();

There are even more features. All AbstractBeans come with free equals(), hashCode() and compare().

The last neat feature is the ability to write a builder for any bean easily, with only one additional method:

public class Contact extends AbstractBean<Contact> {
...
static <V> BeanBuilder<Contact> with(BeanProperty<Contact, V> property, V value) {
    return new BeanBuilder<Contact>() {
        public Contact createBean(PropertyValues<Contact> values) {
            return new Contact(values.get(Contact.NAME), values.get(Contact.AGE));
        }
    }.with(property, value);
}

Now, I can write something like this:

Contact contact = with(NAME, "david").with(AGE, 34).with(EMAIL, "d@g.net").build();

Note, that all of the features are statically typed and don’t use reflection.

What do you think?