How JDepend Changed My Java Packaging

One important feature of Java language is the package keyword. It helps a lot in modularizing your code. But how exactly one should use it is not that clear.

I have been on projects where 100s of classes are in a same package and more often where you have packages for every 2 classes. Often, packages are chosen so as to split functionalities. But often as well, people are packages maniacs and create way too many of them, because they want to sort things out, not necessarily applying a consistent logic. For example, I am sure many of you have seen the “blahblah.exceptions” packages where you dump exceptions classes.

Without any precise intention for packages, you encounter quickly cyclic dependencies in your project, and your build system becomes overly complicated. Then you try to remove cyclic dependencies, not by using the package keyword better, but by building jars differently (=ugly jars) and “refactoring” a bit.

I fell myself in many of those traps. Fortunately I stumbled on my way on JDepend package analysis program. At first I wondered why JDepend calculated dependencies between Java packages and not between Jars, as in your project what matters is jar interdependencies. After using it regularly, first for the fun of trying not to have cyclic dependencies in my Java packages - the green light effect (I wanted my green light on my project), I understood much better its interest. I now make Java packages that are much more meaningful. They not only separate functionalities, but also create excellent modularity. Building a project is very easy, reusing parts of it is very clear. If one needs to split a jar in a project, it’s very clear how to split it (by Java packages). And I find that in the end my packages make much more sense.

Placing a class in the right package is most of the time not difficult, especially for experienced programmers. But now and then, with JDepend, I find mistakes. Correcting those mistakes regularly, when it’s just about one or two classes is quick and easy. Correcting them on a project where dependency analysis was never done is a nightmare.

Now I don’t really care about JDepend metrics about abstractness and instability so much, I did not find any good use of them. But JDepend (or a package dependencies checker) really is an essential program for good Java development.

You Know IOException? Think Again!

I was amazed today to find out that there was no constructor IOException(String, Throwable) or IOException(Throwable) in JDK1.4 and JDK1.5. It is finally in JDK1.6, I can’t believe it took Sun that much time to change that.

So the workaround is:

`IOException ioe = new IOException("message");`
`ioe.initCause(e);`
`throw ioe;`

It can also be written as:

`throw (IOException) new IOException("message").initCause(e);`

It is not a major problem, but still. We can all thank the guy who reported that as a bug to Sun in 2004.

Good Software Books - 2006 version

Here is an update of the most interesting software books I found interesting. I already made such a list in 2005:

  • Object Oriented Software Construction, 2nd Ed, by Bertrand Meyer. This made me understand why OOP is important, what is important in OOP and why it is still relevant. It contains lots of important guidelines you can apply to better design programs. One famous quote is "Real systems have no top". Code Complete (Microsoft Press) covers some of the same ideas as Meyer's book, and some more pragmatic issues that arise in software projects ("measure twice, cut once"). I also liked the chapter on "table driven design".
  • Concurrent Programming in Java, Second Edition, by Doug Lea: there is all you need to know about programming in a multithreaded environment in it. The chapter on synchronization should be a must read for every Java developer.
  • Design Patterns by the GoF: simply the best presentation of most common design patterns. I have a glance on it once in a while.
  • Artificial Intelligence through Prolog, by Neil C. Rowe (Prentice-Hall): if you don't remember much about Prolog, it's a good book. It details how Prolog interpreters work.
  • File Systems Forensic Analysis, by Brian Carrier (Addison Wesley): everything you need to know about disks and file systems, every trick to recover lost data. To go more in depth into file systems theory, you can read the free Practical File System Design with the Be File System from D. Giampaolo, the creator of BeFS.
  • Mind Hacks (O'Reilly): you probably already bought that one. Not about software, but excellent.
  • Practical Issues in Database Management by Fabian Pascal (Addison Wesley): short but concise book on relational database theory. F Pascal is of CJ Date school of thoughts, "null are evil". You don't need to read it if you have read any other similar book (by CJ Date for example).
  • Inside The Java Virtual Machine, by Bill Venners (McGraw-Hill): there are other books on the same subject. While this book has some bad reviews, I found it an easy read, and it explain well enough for me all the inner details of Java. I found "Programming for the Java Virtual Machine" not better, and with some bad example of a Prolog language for the JVM (1 full chapter for this to present a way too simple thing to be of any use).
  • Programming Jabber, by O'Reilly: I have read it 2 years ago, I enjoyed how they made you go through building a Jabber server.
  • Lucene In Action: the only book about Lucene, some of the info is useful to understand how it is designed.
  • Hibernate In Action: if you have to use hibernate, this is the book to read. It presents different ways of using it.
  • some Javascript+DHTML(+CSS) book: useful if you have none. They often have good tricks to solve the usual problems. In the AJAX days, it becomes useful again. I find O'Reilly's "Javascript - The Definitive Guide" good to have an API reference (as ebook), and "Javascript and DHTML Cookbook" has the most useful recipes.
  • Lean Software Development by Poppendieck (Addison Wesley): easy to read, good presentation of software dev management problems and pragmatic solutions. My favorite on the subject. Another good one but very specific is "Requirements Management" (MS Press).
  • UML Distilled by M Fowler: always useful to have if you need to draw UML diagrams.

I Get Spring

When you google up Java Spring, one of the best results is a post from crazybob called “I Don’t Get Spring”. For a long time, I shared a similar opinion. But now that I have used it, I get it. I only use it for defining replaceable services, so when I talk about Spring, I mean spring-core and spring-beans.

These two packages are not big, and have only very few dependencies. So it is quite easy to use Spring in any project, be it small or not. It is actually easier than using NanoContainer because Spring has less external dependencies.

I did not talk about Dependency Injection yet, because that was not my primary goal. Many times I had to write by hand configurable factories. By using Spring, I avoid writing all that boilerplate code. I was surprised that with 1 line of code I actually had my factory done. Granted, the config file is xml, an I am not necessarily an xml fan. But 1) it’s very simple, and 2) if you don’t want your custom factory to depend on all implementations, you will either use strings in your code or a config file, which in the end is no better than Spring config file.

