You are on page 1of 17

JAVA Coding Standards(SG620)

Version Released on Author Last Revised by : : : : 1.5 29th June 2005 Ashish Gupta Namita Sehgal

Perot Systems Technology Services Plot # 3, Sector 125 NOIDA - 201301 Uttar Pradesh, India

Security Classification: Perot Systems Technology Services Confidential


This is a controlled document. Unauthorized access, copying and replication is prohibited. This document must not be copied in whole or part by any means, without the written authorization of Head of Quality Assurance Group, Perot Systems Technology Services.

People. Processes. Technology. Results.

www.perotsystems.com

Proprietary and confidential. 2005 Perot Systems. All rights reserved.

Contents

1.

Overview..

1.1. Intended Audience .......................................................................................3 1.2. Acronyms & Definitions ..............................................................................3 1.3. Responsibilities..............................................................................................3 1.4. Quality Record Forms ..................................................................................3 1.5. References ......................................................................................................3

2. 3.

Introduction ..3
2.1. Conventions...................................................................................................4

Naming Conventions

3.1. Package...........................................................................................................4 3.2. Class ................................................................................................................4 3.3. Interface..........................................................................................................4 3.4. Methods..........................................................................................................5 3.5. Variables.........................................................................................................5 3.6. Member variables..........................................................................................5 3.7. Constants........................................................................................................5 3.8. Accessors and Mutators ...............................................................................5 3.9. Exceptions ......................................................................................................5 3.10. Swing components Naming convention ..........................................5 3.11. Enterprise Java Beans Naming convention......................................7 3.12. JSP / Servlet Naming convention .....................................................7

4.

Header & Footer

..7

4.1. Header ............................................................................................................7 4.2. Footer ..............................................................................................................8

5. 6. 7. 8. 9.

Documentation Format Layout

.8

.9 .11 .11

Best Practices (JSP/ Servlet/ EJB inclusive) AMENDMENT HISTORY

.16

SG620:JAVA Coding Standards Version 1.5

Confidential

Page 2 of 17

1.

Overview
The purpose of programming standards is to support the development of applications that are consistent and well written. Standards and guidelines help developers to create a code base with a uniform presentation, which leads to code that is easy to understand, easy for other developers to use and easy to maintain. Standards and guidelines also help developers to avoid the common pitfalls of Java that leads to code that is robust, reliable and portable. Coding standards for Java are essential and should be adopted to achieve the following goals.

Facilitate joint development Avoid common pitfalls Maintainability Reliability Readability/Comprehensibility

1.1. Intended Audience


This guideline is intended for use by developers and reviewers in Java.

1.2. Acronyms & Definitions


Acronym Description PS TS DCA VER Perot systems Technology Services Document Control Administrator Version

1.3. Responsibilities
None

1.4. Quality Record Forms


None

1.5. References
None

2.

Introduction
In the beginning it was very simple, a programmer sitting at his desk churning away code in his garage. He was one with his code, he knew where everything was, didn't have any uses for UMLs, structures or comments, and there were absolutely no co-workers, bosses and people like me writing documents like this telling you what you should and shouldn't do. It was the

SG620:JAVA Coding Standards Version 1.5

Confidential

Page 3 of 17

golden days, where every programmer knew how to write assembler in any language, comments were for wine critics and programming was an art. Today it's difficult to imagine any type of large-scale system with 1 programmer on it. The modern day programmer spend less time coding, more time collaborating, after all it's all about the team. Communication between programmers is a key factor in a successful software shop. Everyone needs to be kept on the same page throughout the cycle. Amongst different levels of systems, source code plays a vital role, this is the heart of our system and programmers/developers should not have too much trouble navigating through it. Coding standard is not there to play gestapo and force upon us an idealistic "standard", stripping us of our style and personality, this is there as a guide, creating a commonality amongst programmers to increase readability, productivity, maintainability, robustness and professionalism. Imagine a bunch of construction workers refusing to conform to one "construction standard", allowing different types of building methods for everyone, would we feel safe walking into such building? Software should no less be different. We all depend on each other's work to make come about something greater.

2.1. Conventions
The conventions followed in the document are the same as specified in the Documentation Standards SG510.

