Logging Like it’s 2011

Earlier this year I revisited how I was logging things in Java, and decided I would try a hybrid approach.  I’m reporting back to say that it’s been successful. There are basically two ways I do it now:

Use java.util.Logging for libraries

It turns out that there’s nothing actually wrong with JUL aside from its limitations in terms of configuration.  It has different names than the Ceki Gülcü loggers (warning() instead of warn(), finest() instead of trace(), etc.) but otherwise works the same.  The configuration side of things I can’t even speak do as I haven’t had to configure it, I never use the actual JUL output.

Use Logback for applications

As suspected, Logback is basically just a new version of Log4J.  It’s got some niceties like MDCInsertingServletFilter that means I don’t have to write that filter myself anymore, and it’s supposedly faster and more stable, so there’s no reason I can see not to use it.  I also like that it has a format for condensing class names without completely losing the package names, so it goes from “com.efsavage.application.servlet.LoginServlet” to “c.e.a.s.LoginServlet” instead of just “LoginServlet”.

Why use two?

I like the fact that my libraries have zero logging dependencies and configuration, so I can always pop them into another app without adding baggage or conflicts or much additional configuration.  I can upgrade the logger in one application without having to deal with version conflicts of my other apps and having to do classpath exclusions and that type of nastiness.

Tip

If you do it this way, and you see your JUL logging showing up twice, you can edit the default logging config in your JDK installation, or if you prefer to leave that untouched as I do, try this (via Java Bits):

java.util.logging.Logger rootLogger = LogManager.getLogManager().getLogger("");
Handler[] handlers = rootLogger.getHandlers();
for (int i = 0; i < handlers.length; i++) {
rootLogger.removeHandler(handlers[i]);
}
SLF4JBridgeHandler.install();

This basically yankts out the default logger and let’s SLF4J do it’s thing alone.  In a webapp you’ll probably throw this in your context listener or startup servlet where you previously did your log4j config.

Java 7

Java 7 (AKA Java 1.7.0) is out! What does this mean, is this a Big Deal like Java 3 or 5 or a snoozer like Java 6 or something in the middle like Java 4? It all depends on what you do with it, but for most Java developers, we’re looking at a Java 4-ish release. There are some new APIs, and some really nice syntax cleanup, but ultimately it’s not a big deal.

Here’s the list of what’s changed:

The stuff I hope I don’t have to care about (AKA The Boring Stuff)

These are the under-the-hood changes I will probably only encounter when debugging someone else’s code.

Strict class-file checking

I’m not entirely sure what this is, and it doesn’t seem like too many other people are either.  I think it means that Java 7 files have to declare themselves as different than previous versions and do some pre-verification as part of compilation.  I don’t know if this is actually something new or just declared baggage.

As specified in JSR 202, which was part of Java SE 6, and in the recently-approved maintenance revision of JSR 924, class files of version 51 (SE 7) or later must be verified with the typechecking verifier; the VM must not fail over to the old inferencing verifier.

Upgrade class-loader architecture

Fixes some deadlock issues when writing non-hierarchal custom classloaders.  If you’re writing custom classloaders, this is probably great news.  Unfortunately if you’re writing custom classloaders you’re pretty much screwed with or without this improvement.

More information here.

Method to close a URLClassLoader

Pretty self-explanatory.  if you’re using a URLClassLoader, you may at some point want to close it.  Now you can.

More information here.

SCTP (Stream Control Transmission Protocol)

From what I can gather SCTP is somewhere between UDP’s lightweight “spray and pray” approach and TCP’s heavy-duty “armored convoy”.  Seems like a good choice for modern media narrowcasting and always-on sensor networks, but don’t quote me on that.

More information here.

SDP (Sockets Direct Protocol)

Implementation-specific support for reliable, high-performance network streams over Infiniband connections on Solaris and Linux.

SDP and/or Infiniband seem to networking where you can get more throughput by bypassing the nosy TCP stack, but without completely ignoring it.  Kind of like flashing your badge to the security guard and letting all your friends in, I think?

