You are on page 1of 8

Java Source Code Standards Check List

Line Item CLARITY File Headers 1. Does each file have the correct header? Naming Conventions 2. Do all packages start with "com.yourdomainname"? 3. Are package names single lowercase words with no spaces, dashes or special characters (com.domain.package)? 4. Do class names start with a capital letter followed by mixed case (FooBarReader)? 5. Do member functions, variables, and parameters start with a lowercase letter followed by mixed case without underscores (fooFunction)? 6. Do debug-only classes and methods start or end with debug? 7. Are factory classes named xxxFactory with MakeXxx functions? 8. Are getters and setters named getXxx and setXxx and appropriately consistent with the Java Bean specification? 9. Are Boolean getters named isXxx, canXxx, hasXxx, or willXxx? 10. Do methods which return several items of information end in List (getFooList)? 11. Do initialization methods named init()? 12. Are all class variables appropriately prepended with their scope? Static Instance Public gbl pbl Protected, Friendly, Private cls my, i 13. Are constants all uppercase with underscores separating words? (THIS_IS_A_CONSTANT) 14. Are variable names clear (more than 5 characters except for short loops and immediate usage)? 15. Do variable names use contractions which are obvious? 16. Do variable names match obvious sources (for example, SQL column names)? Code Indentation 17. Do braces line up vertically with the code indented from the braces? Commenting Code 18. Does the package have a package.html file describing the basic purpose of the package and how to use its classes? 19. Does every public class, method and variable have a JavaDoc comment which adequately explains how to use the class, method or variable? 20. Do implementations of interfaces or super-class functions rely on the interface/super-class JavaDoc comment? 21. Does the code together with its comments adequately explain how the code operates? 22. Are the following grouped separately with commented markers: constructors, public functions, other functions, inner classes, object functions [toString(), equals()], test harness [main()]? 1 YES NO

23.

For libraries: Does each public class have a javadoc comment including information on: Typical Usage (designed to be used as is or extended with sub-class) Life Cycle (how class is expected to be used in the program) Synchronization (whether thread safe; if thread safe, how?) ROBUSTNESS Synchronization 24. Is access to non-final static variables (glb or cls) synchronized? 25. If the class is designed to be used in an EJB, does it avoid non-final static variables entirely? Parameters, Variables, Constants 26. Are the correct parameters passed? That is, do the calling and called parameters match? 27. Have magic numbers been replaced by constants? 28. Are all object references checked for null before usage? 29. Are class casts made safely (usually by checking with an instanceof)? 30. Are object variables which do not immediately fall out of scope set to null when no longer needed? 31. Are numeric parameters checked for correct range before usage? Computation 32. Are parenthesis used instead of depending on operator precedence and used correctly? 33. Are intermediate results stored instead of recomputed? 34. Is conversion between integers and floats appropriately handled? Exit Points 35. Are all intermediate exit points necessary, appropriate, and obvious? 36. Is all necessary cleanup done before exiting (especially when exiting from try/catch blocks)? 37. Does method only exit through normal means (e.g. does not call System.exit())? Looping 38. If looping over an indexed variable, is the index counter correctly set to the size of the indexed variable? 39. Is the loop guaranteed to terminate? Branching/Switching 40. Does each case which has code end in either a break or a comment that it deliberately intends to fall through to the next case? 41. Is there a default case to handle unexpected input? Miscellaneous 42. Divided by zero handled? MAINTAINABILITY Coupling 43. No public variables without strong justification in comments. 44. Do the classes avoid using protected and package/friendly variables of other classes in the same package? 2

Program Messages/Log Entries 45. Are messages understandable? 46. Does the message adequately describe the source of the problem so a programmer can find the problem (class.method.mark)? 47. Does the message adequately tell the user what the user can do (keep working, kill program, etc.)? 48. Does the message read like a human talking (and not like a robot)? 49. Does the message use correct grammar? 50. Does the message keep the user free from any blame or fear (e.g. does not say "You moron! You pressed the wrong button!" ) Miscellaneous 51. Is each class, method, and variable used and used only for a single purpose? 52. Does the class make use of available class libraries? FUNCTIONALITY 53. Does package meet design requirements? 54. Does the code match the design specification? 55. Does the code create any performance bottlenecks or problems?

Java Source Code Standards Check List Explanation


