12 Feb 2008

A better way to use Java Enum than switch

I think java enum are a nice addition to the language. I used to combine them with switch/case statements. But lately François, a colleague, shown we a better way :)

You can embedded behavior in each enumeration case, reducing client code and making it more elegant :)

Let's take a simple example: Every day of the week you need to do something: take out the garbage, go to the laundry etc. ...

Using switch here's how I would have done it:
    private enum Week {Sunday, Monday, Tuesday, Wednesday, Thursday, Friday, Saturday}

public static void main(String[] args) {
final Week today = getToday();
Action action;
switch (today) {
case Sunday:
action = new FamillyDiner();
break;
case Monday:
case Friday:
action = new Garbage();
break;
case Tuesday:
action = new Laundry();
break;
case Wednesday:
action = new ChillOut();
break;
case Thursday:
action = new Grocery();
break;
case Saturday:
action = new SoccerGame();
break;
default:
throw new RuntimeException("Impossible day!");
}
action.execute();
}

Conclusion:
  • You can see the number of lines in main() is quite important
  • The client code (the switch/case code) is likely to be duplicate
  • There is an unnecessary case "default" that can never happen (even null case would result in a NullPointerException in the switch)
  • But it still much better than a if/elseif/else using int

Adding behavior to the enum:
    private enum Week {
Sunday {
@Override
public void execute() {
System.out.println("Mom and Dad diner.");
}
}, Monday {
@Override
public void execute() {
System.out.println("Take the garbage out.");
}
}, Tuesday {
@Override
public void execute() {
System.out.println("Do the laundry.");
}
}, Wednesday {
@Override
public void execute() {
System.out.println("Have a beer. Just Chill out!");
}
}, Thursday {
@Override
public void execute() {
System.out.println("Go out to the local store for Grocery with shoping list.");
}
}, Friday {
@Override
public void execute() {
System.out.println("Take the garbage out.");
}
}, Saturday {
@Override
public void execute() {
System.out.println("Manchester vs Arsenal! Can't miss that!");
}
};

public abstract void execute();
}

public static void main(String[] args) {
final Week today = getToday();
today.execute();
}

Conclusion:
  • Less lines of code and still readable
  • main() code is soooo easy
  • No unnecessary case "default"
  • If you don't want this behavior and still use the enum you are free to use the switch/case way


Clearly I think this approach is far better and much more elegant unless someone show me otherwise...



Download the complete code sample.

7 Feb 2008

Comparison: java.util.logging vs org.apache.commons.logging

Here's a comparison between the java logging system and apache commons logging system.

For the lazy ones here's the conclusion:
  • Commons Logging Rocks!
  • Java Logging Sucks!

Why ? Well because:
  • Commons Logging api is better
  • Commons Logging let you choose your logging implementation
  • Commons Logging is bulletproof, production ready, heavily use everywhere
  • Everybody knows Commons Logging

Not convince yet ? Good I like people that don't take things for granted easily ;)

Let's compare the 2 frameworks api:
Java LoggingCommons Logging
Unclear log level: SEVERE > WARNING > INFO > CONFIG (wtf?) > FINE > FINER > FINEST (missing some imagination here ?!)Clear log level using different names: FATAL > ERROR > WARN > INFO > DEBUG > TRACE
No ERROR level! I find it really disturbing especialy since there is a System.err stream for so many yearsThere is an ERROR level
To log an exception:
logger.log(Level.SEVERE, e.getMessage(), e);
or may be
logger.log(Level.WARNING, e.getMessage(), e);.
Unclear what Level to use and why do I need to do e.getMessage() it could have been done in the log() method.
Missing simple methods: logger.warning(Throwable t) and logger.severe(Throwable t)
To log an exception: logger.error(e);
To configure either modify the logging.properties in your JRE/lib folder or set -Djava.util.logging.config.file=/my/folder/logging.properties
No way to put a conf in the classpath to be automaticaly pick up by the logging framework
Possibility to put an already configured conf file
Create a logger:
private static Logger logger = Logger.getLogger(MyCLass.class.getName());
Missing method: Logger.getLogger(class)
Create a logger:
private Logger logger = Logger.getLogger(getClass());


The good things about Java Logging:
  • Classloader: About the configuration part the way java logging does the configuration is less flexible but might reduce classloader problems that you encounter with commons logging (see: Commons_Logging_FUD)

  • No jars to add, No additional dependency


Working with Commons Logging api is some much better, simple and easier that I will continue to put those 2 jars in the classpath whenever possible if that's what it takes to use it.

Now try both and make your own opinion ;)

30 Jan 2008

Firefox - Free your memory

Firefox consume lots of memory.

You can free it by using this little program call "Freefox" [fr] (direct download link).

I went form 300 Mo to 20Mo :o

It's windows only.

Is there such a thing for eclipse? :p



from sebzen

8 Jan 2008

Jakarta Slide is Retired

Just discovered that Jakarta Slide the Java WebDAV open source server is now officially a dead project.

From the website:
As of 2007-11-03, the Slide project is retired. This site is kept online for archiving purposes.

Due to the lack of a developer community, the codebase was no longer actively maintained and security issues could not be addressed by bugfix releases. The Jakarta PMC therefore had no other choice but to retire Slide.

If you are looking for a WebDAV client or a server-side Content Repository, please consider the Apache Jackrabbit project as an alternative.

