Okay, there’s one, huge, bug-spawning pet peeve of mine in coding Java: premature declaration.
If you have a value that is being used often, and you want to cache it, feel free to make it a private final variable, preferably a private static final variable. Be my guest.
However, as a general rule, you should allocate something when you need it, and let it fall out of scope almost immediately after you’re done using it. If you “accidentally” use it at an inappropriate spot, the compiler will catch that. Garbage collection will thank you.
The most common cause for bugs (and biggest waste of memory) is the one-off instance member variable. Because declaring objects is “expensive” in Java you find all kinds of weird hacks of moving variables that are only used in one method out into the actual body of the object. All of the problems that people hate about global variables then starts to be subject in that class for that variable. On top of it, you’ve then just made the class thread-unsafe unless you do some dangerous synchronization backflips to try to secure it.
Similarly, if you’re using a loop variable, declare it within the loop, not outside. Yes, you’ll produce lots of garbage. That’s fine — that’s why you have a garbage collector. On the other hand, you then don’t have to worry about as many naming issues, and your object vanishes much sooner. On top of it, this kind of coding style allows you to use the “final” modifier with great abundance, which makes your code much easier to read and maintain.
If you need to speed up your code, and you can prove that the bottleneck is in object creation at this area of code, and you are certain that there’s no better algorithm to be using, then and only then can you start to consider premature declaration. I would instead suggest creating a Factory class (probably utilizing Commons-Pool), though. You’re almost always gonig to be better-served at that point, because you are going to be solving the underlying problem (instantiating the Foo class is expensive) instead of the surface problem (this code instantiates a lot of Foo objects).
Related posts:
Pingback: Enfranchised Mind » 7 Actually Useful Things You Didn’t Know Static Typing Could Do: An Introduction for the Dynamic Language Enthusiast