* Opening and closing braces must be formatted using one of the following two methods:
**Method 1:** On a line by themselves at the same level of indentation as the initiating keyword.
-
```
-
Java
+
```Java
if ( byteBuf == null )
{
@@ 44,22 43,22 @@
}
```
**Exception**: the closing brace of the do-while statement.
-
```
-
Java
-
if ( byteBuf == null ) {
-
byteBuf = new ByteBuffer( BUFFER_SIZE );
-
}
+
```Java
+
do
+
{
+
charNumber++;
+
ch = clientName.getChar( charNumber );
+
+
} while ( ch != '\0' );
```
**Method 2:** Opening brace on the same line as the initiating keyword and closing brace on a line by itself at the same level of indentation as the initiating keyword.
-
```
-
Java
+
```Java
if ( byteBuf == null ) {
byteBuf = new ByteBuffer( BUFFER_SIZE );
}
```
**Exception**: the closing brace of the do-while and try statements.
-
```
-
Java
+
```Java
do {
charNumber++;
ch = clientName.getChar( charNumber );
@@ 78,13 77,11 @@
* Always write the left parenthesis directly after a function name (no intervening space).
* When a statement spans more than one line, break the statement in a way that each line is obviously syntactically incorrect, and indent the continued line or lines in a way that makes the continuation more visible.
* All classes and public methods must be preceded by a javadoc comment.
* Class javadoc comments must contain a meaningful description of the class and an @author tag for each person who has worked on any part of the class.
* Method javadoc comments must include a meaningful description of the method, @param tags for each parameter, and, if applicable, @return and @exception tags.
-
```
-
Java
+
```Java
/**
* Adds a graphic object to the bounding box. If any of the object's
* dimensions fall outside the box, the box's dimensions will grow to
@@ 156,22 151,19 @@
### **2.5 Naming Conventions**
#### **2.5.1 Rules:**
* Whenever mixed-case names are made up of more than one word, the first letter of each word following the first should be uppercase.
-
```
-
Java
+
```Java
closeFile();
Button okButton;
int accountTotal;
int average;
```
* Whenever all-uppercase names are made up of more than one word, each word should be separated with an underscore.
-
```
-
java
+
```java
final int MAX_RANGE = 100;
final String BUTTON_NAME = "a button name";
```
* Methods should be named so that they describe what the method does, starting with an active verb whenever possible.
-
```
-
Java
+
```Java
protected void hideComponent() { /* ... */ }
public int getAverage() { /* ... */ }
public void refreshScreen() { /* ... */ }
@@ 180,16 172,14 @@
* Modifier methods should begin with "set".
* Components should end with the type of the component.
* This is to make the use of the variable a bit more obvious. For example `"ageTextField"` is unambiguous, while "age" may be mistaken for a numeric value.
-
```
-
java
+
```java
Button cancelButton = new Button();
List customerNameList;
BigGrid salesTrackingGrid;
```
* Class names should be a description of the class, and should be mixed case and begin with an uppercase letter.
* Interface names should be a description of the interface's services.
-
```
-
Java
+
```Java
interface Compressable { /* ... */ }
interface Singleton { /* ... */ }
```
@@ 200,8 190,7 @@
##### **2.5.2 Recommendations:**
* Avoid the overuse of "i", "j", and "k" as variable names.
* These variable names don't offer much in the way of providing readability. Compare:
-
```
-
Java
+
```Java
for ( int i = 0; i < totalMonthsDisplayed; i++ )
{
for ( j = 0; j < totalSales; j++ )
@@ 211,8 200,7 @@
}
```
... with ...
-
```
-
Java
+
```Java
for ( int row = 0; row < totalMonthsDisplayed; row++ )
{
for ( column = 0; column < totalSales; column++ )
@@ 228,16 216,14 @@
* Hiding data provides all the benefits of using abstract data types, and limits the places that data can be changed (and/or corrupted). Giving an object the ability to prevent access to its internal state also allows it to test itself whenever its state is queried or changed to ensure that the change is consistent with the object's internal state.
**Don't do this:**
-
```
-
Java
+
```Java
public class Foo
{
public int counter;
}
```
**Do this instead:**
-
```
-
Java
+
```Java
public class Foo
{
private int counter;
@@ 259,8 245,7 @@
#### **2.6.2 Recommendations:**
* When a private data member has a public or protected access method, those methods should be used internally by the class as much as possible to provide consistency.
**For example, given the following class:**
-
```
-
Java
+
```Java
class Dimensions
{
public void setDimensions( int width, int height ) { /* ... */ }
@@ 274,14 259,12 @@
}
```
The code in the body of `Dimension.getArea()` could look like this:
-
```
-
Java
+
```Java
area = width * height;
```
This would work, but will need to be modified if the height or width were changed from a data member to a calculated value. The following code would require no such modification:
-
```
-
Java
+
```Java
area = getWidth() * getHeight();
```
@@ 303,15 286,13 @@
##### **2.8.1 Rules:**
* Avoid the use of numeric values in code, use symbolic values instead.
**For example:**
-
```
-
java
+
```java
colWidth = strWidth + 10 + ( level * 3 );
// ...
cellWidth = cellStrWidth + 10;
```
For the unfortunate programmer who has to maintain (or fix) the above code, there's no indication of what "10" or "3" represents, or whether both "10"s represent the same thing. And if the code maintainer finally figures out that "10" probably represents margin widths, and changes it to something smaller, there's an excellent chance that an instance will be missed, and more time will be wasted tracking down a difficult-to-find bug. Something like the following code should be written in the first place:
-
```
-
Java
+
```Java
final int COL_INDENT_WIDTH = 3; // amount to indent, per level
final int COL_LEFT_MARGIN = 5; // width of column left margin in pixels
final int COL_RIGHT_MARGIN = 5; // width of column right margin in pixels
@@ 326,13 307,11 @@
* Variables are to be declared with the smallest possible scope.
* Each variable is to be declared in a separate declaration statement, and have a commented description.
**Don't do this:**
-
```
-
Java
+
```Java
int moveAmount, selectedIndex;
```
**Do this:**
-
```
-
Java
+
```Java
int moveAmount; // number of items to move
int selectedIndex; // currently selected item
```
@@ 340,8 319,7 @@
###### **2.9.1 Rules:**
* The code which follows a case label must always be terminated by a break statement.
* The switch statement must always contain a default branch, which handles unexpected cases.
-
```
-
Java
+
```Java
switch (tag)
{
case A:
@@ 361,8 339,7 @@
* A switch statement must always contain a default branch which handles unexpected cases.
* All flow control statements (if, else, while, for and do) must have opening and closing braces, even if the block contains no statements.
Empty loops can be deceiving. In the example below, it's easy to mistakenly think that the last line is contained in the loop:
...will likely compile the same as the more readable:
-
```
-
Java
+
```Java
if ( rowNumber == 0 )
{
selectTable();
@@ 400,8 374,7 @@
}
```
**Exception**: cases in which a ternary statement simplifies an assignment.
-
```
-
Java
+
```Java
double scale = ( isHalfScale() ? 0.5 : 1 );
// ...may be more readable than...
@@ 426,8 399,7 @@
* **Avoid the use of continue.**
`continue` tends to make loops harder to understand by concealing the structure of program execution. When tempted to use them, try to use an if...else.. statement instead.
Exception: a `continue` statement near the top of a loop can sometimes make the code more readable by avoiding a series of if...else... statements, or a complex loop control structure. For example:
-
```
-
Java
+
```Java
while ( row != null )
{
if ( row.getIsEmpty() )
@@ 441,8 413,7 @@
```
* **Avoid the use of break in anything but the switch statement.**
break tends to make loops harder to understand by concealing their exit conditions. Here's an example of break that confuses the structure of a loop:
-
```
-
Java
+
```Java
while ( true )
{
Rectangle areaRect = area.getRectArea();
@@ 461,8 432,7 @@
```
**Exception**: break can sometimes be used judiciously to avoid messy nested if...else statements in loops or a large number of boolean conditions in the control statement at the top:
-
```
-
Java
+
```Java
while ( ch != '\u0000' )
{
// if this is a metastring token, drop out of the loop
@@ 478,8 448,7 @@
The flow of control within a function is more difficult to understand when there are multiple exit points.
**Exception**: early returns can sometimes be used at the beginning of a function to avoid long if...else.. constructions. When used in this way, it's recommended that they are documented in a way that draws attention to them.
-
```
-
Java
+
```Java
boolean setName( Client client, String name )
{
int clientIndex = findClient( client );
@@ 494,20 463,29 @@
##### **2.10.1 Recommendations:**
* **Comment in a style that's easy to maintain.**
Example of a hard-to-maintain commenting style:
-
```
-
Java
+
```Java
//--------------------------------------//
// get the size of the buffer //
//--------------------------------------//
```
Example of easy-to-maintain commenting styles:
+
```Java
+
//------------------------------
+
// get the size of the buffer
+
//------------------------------
+
+
/*
+
* get the size of the buffer
+
* then allocate another buffer of the same size.
+
*/
+
```
* **Comment as you go.**
Don't code with the intention of going back later and putting comments in. Try to comment first and code around the comments.
* **Avoid non-data endline comments.**
Endline comments are difficult to maintain because they have to aligned properly, are difficult to edit, and there usually isn't enough space to comment effectively.
+
**Exceptions**: data declarations, and comments at the end of blocks. Example of these:
-
```
-
Java
+
```Java
int numberOfKeys; // number of virtual keystrokes
// ...
} // switch
@@ 515,8 493,7 @@
```
* **Don't duplicate the code in the comment.**
The following comments are redundant:
-
```
-
Java
+
```Java
// if the allocation flag is more than zero
if ( allocSize > 0 )
{
@@ 525,8 502,7 @@
}
```
This comment explains what's actually happening:
-
```
-
Java
+
```Java
// if a buffer was successfully allocated, record the size
if ( allocSize > 0 )
{
@@ 536,8 512,7 @@
#### **2.11 Exception-Handling**
##### **2.11.1 Rules:**
* **Where there is a clear separation between presentation classes and integration classes, the integration class should repackage checked exceptions to pass to the presentation class to preserve encapsulation.**
-
```
-
Java
+
```Java
public class UserDAOImpl implements UserDAO
{
findByUserId(String userId)
@@ 559,8 534,7 @@
* **Preserve the original stack trace information throughout the life of the Exception.**
If an exception is caught in an integration class, and an exception is to be re-thrown to the presentation class, the newly thrown exception must preserve the caught exception stack trace.
* **Exceptions should be logged once whenever they are caught except as outlined by rule 4 and dealt with where they are caught, exceptions should not be passed to generic exception handling methods.**
-
```
-
Java
+
```Java
public class UserDAOImpl implements UserDAO
{
findByUserId(String userId)
@@ 580,8 554,7 @@
}
```
* **Swallowed checked exceptions should be avoided, and where they cannot be avoided proper commenting should document why an empty catch block exists. The general exception java.lang.Exception should never be caught.**
* **A function should not contain split try catch blocks, where multiple checked exceptions are caught they should be handled in subsequent catch blocks or if necessary in nested try blocks.**
-
```
-
Java
+
```Java
try
{
User user = (User)getSqlMapClientTemplate().queryForObject(GET_USER, userId);
@@ 616,8 588,7 @@
* **Catch subclasses before base classes.**
If you catch the base class of an exception before trying to catch classes derived from it, the first catch block will catch all derived exceptions:
-
```
-
Java
+
```Java
try
{
doSomething();
@@ 647,8 618,7 @@
* **Always use try-with-resources for AutoCloseable resources.**
This ensures proper resource cleanup and prevents resource leaks.
-
```
-
Java
+
```Java
// Good
try (BufferedReader reader = new BufferedReader(new FileReader("file.txt"))) {
return reader.readLine();
@@ 664,8 634,7 @@
```
* **Close resources in the reverse order of their creation in finally blocks (when try-with-resources cannot be used).**
* **Avoid creating unnecessary objects in loops.**
-
```
-
Java
+
```Java
// Bad
for (int i = 0; i < 1000; i++) {
String status = "Processing " + i;
@@ 678,8 647,7 @@
}
```
* **Never ignore InterruptedException without re-interrupting the thread.**
-
```
-
Java
+
```Java
try {
Thread.sleep(1000);
} catch (InterruptedException e) {
@@ 689,8 657,7 @@
```
##### **2.13.2 Recommendations:**
* **Use StringBuilder or StringBuffer for string concatenation in loops.**
-
```
-
Java
+
```Java
// Bad
String result = "";
for (String item : items) {
@@ 707,8 674,7 @@
* **Consider using object pooling only for expensive-to-create objects (e.g., database connections, thread pools).**
* **Avoid using finalizers. Use try-with-resources or explicit cleanup methods instead.**
* **Be aware of autoboxing/unboxing costs in performance-critical code.**
-
```
-
Java
+
```Java
// Bad - autoboxing in loop
Integer sum = 0;
for (int i = 0; i < 1000000; i++) {
@@ 722,8 688,7 @@
}
```
* **Use lazy initialization for expensive objects only when necessary.**
-
```
-
Java
+
```Java
private volatile ExpensiveObject instance;
public ExpensiveObject getInstance() {
@@ 742,8 707,7 @@
* **Always use the highest-level concurrency utilities available** (Executor framework, concurrent collections) rather than wait(), notify(), and synchronized blocks when possible.
* **Document thread-safety guarantees for all classes.**
Use annotations like` @ThreadSafe`, `@NotThreadSafe`, or `@Immutable` in javadoc.
-
```
-
Java
+
```Java
/**
* This class is thread-safe. All methods can be called concurrently.
* @ThreadSafe
@@ 754,16 718,14 @@
```
* **Never expose mutable internal state without proper synchronization.**
* **Always use the volatile keyword for flags that are set by one thread and read by others.**