This site is kept online for archiving purposes.
Not really surprising since last time I checked the project already seemed in a zombie state. But now it is clear...

4 Jan 2008

Don't Make Me Think: A Common Sense Approach to Web Usability

I'm currently reading "Don't Make Me Think: A Common Sense Approach to Web Usability" excellent book btw.

This little comic strip about "Religious debates" is so funny and so true that I couldn't wait to share it with you :D

You can replace "pulldowns" by whatever term: emacs, vim, java, .net, ruby, python, css, pdf etc...




Technorati tags:

14 Dec 2007

Close Encounters of the Third Kind (Silverlight)

I have been hearing and blogging about Sylverlight for many months now
But it's actually the first time that I encounter a sylverlight application while trying to: download the .NET Framework.

Microsoft doesn't force you to use it (there is an alternate web1.0 interface) but I thought I'd give it a try :)

First impressions:
  • I had to download sylverlight (1Mo, small = cool)
  • Restart firefox :( (bad especially when you have dozen of web pages open...)
  • Quit slow to start up (reminds me of applets)
  • The interface (controls, buttons...) is neat, it looks cool
  • The application I tested has too many gadgets for my taste (everything can fold/unfold) could have been more simple (but that's not a technology problem, it's an UI improvement)
  • Things that looks like buttons don't response or do anything ?! (that's really bad) that actually made me quit the application/web page

Well it didn't convince me.
Nice buttons, control, interface... but not user friendly and technical problems.
I know that's 2 different things but for users it's the same.
It reminds me of applets: nice idea but in practice it's not working well (I would have expect microsoft to know how there own technology work)...

update: After re-entering the sylverlight application/webpage; buttons are working, but the interface is really really not user friendly. It seems to me they wanted to use all those nice new features without thinking of the user :(
Also I tried to send them a mail or comment with this post link to help them improve but I gave up when I landed on this horrible support page.

Technorati tags:

15 Nov 2007

Fin du Buzz pour Facebook [fr]

Excellent article de Fred Cavazza analysant la situation de Facebook: "Pourquoi je ne crois plus en Facebook"

Il liste et analyse tous les points faibles de Facebook. Je suis d'accord avec sa conclusion, je pense que Facebook ne revolutionnera rien du tout en fin de compte mais existera avec une communauté correct d'utilisateurs.

Deux choses m'ont fait réagir en lisant cet article:
  • Les statistiques sur les sites les plus utilisés par les gens: les vrai, pas les geeks ;)
- 55 millions d’utilisateurs. OK, mais ça reste à peine plus d’1/4 de MySpace et d’1/3 de Neopets
- Près de 650.000 utilisateurs en France. Certes, mais ça fait à peine 5% par rapport à la communauté Skyblog ou à celle de Windows Live
  • A quel point je (et les personnes qui m'entourent) sommes complétement en dehors des réalités! (je le savais déjà mais disons que c'est une piqûre de rappel)
Depuis au moins 1 an je n'entend parler (sur les blogs, au café, par Instant Messaging...) que de Twitter, Facebook et autres application web 2.0.
On se moque régulièrement des sites MySpace, des Skyblog parce qu'on les trouve "kitch" et pourtant c'est ça que les gens utilisent !!

Il faut se rendre à l'évidence que je fais partit d'une caste repliée sur elle-même... un informaticien avec un blog (depuis longtemps), qui n'écoute pas M.Pokora ou Zazie et qui utilise internet pour le plaisir de l'utiliser (pas pour faire des choses).

Seulement lorsqu'on se retrouve devant des choix pour décider de la présentation d'une page web de son IHM, systématiquement j'entend dire:
"Si j'étais l'utilisateur je ferais ça..."

Seulement comment voulez vous, vous mettre à sa place, on est tellement différent!

Pour moi la seul vrai solution pour savoir si un site est bien pensé ou non, c'est de faire des tests d'utilisabilités.

Malheureusement je n'ai jamais eu l'occasion d'en voir en action en France, il semblerai que personne ne sache que ca exist ou que les informaticiens dans leurs chateaux de verre se disent qu'on ne peut pas laisser de tels choix à "des gens qui n'y connaissent rien" :(

Technorati tags:

7 Nov 2007

Mootools nice package manager

I just discovered the mootools download manager (mootools is an ajax javascript library).

Just click on the extensions you want and it will build you a single js file with them.

I like the skin, colors etc... I think they are neat :)

But the most interesting part it that if you want A it will automatically select the extensions it depends on for example B and C :)

Try to select: Element.Selectors or Fx.Transitions

But when unselecting A it doesn't unselect B and C...
Unless this is a core package that more specific package need in order to work.

Try to select all and then unselect: Element

But that doesn't bother me I prefer something simple and working well than something trying to be too smart ;)

18 Oct 2007

How to detect broken, dead rss feeds in google reader

A simple trick, I wanted to share in google reader.

Go to the Trends page:


Select the "Inactive" tab in "Subscription trends":


There you have it the list of somehow inactive feeds.

The top 3 reasons why those feeds may be inactive are:
  • the blog doesn't exist anymore (404)
  • the blog changed it's engine and the feed url is not the same (for ex: the blog moved from jroller to wordpress, it is hosted somewhere else...)
  • there hasn't been any post for a really long time
Advise for the blogger reading this:
  • Try to avoid at all cost changing the feed url
  • When it's not possible write a last post saying the url is changing before changing it otherwise nobody will notice it and therefor you are loosing all your readers