More information here.

Use the Windows Vista IPv6 stack

I’m assuming that this also applies to Windows 7, but I’ll worry about this when my great-grandkids finally make the switch to IPv6 in 2132.

TLS 1.2

Better than TLS 1.1! (TLS 1.2 is SSL 3.3).

More information here.

Elliptic-curve cryptography (ECC)

The official description sums it up:

A portable implementation of the standard Elliptic Curve Cryptographic (ECC) algorithms, so that all Java applications can use ECC out-of-the-box.

XRender pipeline for Java 2D

Now, when you aren’t gaming, you can  leverage some of your GPU power to do image rendering and manipulation in Java instead of just mining BitCoins.

Create new platform APIs for 6u10 graphics features

Let’s you use opacity and non-rectangluar shapes in your Java GUI apps.

More information here.

Nimbus look-and-feel for Swing

Your Swing apps can now look like outdated OS X apps.

More information here.

Swing JLayer component

Useful way to write less spaghetti when trying to make Java GUI apps behave like other modern frameworks.

More information here.

Gervill sound synthesizer

Looks like a decent audio synthesis toolkit.  Not sure if this really needs to be in the JDK but now you can add reverb to your log file monitor’s beeping.

More information here.

The important stuff I don’t really use (AKA The Stuff I’m Glad Someone Thought Of)

These are the changes that probably only help if you’re on the cutting edge of certain facets of using Java.  Eventually these will probably benefit us all but I doubt many people were waiting for these.

Unicode 6.0

Also self-explanatory, new version of Unicode.  Has the new Indian Rupee Sign (?) and over 2,000 other new glyphs, so it’s certainly important if you use those, but otherwise not so much.  I don’t know enough about switching versions of Unicode to say if this is something to be worried about, but if you have lots of it in your app, it’s probably safe to say you should do some major tests before switching.

More information here.

Locale enhancement

Locale was previously based on RFC 1766, now it is based on BCP 47 and UTR 35.

This isn’t just new data, this is a new data structure, as the number and classification of languages on computers has evolved beyond the capabilities of RFC 1766.  I’ve always been glad that Java is so robust in it’s internationalization support even though I’ve never really taken advantage of most of it.

Separate user locale and user-interface locale

Now this is interesting, but I can’t find any good use cases yet.  My guess is that this is part of Java’s ongoing push towards multi-platform/multi-language interfaces, notably Android.  You can set a Locale (and the rules a locale dictates) not only on geo/cultural basis but on a device/environment basis.  Locale.Category only has two entries but I wouldn’t be surprised if more of them creep in in future versions.

JDBC 4.1

java.sql.Connection, java.sql.Statement, and java.sql.ResultSet are AutoCloseable (see try-with-resources below).

Also, you can now get RowSets from a RowSetFactory that you get from a RowSetProvider.  If you’re still writing JDBC this probably makes your life easier, but only in the “at least I”m not writing custom classloaders” way.

Update the XML stack

Upgrade the components of the XML stack to the most recent stable versions: JAXP 1.4, JAXB 2.2a, and JAX-WS 2.2

Your XML library is always a version that’s too old or too new, so you might as well go with the new one.

The important stuff I don’t use yet (AKA The Cool Stuff)

InvokeDynamic – Support for dynamically-typed languages (JSR 292)

The short version is that this makes things better for people implementing dynamically-typed languages on the JVM, like Clojure.  While the JVM is actually less statically typed than you might think if you’ve only used it via normal Java, methods in particular were difficult for these languages.

The long version is here.

Enhanced MBeans

I’ve never knowingly used MBeans (Managed Beans), but they do seem useful for large systems.  Regardless, they’ve been enhanced:

Enhancements to the existing com.sun.management MBeans to report the recent CPU load of the whole system, the CPU load of the JVM process, and to send JMX notifications when GC events occur (this feature previously included an enhanced JMX Agent, but that was dropped due to lack of time).