Dependency Injection is the big plus that Springs gives on top of it. It’s very useful to define your dependencies explicitly in the config file, since all beans instantiated from the config file are instantiated dynamically. And by defining the dependencies, you also get for free the injection.

Spring is not big and strange and unknown. It solves a fairly simple problem. But again I don’t use it for everything, every class. I don’t think it brings much versus straight Java code when you don’t want replaceable services. And putting it in places where it is not needed would be dangerous, because of the unneeded xml configuration.

Java Serialization vs .NET Serialization - Java Perverse?

Did you know what happens in Java when you serialize a subclass of a non serializable class? I was surprised by the answer: it works!

Unfortunately it is not a good thing, because it will serialize fields from your subclass and no fields from the parent class. So you'll end up with a half serialized instance.

In .NET, it breaks at runtime, throwing an exception, which is I think, much more logical, because then you don't end up with half data somewhere.

  • Java Code:
import java.io.ByteArrayInputStream;
import java.io.ByteArrayOutputStream;
import java.io.ObjectInputStream;
import java.io.ObjectOutputStream;
import java.io.Serializable;



public class Test
{
  public static class Toto 
  {
    public String me;    
  }
  
  public static class Toto2 extends Toto implements Serializable
  {
    public String you;
    public String toString()
    {
      return me+" "+you;
    }
  }
  
  public static void main(String[] argsthrows Exception
  {
    Toto2 t = new Toto2();
    t.me = "it's me";
    t.you = "it's you";
    System.out.println("t="+t);
    ByteArrayOutputStream b = new ByteArrayOutputStream();
    ObjectOutputStream oos = new ObjectOutputStream(b);
    oos.writeObject(t);
    ObjectInputStream ois = new ObjectInputStream(new ByteArrayInputStream(b.toByteArray()));
    System.out.println("u="+ois.readObject());
  }
}

will output:
t=it's me it's you
u=null it's you

  • .NET Code:
using System;
using System.Collections.Generic;
using System.Text;
using System.IO;
using System.Xml;
using System.Xml.Serialization;
using System.Runtime.Serialization.Formatters.Binary;

namespace ConsoleApplication
{
    public class Toto
    {
        public string me;
        public override string ToString()
       {

            return me;
       }
    }
  
    [Serializable]
    public class Toto2 : Toto
    {
        public string you;
        public override string ToString()
       {

            return you + " " + me;
        }
    } 