3.

Naming Conventions

3.1. Package
PS TS written code should always begin with com.PS TS unless specified
otherwise. Capitals should not be used in the packages names. Automated unit test cases using frameworks like JUnit should be placed in a parallel package hierarchy in a separate source folder. Using the same package naming convention for them would cater to easy testability of complex protected methods.

3.2. Class

Class names should be descriptive nouns or noun phrases, not overly long, with first letter of every word in uppercase. Some examples of conforming names are

SecurityManager ClassLoader

3.3. Interface

Same naming convention as that for class, usually ending in suffixes like able, or Listener. Some examples of conforming names are

Loggable Nameable Runnable


Confidential Page 4 of 17

SG620:JAVA Coding Standards Version 1.5

QueueListener ActionListener

3.4. Methods

Method names should be verbs or verb phrases, with first letter in lower case and first letter of every subsequent word in uppercase. Some examples of conforming names are

log processRequest certify

3.5. Variables

Variables should have names that are nouns, noun phrases, or abbreviations for nouns. Names of fields that are not final should have the first letter in lower case and first letter of the subsequent words in uppercase. Some examples of conforming names are
logger logManager

o o

3.6. Member variables


o o

Member variables should have m_ appended to them. Some examples of conforming names are
m_logger m_logManager

3.7. Constants

The names of constants in interface types and final variables of class types should be a sequence of one or more words, acronyms, or abbreviations, all uppercase, with words separated by underscore "_" characters. Some examples of conforming names are
MIN_VALUE MAX_VALUE

o o

3.8. Accessors and Mutators


Accessors should be named getProperty (where property is the name of the member they are supposed to retrieve) Mutators should be named setProperty (where property is the name of the member they are supposed to mutate)

3.9. Exceptions

Exceptions should follow the same naming conventions as those for naming classes, they must additionally be suffixed by the word Exception

3.10. Swing components Naming convention


SG620:JAVA Coding Standards Version 1.5 Confidential Page 5 of 17

A control or a component name should have two parts. First part or the prefix should help in identifying the type of the control. Second part should identify the functionality or the purpose of the component. The name should additionally conform to conventions for variables and member variables. Use the following table to identify prefixes for particular Swing components Control/ Component Type Button Check Box Color Chooser (or Dialog) Combo Box Desktop Pane Editor Pane File Chooser (or Dialog) Frame Internal Frame Label Layered Pane List Menu Bar Option Pane Panel Password Field Popup Menu Progress Bar Radio Button Scroll Bar Scroll Pane Separator Slider Split Pane Tabbed Pane Table Text Area Text Field Prefix btn cbx clrdial cmb dskpan edtpan fldial fr intfr lbl lypan lst mnubr optpan pnl pwdf ppmnu prgbr rdbtn scbr scpan sep sldr splt tbpan tbl txta txtf
Confidential Page 6 of 17

SG620:JAVA Coding Standards Version 1.5

Text Pane Toggle Button Tool Bar Tree

txtp tgbtn tlbr tre

3.11. Enterprise Java Beans Naming convention


Entity Beans should be named NameEntityEJB.java Session Beans should be named NameSessionEJB.java Entity Bean Homes should be named NameEntityHome.java Session Beans should be named NameSessionHome.java Entity Bean Remotes should be named NameEntityRemote.java Session Bean Remotes should be named NameSessionRemote.java Each entity bean should have a Serializable primary key class which should be named NameEntityPK.java

3.12. JSP / Servlet Naming convention