The Important Stuff I Use (AKA The Good Stuff)

These are the reasons I’ve even bothered to look at Java 7.  I’ll probably write a follow-up on each of these when I have some experience with them.

JSR 203: More new I/O APIs for the Java platform (NIO.2)

I’m including this here because I’m actually doing some data/file work where this will come in handy.  Basically this exposes a lot of I/O and Filesystem functionality that you previously had to dip into native libraries for, like actually telling the OS to copy a file rather than reading and writing the data yourself.  If you’re not doing any file-based work right now, keep a mental note to look into this the next time you type “File”.

More information here.

NIO.2 filesystem provider for zip/jar archives

Included here for similar reasons as the previous item, but I think it’s pretty cool that you can treat a zip file as a filesystem and operate within it.  Unfortunately it looks like the basic implementation is read-only, but I’m guessing the pieces are there for a read/write version.

More information here.

Concurrency and collections updates (jsr166y)

java.util.concurrent, as far as I’m concerned, is something everyone who considers him/herself a senior Java dev should be familiar with.  It’s rare that your code will not be able to take advantage of it in some way.  One of the missing pieces was a good fork/join component, where you can split jobs and wait for them all to complete in parallel before moving on.  I actually built a version of this approach (sadly not open sourced), so I’m eager to tinker with the new standard one.  I expect that list most of the concurrent library you’ll need to sprinkle in some of your own helper code to make things elegant, but the hard parts are solved and built and ready for assembly.

More information here.

Project Coin – Small language enhancements (JSR 334)

Ah, the sugary goodness that you’ve been waiting for.

  • Strings in switchNot terribly useful since we could (and probably still should) use enums, and you still have to use if blocks for anything fancy like regex matches.
  • Binary integral literals and underscores in numeric literalsI never really thought of this as a problem, much less one worth solving, but sure, why not.
  • Multi-catch and more precise rethrowNow this, as an ardent fan of exceptions, I like.  It not only cuts down on copy/paste exception handling, it helps avoid subclassing exceptions, which is almost always the wrong approach.  More info on this later.
  • Improved type inference for generic instance creation (diamond)Great idea that really should have always been there. Example:
    Map<String,Integer> myMap = new HashMap<>();
  • try-with-resources statementProbably the most important syntax change.  Now you can skip all of those finally { resource.close(); } blocks that were important but verbose even for my taste.  Doesn’t really help with the situation of the close method throwing an exception of its own though, so I’m curious to see how I end up handling that situation.
  • Simplified varargs method invocationJust avoids some methods that really never should have been there in the first place.

More information here (PDF).

Summary

So basically, a bunch of “nice to have” stuff.  Code will be a little cleaner, resources will be closed a little more often.  GUI apps will be a little fancier.  Some more people might try concurrency.  Programs will run a little faster.  The next thing you know we’ll be looking at Java 8

 

 

 

To switch or not to switch, Part 1

This entry is part 1 of 3 in the series To switch or not to switch

I was listening to a talk the other day and the speaker derisively mentioned “those people who are happy writing Java for the rest of their lives”, and I thought “Am I one of those?” and then I thought “is that a bad thing?”. As part of my “question everything” journey, I decided that it was time, after 10+ years, to have Java report for inspection and force it to defend its title.

I should make it clear, that I am not a language geek, or collector. I generally disagree with “use the right language for the right problem”, I prefer “use the right language for most of your problems”. So far, Java has been that for me. Some things I do in Java are more easily done in other languages, but not so much so that it overtakes the headaches of heterogeneous codebases. If something is really difficult, or impossible in your main language, bring something else in, but keep it simple. I also think it’s fine to have more than one main language, a client of mine is currently transitioning off C#, keeping Java, and adding Python. What they don’t have is random parts of their infrastructure done in erlang or perl or tcl because that’s what someone wanted to use that day.

