This topic is now archived and is closed to further replies.


[java] Good Java Programming Habits / conventions?

Recommended Posts

I''m an experienced C / C++ programmer getting into Java, and I had a few questions about your general programming habits, and what''s considered good practice, and what general conventions there are... 1. Is it good practice to set objects to null when you are done with them (when the object is in scope for the duration of the program), or does the JVM recognize that it''s not being used in either case, and doing this is merely redundant? 2. Is there any convention in naming the classes themselves? I am still wondering why in the Standard Library, class names have no prefix, except for in the javax.swing library, where the class names are prefixed with J; like JFrame and JButton. (I already know about camelNotationLikeThis being used to name methods and variables). 3. How widely used is JavaDoc? 4. For persistant data, is it more common to see data written to, then loaded from a file, or to use Serializable classes? 5. Since constants don''t actually exist for reference types in Java (only the reference itself is constant, not the object behind it... something I miss from C++), should I always make it explicit by making constants UPPERCASE? 6. What sort of Assertion services are there (JDK 1.4)? In C++, I could use preprocessor tags so that certain tests were only performed during debug builds, is there any thing of that sort in Java, so that I can have certain tests that will only run in debug, and not (or barely) affect the performance of my released program? A tremendous thanks to anyone who can answer some of my questions here.

Share this post