Line 1. Explanation A header is a comment at the top of the file. Often organizations will want a copyright placed in the header. In such organizations, you may want to champion making the framework open source and using a GPL license for that type of non-proprietary code. The actual information to be placed in the header will vary by organization and project. In the old days, change histories were placed in headers. Since the same information can be obtained from a version control system, it is useless to place manual change histories in header. Note that some version control systems (CVS) will automatically update the change history if the correct tags are used. If this is available, it should be used. 2. 3. 4. 5. 6. 7. 8. Starting packages with your domain name reversed is a Java convention to guarantee a universally unique name space for all packages. Java convention. Spaces especially dont do well in package names. Java convention. Java convention. Make it easy to see your test/debug routines as compared to those which actually operate the system. Used when you build integrated testing/debuging into your classes. Makes it easier to see what the class does. Of course, you have to understand the Factory pattern to understand how to apply this. Ever wonder what makes a class a Java Bean? Nothing. That is, you dont need to implement or inherit from anything to be a Java Bean. A Java Bean just conforms to the Java Bean specification. And the most basic part of the Java Bean specification is the use of get and set functions in a particular pattern. Thats why you see get and set used all over the place. Knowing the actual Java Bean pattern isnt all that important unless you are actually trying to implement a Java Bean. Makes the code using these functions really fun to read! Just trying to make the code using the function easier to read. Ever needed to use several constructors with different parameters, all of which eventually need to execute the same code? Ever notice that you just cant put the common code in a constructor and call it from the other constructors? Drat Oh, well, put the code in a function called init and then call it from the other constructors. This one is often controversial. The point is that your code should clearly show when a variable has a scope beyond the immediate method it is used in. Hence, I like special designations for variables whose scope is beyond a single method. The abbreviations stand for: gbl global You can get to this baby from anywhere. cls class You can get to this baby from almost anywhere. pbl public Like a get and set. i instance Most typical variable type for an ojbect. my not an abbreviation designed to make code easy and fun to read. 4

9. 10. 11.

12.

Note that static variables (gbl and cls) are suspect in object oriented programming and are always discouraged. (But when you need em, you gotta have em.) Public instance variables are useful when you dont need code with the get and set functions and dont need Java Bean conformance. 13. 14. This standard is pretty constant across the programming universe. At least from C to Java. I added this rule when I had a programmer who used one and two character method and variable names throughout his code with absolutely no comments. In fact, we obfuscated and deobfuscated this code (testing the obfuscation software) and the de-obfuscated version was easier to read than the original source code! The loop exception is for the classic loop construct: for ( int i=0; i<stopVar; i++ ) Immediate usage shows up in exception handling and event handling: catch( Exception ex ) handle( Event ev ) Note the use of ex and ev instead of the classic e. Using just the e will cause problems when you start handling exceptions in your event handler. 15. 16. 17. I use vary few contractions because I usually forget what they are. This is a pretty radical idea: if you are bringing a SQL column directly into a variable, name the variable the same as the SQL column. My pet peeve is the C practice of opening braces at the end of one line and putting the closing brace at the start of a line. This makes reading the hard-copy code (hard-copy? Boy am I oldfashioned!) much harder. Paper is cheap and monitors are big now. There is really no reason to keep using that ancient practice. (I know I am going against the flow of Suns Java examples. Maybe Im related to Galilao.) If you include package.html in the package directory, JavaDoc will pick it up and incorporate it on the page describing the class. Great way to do detailed documentation without having to have documents separate from the code. Well, all methods should have a JavaDoc comment. Emphasis on the public methods because the JavaDoc comment should tell other programmers how to use the public interface for the class. There is an exception to every rule. This is the exception to the all public methods should have a JavaDoc comment. If a method implements a method in an interface or overrides a method in a super class, then not adding a JavaDoc comment will cause JavaDoc to use the comment from the interface or super class. This is much easier than writing another comment. You add comments where the code is not obvious. It is not always obvious where comments are needed when you write code. However, if it takes you a while to figure out some piece of code, immediately add a comment with you new found knowledge so that the rest of the world (and you the next time you read this code) can benefit from your newly acquired wisdom.

18.

19.

20.

21.

22.

I like to use visual separates to make it easier to find types of functions both in the editor and on hardcopy. The following is a typical separator:
/* =============================================================================== Constructor =============================================================================== */

Notice that the separator is exactly eighty characters exactly what will typically print on thue usual default settings. Note that this technique will not work with IBM VisualAge which stores by method, not by class (not that that ever happened to my code while evaluating VisualAge). As a side note, I prefer the main() at the end of the class preceded by any toString() or equals(). 23. 24. 25. 26. 27. If you are writing a library which is designed to be used by others, you should go to extra lengths to help the other folks figure out how to correctly use your stuff. Yet another reason to get rid of these puppies. Getting rid of static variables is what allows for thread-safe EJB code. Criss-crossed parameters can be darn hard to debug, especially if the parameters are numbers in a similar range. That is, there are no numbers in the middle of the code which dont have a name. If you need an explanation as to why constants are better than magic numbers, go back to school! Just kidding. It makes maintenance and readability way better. One of the greatest sources of unexpected run-time errors is calling a method on a null object. For example, assume the following function:
foo( RandomObject bar ) { bar.fight(); }

28.