I could make this task easier and just look at the “marketable” skills out there, which is a small subset. While I think it’s unlikely that there is some forgetten language just waiting for its moment, it’s certainly possible I could find a neat one that’s fun to play with. Languages like Ruby and Python spent years before people could find jobs doing them. So I’m going to look at literally every single language I can find, and put them through a series of tests. If you find a language I haven’t mentioned, let me know and it will be given the same chance as the rest.

Round 1:

The point of this round is to identify languages that have any potential for being useful to me.

Qualifying Criteria

Rule 1. It must be “active”.
This is admitedly a subjective term, but we’ll see how it goes. Simula is clearly not active, while Processing clearly is, with a release only weeks ago.
Rule 2. It must compile and run on modern consumer hardware and operating systems.
This means, at minimum, it works on at least one modern flavor of Linux, because I will want this to run on a server somewhere, and I don’t want a Windows or OS X server, or worse, something obscure. For bonus points, it will also work on Windows 7 and/or OS X.

So, that’s it for now. There are no requirements for web frameworks or lambdas or preference for static versus dynamic typing, I think those elements will play out in later rounds.

  • Ada
  • Agena
  • ALGOL 68
  • ATS
  • BASIC
  • BETA
  • Boo
  • C
  • C#
  • C++
  • Clean
  • Clojure
  • COBOL
  • Cobra
  • Common Lisp
  • D
  • Diesel
  • Dylan
  • E
  • Eiffel
  • Erlang
  • F#
  • Factor
  • Falcon
  • Fantom
  • FORTH
  • Fortran
  • GameMonkey Script
  • Go
  • Groovy
  • Haskell
  • Icon
  • Io
  • Ioke
  • Java
  • JavaScript
  • Logo
  • Lua
  • Maple
  • MiniD
  • Mirah
  • Miranda
  • Modula-3
  • MUMPS
  • Nu
  • Objective Caml
  • Objective-C
  • Pascal
  • Perl
  • PHP
  • Pike
  • Processing
  • Pure
  • Python
  • Reia
  • Ruby
  • Sather
  • Scala
  • Scheme
  • Scratch
  • Self
  • SPARK
  • SQL
  • Squeak
  • Squirrel
  • Tcl
  • Tea
  • Timber
  • Unicon
  • Vala
  • Visual Basic .NET

This list is actually a LOT longer than I expected, and yes, there actually is a modern version of ALGOL 68. Stay tuned for part 2.

Logging Like it’s 2002

I’ve been going through my old code, looking for stuff that might be worth sharing. At the same time, I’ve been maven-izing my builds, and decided I should revisit each dependency, as some of this code is so old the dependencies are very out of date and/or included in the JDK now. Which brings me to log4j.

I’ve literally used log4j on everything I can ever remember doing in Java, but not anymore. Don’t get me wrong, I have no problem with it, and may continue to use it in my applications (if I don’t like logback), but I won’t be including it in any libraries anymore. After 8 years, I’ve finally adopted JUL. Here’s the options and why I chose JUL:

JUL (java.util.logging)

Pros

I’ll start with the victor, because the reason is the simplest. No dependency or version issues, one less thing to download, guaranteed to be there. There is also plenty of code out there to use one of the other frameworks to do your actual logging, so the config isn’t really a burden on the developers using the library.

Cons

Not sure yet. It’s not widely used, but I think that’s because there are far more Java frameworks/applications out there than libraries. There is also a performance issue with SLF4J when you have JUL logging set to a low level, but you shouldn’t need to run (presumably stable) libraries in debug or trace when performance is an issue (e.g. in production), only when you’re trying to debug something. The JUL’s actually logging isn’t really relevant here, as I think most applications will just be running it’s output through their own logging framework.

log4j

Pros

Works great, very stable, hasn’t changed in long enough that you only have version issues when you’re dealing with REALLY old code.

Cons

Less people are using it, more projects are going to SLF4J/Logback. These new frameworks do add some nice features, and log4j is basically abandoned, so I think it’s time to stop doing anything new with it.