Servlets should be named as NameServlet.java For JSPs follow your project specific conventions, no need to suffix it with JSP as the extension clearly indicates that it is a JSP Identifying session variables is a design time issue, and all session variables should be identified right then. The session variables should be named as ssnVarName. (Suggestion: The session variables should not be accessed thru specifying their names as string literals, rather a common interface should have public static final String corresponding to them. These should then be used across Servlets/Actions/JSPs. This would prevent misspelt name based null fetches, propagative changes in case of a name change. This is specially of help in a big environment where JSP coder and Servlet/Action coders are two different roles.

4.

Header & Footer

4.1. Header
Every Java code file written by PS TS should bear the following copyright block as the first thing in the file
/* * $Id $ * PS TS 2001-2002. * All Rights Reserved. * This software and documentation is the confidential and proprietary * information of PS TS ("Confidential Information"). * You shall not disclose such Confidential Information and shall use * it only in accordance with the terms of the license agreement you * entered into with PS TS Corporation. * Unauthorized reproduction or distribution of this Confidential Information, * or any portion of it, may result in severe civil and criminal penalties. * * Developed by PS TS. * */ SG620:JAVA Coding Standards Version 1.5 Confidential Page 7 of 17

The keyword $ID $ above will expand into the Versioning repository identifier for the code file.

4.2. Footer

Every Java Code file written by PS TS should contain the modification log in its footer. The use of key word $log $ is recommended. In version management systems like CVS and PVCS this will auto expand into any comments entered during a commit to the versioning system. The following should be the footer
/* * $log $ */

5.

Documentation

Collaboration requires we communicate at every level possible, especially in our source code. Sometimes the very programmers who wrote the code themselves forget what they wrote. Documentation will save your time and times of others, while effectively making you a vital player in the team. All classes should begin with a class header comment, which is in the following format
/** * The first sentence is used by Javadoc to make summary of this class. * The first sentence should be crisp, brief and informative enough * to stand on it's own. Follow the Javadoc @ tags to maximize your * comments. * * @version $Revision$ $Date$ * @author Your name here * @see java.io.IOException */

Each class comment block must include o o o o Exactly one @version At least one @author Use of keywords $Revision$ and $Date$ to fill in @version tags is recommended
@see

or {@link..} for every non trivial class referred to by this class.

Each method comments should include o Purpose of the method o o o o o o o o Preconditions Effects Algorithmic notes Examples of usage
@param

based description of all input parameters based description of the returned value based description of all the exceptions

@return @throws @link

or @see based reference to all the referred methods


Confidential Page 8 of 17

SG620:JAVA Coding Standards Version 1.5

JAVADOC style comments should not be used inside methods C style (/*.*/) comments should be used for explaining logical block of statements. (Please be aware that having once documented a methods algorithm in the method comments, it may not be necessary to document every line of code in that method). Think and document complex blocks, which you think may be difficult for a new reader to comprehend. Avoid over documentation. C++ style (// ..) comments should be used for briefly describing a particular statement (preferably place the comment at the end of the statement, in the same line). Precede a comment line of any kind with a blank line. Immediately follow up the comment line with the code block for which it is intended. Take full advantage of JAVADOC and HTML tags to significantly improve the readability at HTML levels. Here are some of the HTML tags you can use <UL> This is a bulleted list<li>a bullet point</li></UL> <CODE> - Emphasize as code <PRE> - pre-format <B> - boldify <i> - italicize

o o o o o

6.

Format
Following formatting rules should be obeyed

Indentation consists of spaces only (in particular no tab characters allowed). 80 column line is recommended Statement spill over (in case the statement cannot fit in a single line) should be indented. The recommended indentation techniques are o Begin at the same level where the right hand side of the previous statement began o o Or Indent one level in However only one of the above should be consistently used for a project.

Each indentation level is four spaces. Method declarations are seperated from the comments of the following method by exactly two lines of whitespaces. Complex statements (if-else, for, while, etc.) should be fully parenthesized, for readability and clarity. Statements with in complex expressions should be indented one level more than the outer complex expression. No more that one simple statement should be put on a line. Left-brace ("{") placement occurs at the end of the current line of code in all cases. Code follows on the next line, indented by a single indentation
Confidential Page 9 of 17

SG620:JAVA Coding Standards Version 1.5

spaces. Right-closing-brace (}) placement occurs in a new line. Example displays the various related situations
/** * Class below */ public class Junk { /* * Method here */ public void foo(ParameterType paramType) { if (condition) { } else { } for (int i = 0; i < loopLimit; i++) { } } }

For all paired statements like try-catch, if-else, do-while etc. the second part of the statement should begin on the same line as the closing brace of the first.
try { /* Block comment */ } catch (MyException e) { /* TODO */ }

All binary operations (except .) (+, /, *, etc.) and assignments should be buffered by a single space. Unary operations (like -, !, and ++) should not be separated by their operands. For example:
double x = (y + z); x++;

Brackets should always be used for conditionals and loops (even if there is a single statement within). For example:
if (condition) { a = b + c; }

A keyword followed by a parenthesis should be separated by a single blank space. For example:
if (condition) {

A blank space should not be used between a method name and its opening parenthesis for the parameters. For example:
public void foo(int b, int c) { m_a = b + c; }

Within parenthesis arguments, or expressions should have a blank space after the delimiter. For example:
public void foo(int b, int[] c) { for (int i = 0; i < c.length; i++) { ... } }

It is recommended to have application-logging statements indented at the same level as method declarations. For example:
public class Junk { public void foo(int b, int c) { if (condition) { a = b + c; logger.debug(); } } }

SG620:JAVA Coding Standards Version 1.5

Confidential

Page 10 of 17

7.

Layout

The header as described above should immediately be followed by the package statement Import statements should follow the package statement. Import statements should be ordered according to following rules 1. Core imports of the form "import java.<packagename>" are listed first; imports of standard Java extensions of the form "import javax.<packagename>" are listed next; and all remaining imports follow. 2. Import lists (core, extension and other) are sorted in alphabetic order independently. 3. Avoid import lines which use the '*' construct (like "import java.io.*"). Using this construct makes it difficult to determine exactly which classes are referenced by your class without detailed inspection of the code.

Public Class level variables should be declared first with in a class (usually public static finals), followed by public Class level methods (public statics), followed by public instance methods (grouped by functionality), followed by protected instance methods, followed by package instance methods, followed by private instance methods, followed by protected instance variables, followed by package instance variables, followed by private instance variables.

8.

Best Practices (JSP/ Servlet/ EJB inclusive)


!" It is recommended to visit the design once again and resort to refactoring of a class in case the lines of code in a class goes beyond 1500 lines (inclusive of comments). Rationale: It is very likely that you have grouped logically separable functionalities together. !" Justify declaration of protected and package variables/methods Rationale: Protected variables/methods should be used only after making sure that sub-classing and overriding will not be in any manner able to compromise the robustness of other methods of the parent class that might depend on these methods. (If you use tools like JTest for static code analysis, it will point out such possible places to you and identify them as code-defects by default) !" !" Avoid accessing class variables using instances Do not use deprecated API

!" Use StringBuffer rather than a String wherever a lot of modifications are required (specially in a loop) Rationale: String being an immutable object will lead to a lot of object creations. !" Change an object value to null when that particular instance is not required any more

SG620:JAVA Coding Standards Version 1.5

Confidential

Page 11 of 17

!" Always use try-catch-finally, wherever a usage of releasable resources is involved. Release the resources in finally to ensure that even in exceptional situations resources will not be held up by the broken piece of code. !" Use application logging (use standards tools like Log4j or JSDK1.4 standard logging mechanism), and log all milestones (information, error, and debug related). Use lighter API to query about logging level wherever a costly object creation for logging is required. !" Avoid throwing and catching Base classes like Exception, rather throw and catch specific exceptions. !" Use Interface based interactions between objects wherever possible, like use Collection rather than specific Vector for return in a method. This way the seam would still be valid if one of the objects changes that implementation of that interface (this will help in making the classes as independent as possible from each other) !" Declare variables final, if you do not intend to modify their values apart from the declaration and definition time. !" Reap the benefits of Object Orientation wherever possible. For example: common functionality should be encapsulated either in interfaces (and an implementation factory written for them) or in inheritable base classes, which can be directly inherited. !" Encapsulate database interactions in DAO (Data Access Objects) or Entity beans. !" Keep the code complexity low, for example: keeping track of more than 4 levels of nestings becomes difficult for a programmer. Sort to refactoring methods if such becomes the case. A common indicator (if you are using the 80 column restriction) is that the moment the code starts spilling over too much, the nesting has gone deep (and hence the complexity). !" Write automation test suites for unit testing (use of JUnit is recommended). Write test case along with the code rather than as an after exercise. !" It is recommended to override toString() method for ease in debugging !" It is also recommended to override equals() method appropriately in case the objects are expected to participate a lot in sorting etc. !" Appropriately evaluate the tradeoffs while using Stateful session beans. They can be heavy on performance. !" When sensible, consider writing a main for the principal class in each program file. The main should provide a simple unit test or demo. Rationale: Forms a basis for testing. Also provides usage examples. !" For self-standing application programs, the class with mail should be separate from those containing normal classes. Rationale: Hard-wiring an application program in one of its component class files hinders reuse
SG620:JAVA Coding Standards Version 1.5 Confidential Page 12 of 17

!" If you can conceive of someone else implementing a class's functionality differently, define an interface, not an abstract class. Generally, use abstract classes only when they are partially abstract; i.e., they implement some functionality that must be shared across all subclasses. Rationale: Interfaces are more flexible than abstract classes. They support multiple inheritance and can be used as mixins' in otherwise unrelated classes !" Consider whether any class should implement Cloneable and/or
Serializable.

Rationale: These are magic interfaces in Java, that automatically add possibly-needed functionality only if so requested. !" Declare a class as final only if it is a crucial class for the integrity of a package and other classes in the package depend on its implementation. !" Never declare instance variables as public. Rationale: The standard OO reasons. Making variables public gives up control over internal class structure. Also, methods cannot assume that variables have valid values !" Minimize reliance on implicit initializers for instance variables (such as the fact that reference variables are initialized to null). Rationale: Minimizes initialization errors. !" Minimize statics (except for static final constants). Rationale: Static variables act like globals in non-OO languages. They make methods more context-dependent, hide possible side effects, sometimes present synchronized access problems. and are the source of fragile, nonextensible constructions. Also, neither static variables nor methods are overridable in any useful sense in subclasses. !" Generally prefer long to int, and double to float. But use int for compatibility with standard Java constructs and classes (for the major example, array indexing, and all of the things this implies, for example about maximum sizes of arrays, etc). Rationale: Arithmetic overflow and underflow can be 4 billion times less likely with longs than int; similarly, fewer precision problems occur with doubles than float. On the other hand, because of limitations in Java atomicity guarantees, use of longs and doubles must be synchronized in cases where use of int and float sometimes would not be. !" Use final and/or comment conventions to indicate whether instance variables that never have their values changed after construction are intended to be constant (immutable) for the lifetime of the object (versus those that just so happen not to get assigned in a class, but could in a subclass). Rationale: Access to immutable instance variables generally does not require any synchronization control, but others generally do. !" Avoid unnecessary instance variable access and update methods. Write get/set-style methods only when they are intrinsic aspects of functionality.
Confidential Page 13 of 17

SG620:JAVA Coding Standards Version 1.5

Rationale: Most instance variables in most classes must maintain values that are dependent on those of other instance variables. Allowing them to be read or written in isolation makes it harder to ensure that consistent sets of values are always used. !" Minimize direct internal access to instance variables inside methods. Use access and update methods instead (or sometimes public ones if they exist anyway).
protected

Rationale: While inconvenient and sometimes overkill, this allows you to vary synchronization and notification policies associated with variable access and change in the class and/or its subclasses, which is otherwise a serious impediment to extensiblity in concurrent OO programming. (Note: The naming conventions for instance variables serve as an annoying reminder of such issues.) !" !" Avoid giving a variable the same name as one in a superclass. Prefer declaring arrays as Type[] rather than Type
arrayName[].

Rationale: This leads to hiding of the parent variable.


arrayName

Rationale: The second form is just for incorrigible C prgrammers. !" Ensure that non-private static have sensible values even if no instances are ever created. (Similarly ensure that static methods can be executed sensibly.) Use static intitializers (static { ... } ) if necessary. Rationale: You cannot assume that non-private statics will be accessed only after instances are constructed. !" Write methods that only do one thing. In particular, separate out methods that change object state from those that just relies upon it. For a classic example in a Stack, prefer having two methods Object top() and void removeTop() versus the single method Object pop() that does both. Rationale: This simplifies (sometimes, makes even possible) concurrency control and subclass-based extensions. !" Define return types as void unless they return results that are not (easily) accessible otherwise. (i.e., hardly ever write return this). Rationale: While convenient, the resulting method cascades (a.meth1().meth2().meth3()) can be the sources of synchronization problems and other failed expectations about the states of target objects. !" Avoid overloading methods on argument type. (Overriding on arity is OK, as in having a one-argument version versus a two-argument version). If you need to specialize behavior according to the class of an argument, consider instead choosing a general type for the nominal argument type (often Object) and using conditionals checking instanceof. Alternatives include techniques such as double-dispatching, or often best, reformulating methods (and/or those of their arguments) to remove dependence on exact argument type. Rationale: Java method resolution is static; based on the listed types, not the actual types of argument. This is compounded in the case of non-Object types
SG620:JAVA Coding Standards Version 1.5 Confidential Page 14 of 17

with coercion charts. In both cases, most programmers have not committed the matching rules to memory. The results can be counterintuitive; thus the source of subtle errors. For example, try to predict the output of this. Then compile and run.
class Classifier { String identify (Object x) { return "object"; } String identify (Integer x) {return "integer"; } } class Relay { String relay(Object obj) { return (new Classifier()).identify(obj); } } public class App { public static void main(String[] args) { Relay relayer = new Relay(); Integer i = new Integer(17); System.out.println(relayer.relay(i)); } }

JSP/Servlets: !" It is suggested to break JSPs per a bread-crumb model, where you break the view into header, footer, navigation, and content areas. Rationale: This will help organize content better, as well as enforcing constraints like security constraints in a more centralized manner. !" It is suggested to follow Model II (MVC) based design for you application web front. #" So use JSPs only as views (aim at 0 java code in JSPs). Populate dynamic data in JSPs using Form/Helper beans only. #" Do not code business process driving directly in Servlet, rather use dependent Action classes, which capture the business process delegation, and have an Action per business functionality to avoid complexity. #" Make the navigation configurable, preferably thru XML based configuration files, so that you can later plug and play navigation paths. #" Apache Jakarta Struts framework provides for all of these. It is recommended to use it. !" Hide special scripting or constraint enforcement in tags. !" Create Abstract classes from which you derive the implementation of your Action and Helper/Form bean classes. Rationale: This way you wont have to duplicate the effort to introduce a generic logging / error handling / validation / monitoring mechanism in all Helper/Form bean and Action classes !" As far as possible do not bank on passing parameters in the URL to Servlet/JSP. This may give a semantic clue to a hacker to get the data out of the portal bypassing normal portal security. This would specially be true when security is being applied at the level of display of options themselves rather than at the submission level also. By looking at a URL and the parameters to submit, the authentic users of the portal specially, may be able to gain unauthorised access. Hence the URL submits should only have reference to the user session id and the indexes, which in that user session point to corresponding semantic entitiy.
SG620:JAVA Coding Standards Version 1.5 Confidential Page 15 of 17

!" Do not use hidden parameters. A smart hacker may get a lot of details by doing a view page source on the browser client. Such things should also be stored in the session. !" Session id should have a component of randomness to it. It should not be a normal sequence number as then a smart internal hacker can guess the sequence and try unauthorised access.
!"

For JSPs it is recommended to use a nesting level of 2 spaces (rather than 4, as recommended for general Java)

9.

AMENDMENT HISTORY
Version 1.5 Date 29th June 2005 9th July 04 14th Mar 03 21st Aug 02 11th Aug 00 23rd Jun 97 Additions/Modifications Reformatting minor changes Prepared/ Revised by Namita Sehgal Namita Sehgal Kiran Bellary Kiran Bellary Rahul Bhattacharya Ashish Gupta

1.4 1.3 1.2 1.1 1.0

Reformatting minor changes Copyright messages not to be included in Header and Footer Section7 and 8. Java GUI and Server side changes. Section 7.1-7.4, and 9-15 added First Release

PEROT SYSTEMS and the PEROTSYSTEMS logo are trademarks of Perot Systems and may be registered or unregistered in the United States, the EU, and other countries. All other trademarks are the property of their respective owners. SG620:JAVA Coding Standards Version 1.5

Confidential

Page 16 of 17

SG620:JAVA Coding Standards Version 1.5

Confidential

Page 17 of 17

You might also like