If bar happens to be null, bar.fight() will throw a null pointer exception. Since this is a runtime exception, it is not likely not caught in a try/catch block and it is likely to propagate up the system causing untold damage (usually in the middle of an important demo). Avoid this with:
if ( bar != null ) bar.fight();

29.

Another great source of unexpected run-time errors is casting a variable to something it is not. This can be avoided by doing an instanceof before the cast type. This is not needed if the class being examined can otherwise guarantee that there will never be a class cast exception. For example, if a class loads a Vector with Strings, that class can safely type cast the output of the Vector as a String without doing an instanceof (since it knows it only put in Strings). This is typically an issue when objects are stored in Sets such as Vectors and ArrayLists. I like to avoid this by converting Sets to arrays when being passed over a public interface to another package. That way the compiler can pick up any type case problems. This may be affected by the ongoing work to add generic types to Java. This is a complicated problem. You create an object and store it in a variable. You put the variable in a hash table. You dont need the object any more. It cant be garbage collected until it is no longer pointed to by the variable in the hash table. Either remove that variable from the hash table, or set its value to null. Typically a problem in implementing caches. (It must have been a real problem for me in the past not such a big deal with the EJB architecture.) 6

30.

31.

I prefer to always verify that the parameters I get make sense. It may take up a little extra time, but it makes the code more robust. I dont believe that the use of assertions will reduce the need for this I just dont think you can test all possible paths while the assertions are on and when they are off they wont do any good at all. My motto better safe than sorry. Dont rely on my dear aunt sally. One of my bosses was real big on this. Most programmers do this reflexively. Arf! I dont do this much, so when I do Im liable to screw it up. Note that you can get into this mess with simple division. Academics and idealists often suggest that you should only exit from a method on the last line of a method. Sorry, its just too useful to return as soon as all needed computation is done. Every time I have tried to eliminate intermediate returns, the code becomes real ugly, real fast. But lets find a middle ground and make early returns obvious. Finally. Well classic example for this is to close a file in the finally clause of the try/catch block where the file was opened. System.exit() should only be in response to the user selecting File Exit on a menu. Ive never seen a programmer blow this stricture. I really hope you dont need an explanation as to why this is important. Ditto. This is one of my favorite boo-boos. Favorite in that I do it a lot. And its always a major pain to figure out what went wrong. I have done this so much, I usually code the switch statement as a set of cases and breaks. Only then do I add the actual code between the case and the break. An example of a correct switch:
switch( someInt ) { case ONE: case TWO: case THREE: case FOUR: DoSomething(); break; case FIVE: DoSomething(); // Deliberately fall through to next case case SIX: DoSomethingElse(); break; default: reportBooBoo( unexpected case: + someInt ) }

32. 33. 34. 35.

36. 37. 38. 39. 40.

Cases one through three dont need an explanation because there is no code and its obvious they are designed to fall through. Case five has code and needs the explanation about deliberately falling through. 41. I prefer to have a default case with every case statement which at least logs that the case statement got called with an unexpected case. If you dont at least log it, how will you ever find the problem? See example above. 7

42. 43.

I hope so or you will have unexpected run-time error. Check the divisor for zero before using. Public variables are horrible except when they are great. They are great for simple data structures. For example, passing data from a servlet to a JSP page just needs a simple data structure composed of all public variables. Note that simple data structures are highly suspect in the object oriented world. Comment the class to note that it is a simple data structure for the JSP merge. This is my biggest beef with Java. I can hide my variable from everyone with private. If I do nothing, they are friendly and everyone in my package can get to them (not very objectoriented). If I want my sub-class to have them, I must use protected which still lets everyone in the package see them. There is no way to say only this class and its sub-classes can see the variable. This is usually dealt with last in a project. Make sure that when an error is recorded in a log or shown to the user, that you the programmer can figure out exactly where the error come from. Using the full class name with a unique identifier within the class (typically based on the method name) should do it. If you can figure out what the users options are, you should tell the user. I rarely see this coded. Can programmers ever write messages which the users can understand? Yadda, yadda, yadda You cant do that now is a classic message of this type. If the user cant do that now, dont let em even try. Mom, baseball and apple pie. Dont fall for the not invented here syndrome. Checking this means the reviewer would have to read the design requirements which in turn means there must be a requirements document. Its never too late to make sure the code does what its supposed to. Obviously, you need a design document to check this. Lets hope not. This test is not real robust since it relies on the Mark 1 eye ball with a fair bit of supposition. Settle all arguments by running actual performance tests. That can be a real learning experience. I once crafted a really great optimization which I coded over two days. Excitedly, I made a benchmark test to show off how much I had speeded things up. The test showed that the optimized code was twice as slow as what I started with. Darn. Lesson: test any optimization to see if it really works.

44.

45. 46.

47. 48. 49. 50. 51. 52. 53.

54. 55.

You might also like