commons logging

Pros

None?

Cons

I’ve always been against commons logging, because 99% of the time, it was just used to wrap log4j. The logic was that you could plug custom logging into it, but you can do that with log4j already, so it’s basically an abstraction of an extensible framework, with zero added value. Actually you have less value because you lose things like MDC. At this point it’s like a virus that just won’t go away, and always seems to end up in the classpath somehow. As far as I’m concerned, I consider this a completely superseded library.

logback

Pros

From what I can gather, logback really is (as claimed on their website) the continuation of log4j. Not having used it, I can only assume this is a good thing, and it just adds new features like parameterization. I’m going to try logback in my next application, and since logback includes slf4j, I will access my library logging that way.

Cons

It’s not really in wide usage yet, which means that a library requiring it is going to add an extra dependency.

slf4j

Pros

If logback is the modern version of log4j, slf4j is the supposedly useful version of commons logging, and supposedly improved version of JUL. It’s not a logger per se, it’s just an API/facade. It has the ability to combine multiple logging APIs and legacy frameworks into one stream, which is why it seems to be getting traction on complex applications.

Cons

I’ve had some serious versioning issues with slf4j, due to some methods being removed or changed, so you end up with older code throwing errors when you use a newer version, thus requiring that you only use the old version and introduce the chance for strange errors in code expecting the newer version. For this reason, I don’t feel very comfortable specifying any version of slf4j, and I will leave it to the user to add it if they wish.

Conclusion

So JUL seems like the best choice for a stable, single-purpose library to use, as it’s the least imposing on whatever uses it. It should be noted that I haven’t actually used JUL yet in a real app, so perhaps I will find out that there’s an actual reason for its lack of popularity. If that’s the case, I will likely use slf4j, and try and find out which methods cause issues so I can avoid them, and not be the person someone else curses for requiring it.

Contrary Opinion: Code coverage by checked exceptions

This is the first in what will hopefully be a series of statements that I may not entirely believe, but to put out there to see if they are viable…

Conventional Wisdom: Unit tests are great, you should have lots of them. More code coverage is better.

Conventional Sentiment: Checked exceptions are a hassle, more trouble than thier worse, promote sloppy coding, etc.

Contrary Opinion: Checked exceptions are a better way to address code coverage than unit tests.

On a scale of 1-10 of using and advocating for checked exceptions, I’m probably an 11. I completely disagree with pretty much all of the conventional complaints against them. They do not promote spaghetti code, they actually clean up your normal logic and neatly compartmentalize your error handling. They do not promote sloppy behaviors like exception swallowing, that’s entirely the programmer’s fault. Adding or removing exceptions breaks client code. Yes, it does, why is this a problem? You added additional error conditions, meaning you changed your contract with the clients, and they should be revisited. If you didn’t have this obvious way to signal a change, chances are that the client would handle things incorrectly. Even some of the major voices in computer science have fallen out of love with them, but usually the reasoning is based on people using them wrong (or being too hard to use right).

On a scale of 1-10 of using and advocating for unit tests, I’m probably a 2. They absolutely have their uses. A straight-up algorithm, especially things like math and parsing, should be unit tested for various input values to assure they’re returning the proper value. However in most modern business/consumer software these represent a very small portion of your code. There are far more lines of code dealing with things like authentication, user inputs, file loading, database and network operations, etc. These are complex activities. Even simple CRUD applications can end up invoking hundreds of functions across dozens of libraries for every operation.

The crux of my argument is that if you use exceptions properly, you don’t need to test if an operation completed properly. If the operation completes, it did so properly, all other conditions would fail to complete. Since you want to be using exceptions properly anyways for cleaner code, unit testing this code is redundant but a waste of time and energy to write and maintain. Not only that but exceptions give you code coverage at compile time AND error handling at run time, which unit tests cannot do.

If you disagree, please tell me why!

Java Goofs: Enhanced For Loop

One of the “big deals” in Java 5 was the enhanced for-loop. Basically you could trim this:

for(int i=0;i<collection.size();i++) {
Object object = collection.get(i);
doSomething(object);
}

down to this:
for(Object object:collection) {
doSomething(object);
}

I don’t think such an improvement was really necessary, but combine this with generics and I have to admit your code does look a little cleaner, so I use them when possible. However, the for-loop is basically a half-implemented hack with two major goofs.

1. It works with anything implementing Iterable, and arrays. Despite working with anything Iterable, it does not work actual iterators, which seems just silly to me.
2. If the collection is null, it throws a NullPointerException. The only defense I’ve seen for this is that “a null collection is not the same as an empty collection”. Agreed, and those people clearly missed the point. The point was to clean up the code and now we have to add the same silly if(collection==null) around the loop. If your code really did need to know if the collection was null (e.g. lazy-loading), it’s going to check anyways, but this would save at least one more repetitive line if the loop just treated null as empty and did nothing.

Missing Java Annotations

@SelfExplanatory – I’d love to be able to turn on JavaDoc warnings in Eclipse, but I can’t. Why? Because 90% + of the code is self explanatory. Do I really need to see that getName() “Returns the name”, or that setName(String name) has the utter audacity to “Set the name”? No, I don’t. Put a @SelfExplanatory and JavaDoc can create these braindead comments without cluttering up my code, while Eclipse can reserve its warnings for the more interesting methods.

@NotNull – Other languages may have solved or avoided this problem, but I’d like to be able to dictate that a variable can be set to anything except null, and also that a method will never return null. It would just save so many headaches (of the onerous Runtime variety, no less), as well as lots of “if (foo == null)”…

The ulterior purpose of this post is to test the upgrade to WordPress 2.6.

Generics: All or nothing?

I am a big fan of strong typing, so when Java 5 added support for generics, I started using them heavily. I don’t agree that that they “clean up” your code, because I see as many or more instances of type parameters, <Class>, as I used to see type casts, (Class). However, they do make code easier to read and follow.

I’ve also been using interfaces more and more over the years, and these days I’d say I use them on almost all of my beans. The lightweight multiple inheritance helps with organization, and when you’re dealing with libraries that monkey with the internal working of your code like proxied beans in Spring and Hibernate objects, interfaces are helpful if not required.

A while back, I inadvertently discovered a pitfall that had been plaguing a project of mine in a very confusing manner. Parameterizing a class should avoid class cast exceptions because of strong typing, but you have to be careful to keep it parameterized, or you can end up causing some very nasty runtime bugs. To illustrate, here is a simple example:

(forgive the formatting, WordPress’ editor is poor at handling code…

First we have a Person interface. People have IDs and vehicles.

package com.efsavage.generic;
import java.util.Set;
public interface Person<PK extends Comparable> {
public PK getId();
public void setId(PK id);
public Set<Vehicle> getVehicles();
public void setVehicles(Set<Vehicle> vehicles);
}

We also have a Vehicle interface, the fields of which are unimportant here:

package com.efsavage.generic;
public interface Vehicle { }

And we have an implementation of the Person interface:

package com.efsavage.generic;
import java.util.Set;
public class PersonImpl implements Person {
private Integer id;
private Set vehicles;
public Integer getId() {
return id;
}
public void setId(Integer id) {
this.id = id;
}
public Set getVehicles() {
return vehicles;
}
public void setVehicles(Set vehicles) {
this.vehicles = vehicles;
}
}

So now let’s write a little test:

package com.efsavage.generic;
import java.util.Set;
public class PersonTest {
public static void main(String[] args) {
Person me = new PersonImpl();
Person<Integer> you = new PersonImpl();
me.setId("5");
you.setId(5);
Set<String> myVehicles = me.getVehicles();
Set<Vehicle> yourVehicles = you.getVehicles();
}
}

This code compiles fine (though Eclipse will flag a few warnings). There’s two problems here.

Despite the fact that PersonImpl implements Person<Integer>, I’m able to set a string via me.setId(“5”), because I did not keep that parameter when I cast me to Person, without a parameter. I would have expected the parameter to be inferred here.

The other problem is that I’m able to cast myVehicles to Set<String>! This wasn’t even a parameter I defined, it’s right in Person. However, by using Person without the PK parameter, Java ignores all other parameters too!

I’m sure someone thought this was a good idea, and there’s a reasonable explanation deep in the JCP forums, but it just seems wrong to me, so be careful to check your parameters if you find weird class cast exceptions showing up in your logs.

Wish List: Session Moratorium

DetourA feature that the major open-source/free servlet containers (Tomcat, Jetty, Resin) lack, AFAIK, is the ability to tell the container to stop issuing new sessions, and more importantly, make this flag known to the HTTP server connector. One or more of Websphere, Weblogic, and ATG Dynamo (I forget which) has this ability, and it’s extremely useful for higher-volume websites.

How it works: Server Bank A is running, Server Bank B is dormant. When you have a new release, you push it to B. Once B is up and running (this can take a while with some advanced applications), you tell A to stop issuing new sessions, and the load balancers send all new traffic to B. Once traffic has bled off of A entirely, A becomes dormant, and is ready for the next release.

Why it’s valuable: You can do a release without interrupting any sessions. This was particularly valuable on the project we used it on, because there was plenty of time to pre-compile pages, and the transactions were relatively high-value ones, so it was worth the price of the commercial license to ensure that none were lost or interrupted.

Considering all of the containers are relatively close performance-wise, and feature-wise, I think this would be a “killer feature” for any OSS container that had it.

Naming Conventions: Java Packages

When developing, conventions can mean the difference between producing something clear and concise and producing something confusing and arcane. They exist at all levels, from the industry and the language down to specific modules of applications. I’m going to attempt to codify some conventions for aspects I use heavily, and I’ll start with one of the easier ones, Java package names. Sun has some basic ones, but I think some more specific guidelines are warranted.

  1. Names should be all lowercase. Uppercase and mixed case denote other concepts in Java and there’s no need to muddy the waters further.
  2. Names should be alphanumeric, preferably just alphabetical.
  3. Do not use version numbers or dates (see below for a possible exception).
  4. Use tld.domain-you-own.project/library.* for distributed or published code. This follows with Sun’s convention, and is the only way to know a name is globally unique, or at least that you are the one that’s allowed to use it.
  5. Do not use tld.domain-you-own.* for internal code that should not be distributed. I typically just use the project or library’s name as the first segment. This convention can be useful in signaling other developers that code is for internal use only, and if something is converted from internal to external usage, this will help identify which version an application was built against.
  6. Package names that are nouns should be singular (mycompany.myproject.account). This maintains consistency with packages that are named for actions (mycompany.myproject.search) and adjectives (mycompany.myproject.common).
  7. Store DAOs in a “data” subpackage. This helps the tree-views in IDEs and also allows for easier control of logging. If you’re being formal and encapsulate DAO operations in a manager class, the manager class should not be in the data package because it’s grammar is business-based, not persistence-based.
  8. Classes that are heavily dependent on third-party packages should be in a subpackage named for the primary dependency. A Hibernate implementation of your DAO should live in mycompany.myproject.data.hibernate. This helps greatly with logging configuration. This is one place where version numbers are permissible, such as mycompany.myproject.data.hibernate3. Use this exception very sparingly, as it can be confusing with regards to forward compatibility.
  9. Classes that are extensions of third-party code should be named for the dependency and be outside of the project’s or product’s context. For example, if you are creating a new type of controller for Spring MVC that does not depend on project-specific code, put it in mycompany.spring.controller. If it is integrated with the application, see the previous point.
  10. Don’t expose organizational details in the package structure (mycompany.mydepartment.myproject). Naming packages by department, office, or region will surely be confusing soon due to management’s penchant to reorganize and reassign.

I consider the above a work in-progress, and welcome comments.