Link to post
Share on other sites
1. Yes, you should set variables to null if they continue in scope, but are not needed. The virtual machine does not know whether or not the variable will be used again -- the way it determines garbage collection is by whether or not there exists a reference to the object (so if it's not set to null, it will remain in memory).

2. I believe the naming conventions in Swing have to do with whether or not they are lightweight (implemented entirely in Java for cross-platform compatibility) and heavyweight (may contain native code). All of Swing's stuff is lightweight, and prepended with a J, all of AWT's stuff is provided for backwards compatibility, and does not start with a J (generally it's better to use Swing stuff).
Quoted from The Java Tutorial
The AWT components are those provided by the JDK 1.0 and 1.1 platforms. Although the Java 2 Platform still supports the AWT components, we strongly encourage you to use Swing components instead. You can identify Swing components because their names start with J. The AWT button class, for example, is named Button, while the Swing button class is named JButton. Additionally, the AWT components are in the java.awt package, while the Swing components are in the javax.swing package.

The biggest difference between the AWT components and Swing components is that the Swing components are implemented with absolutely no native code. Since Swing components aren't restricted to the least common denominator -- the features that are present on every platform -- they can have more functionality than AWT components. Because the Swing components have no native code, they can be be shipped as an add-on to JDK 1.1, in addition to being part of the Java 2 Platform.

3. I'm not sure how widely used it is, but I like it. Even if you don't use the generated HTML, it gives you a good framework for what you should put in your comments. It helps considerably when collaborating with more than one person and your code, or their code is black-box. You should try it and decide for yourself, though, whether or not it's worth using.

4. Serializable classes are great

5. That's a style decision. I leave it up to you.

6. Yeah, I miss the preprocessor. I'm not sure of an answer to that, though. Exceptions barely take any processor as far as I know (so long as they're thrown only in really exceptional circumstances). That still will likely require an 'if' in there, though, so for tight loops that could end up screwin ya. Anybody have a good answer on this one?


[edited by - pirate_dau on March 21, 2002 12:45:58 AM]

Share this post

Link to post
Share on other sites
3 - Love javadocs. I always have the javadoc of the api in my browser while I code. Very handy.

4 - You have to be very careful with serializable objects, you can end up writing tens of megabytes of data to stream for simple objects, especially anything graphical. If a class member can be recreated from other data then make it volatile.

The fanatic is incorruptible: if he kills for an idea, he can just as well get himself killed for one; in either case, tyrant or martyr, he is a monster.
--EM Cioran

Opere Citato

Share this post

Link to post
Share on other sites
3. Javadoc is one of my favorite things about java. I never write a function without writing the javadoc comment first.

5. The java code from Sun does this, so I'd reccomend it just for consistancy.

6. In 1.4 you get the assert keyword. Assertions are not removed from the code by the compiler (like in C release builds). They are enabled in the VM via the -ea switch (enable assertions). By default they are disabled. Here's some more info.

"There is no reason good should not triumph at least as often as evil. The triumph of anything is a matter of organization. If there are such things as angels, I hope that they're organized along the lines of the mafia." -Kurt Vonnegut

[edited by - wayfarerx on March 22, 2002 12:57:06 PM]

Share this post

Link to post
Share on other sites
1. A caveat: don''t bother nulling local variables when you''re done; it''s unnecessary

2. All class names are in fact prefixed by their package. Class name should always begin with a capital letter. Prefixing class names is entirely up to you but not generally necessary except where the names tend to conflict with standard library names, like List (found in java.util); this gets annoying when compiling as you need to explicitly specify the package of a type and your code gets ugly. This is why Swing has the J prefix, because it would have conflicted annoyingly with AWT all the time.

3. Widely, but not much on your own hacking

4. Serializable. Be careful about serializing far more than you want to. In 1.4 you now have XMLEncoder as well which is possibly a nicer solution.

5. static final Object OBJ = new Object(); does in fact create a constant Object which will never go away. Use uppercase if it makes you feel happy. Most people do.

6. assert() is in 1.4 but not earlier VMs. You can switch them off at runtime and the code disappears completely. Beware side effects as usual.

Other stuff you won''t know about yet:

- preallocate everything and reuse object pools when writing games. Sun evangelists are still persisting the myth that garbage collection is more efficient than C. It''s nowhere near the speed of stack allocation, and it''ll ruin your framerate and give you horrible 5-10ms pauses in your rendering loop

- never new() an object in your rendering loop that will be discarded at the end of the frame. Result: jerks and slowness, even on the latest bestest VMs.

- don''t be afraid of static when writing games. Most of the time there''s only ever one of a lot of things in games, like Worlds, Maps, etc.

- make things public and access them however you like. If you''re using getXXX() and setXXX() to access member variables you should really be using a dot instead. This point is so contentious it may start a flame war but among OO purists you will find that the get/set pattern is a bit of a cop out.

- use 1.4 Buffers wherever possible. Give up on pre 1.4 VMs because they simply aren''t fast enough for proper game programming.

- if you really want genuine performance, don''t be afraid to use a tiny bit of JNI, to get direct GL access perhaps, or perform a big batch assembly operation on a Buffer''s contents like some specialised 3dnow instructions.

- write a JNI method to get hold of direct buffer addresses and send them back to java. Henceforth use this as a pointer and pass it to other JNI methods requiring access to the buffer, rather than passing the buffer itself.

- Java2D isn''t fast enough to do pretty 2D games. Use GL.

- Java3D may or may not be fast enough, but beware the myriad bugs.


Share this post

Link to post
Share on other sites
1. Any object that goes out of scope will be automatically garbage collected. When the garbage collecter gets around to it. You only need to set an object to null if you want to make sure that it will be garbage collected, usually in your main loop.

2. Prefixes are not used because everything resides in its on little package. This is similar to namespaces in C, where you won''t get naming collisions if you specify a full path to a class, ie java.util.List. As princec said, you only have to be careful when you import a lot of stuff. As for naming conventions, there is no set standard, but I think most people use the same standard as in the API. Capitalize every important letter in the class name, ie BorderLayout and capitalize every letter but the first in the method name, ie setLayout().

3. JavaDoc is only useful if you comment your code in a certain way that JavaDoc can extract it. I don''t think most casual users use it.

4. Personal choice I think.

5. Personal choice I think. The API jumps back and forth with constants.

6. I found something on the Internet about this. Unfortunatly I can''t remember where. One place to look is Thinking in Java by Bruce Eckel. It is free and can be found at He also wrote a similar C++ book and wrote his own assertions for that. He might have some for Java as well.

The only naming convention that is enforced by the compiler is that all public classes must reside in a file of its own and the file name must be the same as the class name. You can put private classes in with the public classes no problem.

Make it work.
Make it fast.

"Commmmpuuuuterrrr.." --Scotty Star Trek IV:The Voyage Home

Share this post

Link to post
Share on other sites