    class Program
    {
        static void Main(string[] args)
        {

            Toto2 t = new Toto2();
            t.me =
"it's me";
            t.you =
"it's you";
            using (FileStream fs = File.Create(@"c:\test.bin"))
           {

                BinaryFormatter bFormatter = new BinaryFormatter();
                bFormatter.Serialize(fs, t);
            }
            Console.WriteLine("t=" + t.ToString());
            Toto2u = null;
            using (FileStream fs = File.Open(@"c:\test.bin", FileMode.Open))
            {

                BinaryFormatter bFormatter = new BinaryFormatter();
                u = (Toto2)bFormatter.Deserialize(fs);
            }
            Console.WriteLine("u="+u.ToString());
            Console.ReadKey();
        }
    }
}

will throw an exception.

5 Minutes of Google Spreadsheets

Today I noticed a Google Spreadsheets link in my gmail screen. I had read about it but never bothered to try before. In the finance industry, a lot of traders use excel, so I was wondering if Google spreadsheets could be another fit.

Unfortunately for Google, under Linux at least, I don’t find Google Spreadsheets usable for anything else than storing and sharing some information, not often updated. Although I admire the engineers that managed to write the Javascript behind Google Spreasheet, it is way too slow for using it in interesting ways. Editing is slow, copy/paste is slow, sorting is slow.

I then wondered if it could read my contacts CSV from GMail (you can export contacts to a CSV file in Gmail). It could be a better interface to edit contacts. But strangely, importing Gmail CSV in Google Spreadsheets does not work.

I don’t think I’ll use it another 5 more minutes.

Procedural Programming in an OO language

OO is an old buzzword, that is not required anymore to get an employment. Recruiter seems to prefer SOA, Web Services, and in France, “mutualisation” and “urbanisation”. Sometimes I really wonder if OO made it.

I am sure many of you are confronted with programmers that love procedural programming in many of your projects. They might use an OO language but in the end will organize everything by “type”, split invariably state and logic. Everything will be so much better stateless. And we will create lookup maps to glue everything back together. In a way I feel they remove the OO of the language.

It’s not necessarily bad programming. Sometimes it is encouraged by standards, after all, that’s the way most Javabeans are used. It can be preferable in some places, for example you don’t want to mix your XML creating code in the object that has to be transformed to XML, this way of transforming objects to XML has been gone a long time ago in Java.

But the excess of it can be quite frustrating.

Back To Real Java, Bye Bye J2EE

I changed job recently. In this new job, it is refreshing to see Java used like in the old days, without the J2EE layers, and without the extra IBM layers of my previous job. Granted, the fresh Java approach does not apply to many projects, because a lot of apps are just about interfacing a database with a web interface. But Spring success showed that even for many of those projects, fresh Java approach with a small framework is enough.

This makes me think about people (on the net) complaining that in some job interviews, candidates were not able to tell how to get a EJB instance, etc.. Those kind of question are really stupid, as what matters much much more are EJBs concepts and concerns, i.e. what it tries to solve and how it tried to solve it, and for example, what is good/bad about it.

Java is much nicer to use in the old way. Everything seems fast to do. I am surprised it is more pleasant to work with Java in this kind of environment than in a web/J2EE environment.

Moving weekly Javablog stats to a new blog

Javablogs.com top 10 weekly/monthly/yearly entries were starting to pollute my blog too much for my taste. It is more appropriate to dedicate a blog to them. That is what I should have done in the first place as it is very easy to have many blogs with blogger.com.

So you’ll find at javabuzz.blogspot.com the weekly top 10 most read entries on Javablogs, and sometimes more.

JSF Was Too Hard for Experienced Developers

While starting to look into Seam, I noticed that all examples use JSF for the view, and there is no alternative to it. If someone like Gavin (from Hibernate fame) thinks JSF is usable, then I probably overlooked something when I looked into it a few years ago, when JSF was the craze of the moment.

At the beginning, JSF looks very similar to ASP.NET. But I have a small experience with ASP.NET, and ASP.NET is quite simple to understand and use. You can throw up inexperienced developers at it, they will manage to create something that works quite quickly. ASP.NET feels quite natural once you understand the postback thingy. JSF is another beast. Maybe part of it is due to the fact that the Java world has no excellent tools integration like Microsoft has (IBM RAD, one of the most advanced concerning integration, is quite far off). But there are also many technological reasons; when I read that article about JSF shortcomings with JSP, I was shocked that even to do very simple things, you would screw up, because simple things can be very complicated in JSF.

What seems to make JSF much nicer is Facelets, as it solves all problems related to JSP and JSF. This might make my JSF experience a good one, after all. I am curious to see if it makes JSF programming really nicer, and if Seam makes the overall very quick to build and understand.

Previous

Next