Java Code Convention Rules

Java Code Convention Rules

Rules available in this category:

Avoid_subclassing_java_lang_Thread
Always_declare_a_class_having_only_private_constructors_as_final
Replace_enumeration_with_iterator
Combine_if_statements_using_boolean_short_circuit_operator
Avoid_using_fully_qualified_type_names
Avoid_static_imports
Avoid_using_the_negation_operator_more_than_three_times
Avoid_negative_logic_in_if_else
Always_place_class_or_interface_having_same_name_as_the_file_first
Always_cast_null_argument_for_varargs
Avoid_declaring_arrays_using_C-style_syntax
Place_finalize_method_between_public_and_protected_methods
Avoid_using_constant_interface_pattern
Always_define_constants_in_an_interface
Avoid_declaring_multiple_variables_of_different_types_in_same_statement
Avoid_declaring_multiple_variables_in_same_statement
Declare_imports_in_alphabetical_order
Avoid_confusing_if
Declare_class_final
Use_local_variable_instead_of_field
Do_not_declare_unnecessary_constructor
Do_not_call_next_in_hasNext
Avoid_subclassing_java_lang_Thread
Avoid_duplicate_string_literals
Avoid_string_literals_except_in_constant_declarations
Questionable_constant_field_name
Avoid_call_to_deprecated_methods_of_thread
Always_override_equals
Avoid_continue_statements
Specify_locale_for_SimpleDateFormat
Avoid_throw_in_finally
Do_not_hide_class_fields_with_local_variables
Do_not_hide_catch_blocks
Avoid_catching_NullPointerException
Define_default_public_constructor_for_Externalizable_class
Missing_constructor
Avoid_break_with_label
Use_all_three_parts_of_for
Avoid_empty_zip_file_entry
Avoid_empty_jar_file_entry
Use_break_for_each_case
Avoid_using_array_initializers
Use_static_fields_methods_with_class
Check_instanceOf_in_equals
Check_for_equality_using_getClass
Avoid_empty_block_in_case
Define_constructors_before_methods
Alway_call_super_clone
Clone_method_not_implementing_Cloneable
Cloneable_class_not_implementing_clone_method
Always_comment_main_method
Declare_package_with_intial
Avoid_unqualified_access_to_fields
Do_not_overload_finalize
Return_empty_Collection
Avoid_returning_null_instead_of_Enumeration
Avoid_returning_null_instead_of_Iterator
Avoid_subclassing_RuntimeException
Avoid_duplicate_import_statements
Avoid_numeric_literals
Reduce_scope_of_local_variable
Use_similar_import_style
Avoid_using_do_while_loops
Always_use_braces_with_if_or_else
Avoid_hardcoded_absolute_pathname
Avoid_changing_method_arguments
Method_next_should_throw_NoSuchElementException
Avoid_using_increment_or_decrement_operators_in_nested_expressions
Define_package
Always_place_main_method_last
Avoid_Storing_Array_Directly
Avoid_trailing_return_in_methods_not_returning_values
Declare_logger_static_final
Declare_jakarta_logger_private_static_final
Avoid_more_than_one_logger
Avoid_more_than_one_class_per_file
Organize_methods_by_name
Avoid_unnecessary_final_method
Avoid_Unnecessary_IfElse_Or_Ternary
Do_not_use_non_final_static_fields_during_initialization
Space_after_typecast
Use_chained_constructors
Avoid_return_in_finally
Avoid_declaring_constructors_public_for_non_public_classes
Provide_default_case_with_switch
Avoid_star_import
Avoid_ambigious_method_invocation_from_inner_class
Redeclare_class_as_interface_with_only_abstract_methods_and_static_final_fields
Use_for_loops_instead_of_while_loops
Use_while_loop_instead_of_for_loop
Declare_finalize_method_protected
Avoid_subclassing_Error_or_Throwable
Do_not_hide_class_fields_with_method_parameters
Do_not_use_deprecated_APIs
Use_StringTokenizer_for_string_parsing
Declare_for_loops_with_increment_statement
Always_keep_default_as_last_case_in_switch_statement
Avoid_continue_with_label
Do_not_use_public_static_final_array_fields
Avoid_final_modifier_for_Collection
Define_serialVersionUID
Avoid_throwing_NullPointerException
Use_main_only_as_entry_point_method
Use_if_instead_of_switch
Avoid_transient_for_non_serializable_classes
Provide_subclasses_of_Thread_a_run_method
Always_place_constants_on_one_side
Avoid_nested_assignments
Return_zero_length_array
Do_not_call_constructor_in_clone_method
Avoid_nested_ternary_expressions
Avoid_unnecessary_modifiers
Put_Declaration_at_begining_of_Block
Avoid_unnecessary_else
Do_not_use_JDBC_in_bean_class
Declare_static_class_constructor_private
Avoid_generic_exception_catching
Do_not_call_wait_or_notify_from_unsynchronized_method
Always_use_braces_with_loop
Avoid_too_many_nested_blocks
Throw_subclass_of_exception
Avoid_throwing_java_lang_Error
Avoid_throwing_java_lang_Throwable
Express_long_integer_constants_using_L_instead_of_l
Make_bean_class_serializable
Initialize_all_static_fields_explicitly
Always_override_equals_alongwith_hashCode
Avoid_array_declarators_after_variable_name
Avoid_using_lables_in_switch
Avoid_long_method_chain
Do_not_use_JDBC_in_servlet_class
Catch_exception_derived_from_exception
Avoid_methods_with_same_name_as_classname
Always_declare_serialVersionUID_static_final_long
Always_override_hashCode_alongwith_equals
Always_override_toString_method
Avoid_more_than_one_return
Avoid_creating_local_variable_for_return
Declare_for_loops_with_condition_statement
Avoid_unnecessary_comparison_with_null
Avoid_empty_initializer_blocks
Avoid_Non_Static_Initializer_Blocks
Enforce_listener_method_signature
Initialize_All_Local_Variables_At_Declaration
Avoid_abstract_method_call_in_abstract_class_constructor
Always_use_notifyAll
Do_not_change_for_loop_control_variable
Avoid_importing_java_lang
Avoid_assignment_to_non_final_static_in_instance_method
Avoid_null_argument_in_equals

Rule 1: Avoid_assignment_in_if

Severity: Low
Rule: Avoid assignment within the if conditions
Reason: Avoid assignment within the if conditions

Usage Example:

package com.rule;

class Avoid_assignment_in_if_violation
{

public void method()
{
    boolean b;
    if(b = true)    // VIOLATION
    {
        //...
        b = false;
    }
}

}

Should be written as:

package com.rule;
class Avoid_assignment_in_if_correction
{

public void method()
{
    boolean b = true;

    if(b)       // CORRECTION
    {
        //...
        b = false;
    }
}

}

Reference: http://java.sun.com/docs/codeconv/html/CodeConventions.doc9.html
Rule 2: Always_declare_a_class_having_only_private_constructors_as_final

Severity: Low
Rule: If a class has only private constructors but is not declared as final, then some class could try to extend it.
Reason: If a class has only private constructors but is not declared as final, then some class could try to extend it.

Usage Example:

public class Test // VIOLATION
{
private Test() {}
}

Should be written as:

public final class Test // FIXED
{
private Test() {}
}

Reference: Not available.
Rule 3: Replace_enumeration_with_iterator

Severity: Medium
Rule: Iterators allow the caller to remove elements from the underlying collection during the iteration with well-defined semantics.
Reason: Iterators allow the caller to remove elements from the underlying collection during the iteration with well-defined semantics.

Usage Example:

import java.util.Enumeration;

public class MyEnum implements Enumeration // VIOLATION
{

public boolean hasMoreElements()
{
    // ...
    return true;
}

public Object nextElement()
{
    // ...
    return null;
}

}

Should be written as:

import java.util.Iterator;

public class MyEnum implements Iterator // FIXED
{

public boolean hasNext()
{
    //...
    return true;
}

public Object next()
{
    //...
    return null;
}

public void remove()
{
    //...
}

}

Reference: http://java.sun.com/j2se/1.4.2/docs/api/java/util/Iterator.html
Rule 4: Combine_if_statements_using_boolean_short_circuit_operator

Severity: Low
Rule: Combining the if-statements improves code readibility.
Reason: Combining the if-statements improves code readibility.

Usage Example:

public class Test
{

public void fubar(boolean x, boolean y)
{
    if ( x )
    {
        if ( y ) // VIOLATION
        {
            //...
        }           
    }
}

}

Should be written as:

public class Test
{

public void fubar(boolean x, boolean y)
{
    if ( x && y )
    {
        //...
    }
}

}

Reference: Not Available.
Rule 5: Avoid_using_fully_qualified_type_names

Severity: Low
Rule: Using simple type names instead of the fully qualified names improves code readibility.
Reason: Using simple type names instead of the fully qualified names improves code readibility.

Usage Example:

public class Test
{
public void method()
{
java.util.Date date = new java.util.Date(System.currentTimeMillis()); // 2 VIOLATIONS
}
}

Should be written as:

import java.util.Date;

public class Test
{
public void method()
{
Date date = new Date(System.currentTimeMillis()); // FIXED
}
}

Reference: Not available.
Rule 6: Avoid_static_imports

Severity: Low
Rule: Improper usage of static imports can make code difficult to read.
Reason: Improper usage of static imports can make code difficult to read.

Usage Example:

import static java.lang.Math.PI; //VIOLATION

public class Test
{
public double calculate(double radius)
{
double area= PI*Math.pow(radius, 2);
return area;
}
}

Should be written as:

public class Test
{
public double calculate(double radius)
{
double area= Math.PI*Math.pow(radius, 2); //FIXED
return area;
}
}

Reference: Not available.
Rule 7: Avoid_using_the_negation_operator_more_than_three_times

Severity: Low
Rule: This rule violates on any method that uses the negation operator more than three times.
Reason: This rule violates on any method that uses the negation operator more than three times.

Usage Example:

public class Test
{

public boolean method (boolean a, boolean b) // VIOLATION 
{  
    if (!a)
    {
        return (!a && !b);
    }
    else
    {
        return !b;
    }

}

}

Should be written as:

public class Test
{

public boolean method (boolean a, boolean b)  // FIXED
{
    if (a)
    {
        return !b;
    }
    else
    {
        return (! (a || b) );
    }

}

}

Reference: Not available.
Rule 8: Avoid_negative_logic_in_if_else

Severity: Low
Rule: In order to improve code readability.
Reason: In order to improve code readability.

Usage Example:

public class Test
{

public int specialAdd(int i, int j) 
{
    if (i!= j) //VIOLATION
    {
     return i+ j;
    }
    else
    {
     return i;
    }
}

}

Should be written as:

public class Test
{

public int specialAdd(int i, int j) 
{
    if (i== j) //FIXED
    {
     return i;
    }
    else 
    {
     return i+ j;
    }
}

}

Reference: Not available.
Rule 9: Always_place_class_or_interface_having_same_name_as_the_file_first

Severity: Low
Rule: It is a coding convention to make the first class in the file be the class with the same name as the file.
Reason: It is a coding convention to make the first class in the file be the class with the same name as the file.

Usage Example:

//with file name MyClass.java

class ClassOne
{

//...

}

public class MyClass // VIOLATION
{

//...

}

Should be written as:

//with file name MyClass.java

public class MyClass // FIXED
{

//...

}

class ClassOne
{

//...

}

Reference: Not available.
Rule 10: Always_cast_null_argument_for_varargs

Severity: Medium
Rule: The compiler can optionally flag suspicious varargs method invocations.
Reason: The compiler can optionally flag suspicious varargs method invocations.

Usage Example:

public class Test
{

void foo(Test... args)
{

}

void bar()
{
    foo(null); // VIOLATION 
}

}

Should be written as:

public class Test
{

void foo(Test... args)
{

}

void bar()
{
    foo((Test[])null); // CORRECTION
}

}

Reference: No references available.
Rule 11: Avoid_declaring_arrays_using_C-style_syntax

Severity: Low
Rule: Could cause confusion since its not the coding convention followed by Java programmers.
Reason: Could cause confusion since its not the coding convention followed by Java programmers.

Usage Example:

public class Test
{

public static void main ( String args[] ) // VIOLATION
{
    //....
}

}

Should be written as:

public class Test
{

public static void main ( String[] args ) // CORRECTION
{
    //...
}

}

Reference: No references available.
Rule 12: Place_finalize_method_between_public_and_protected_methods

Severity: Low
Rule: Placing finalize between public and protected methods make the code easier to read.
Reason: Placing finalize between public and protected methods make the code easier to read.

Usage Example:

public class MyClass
{

public void method1 () {}
protected void method2 () {}
protected void finalize () {} // VIOLATION

}

Should be written as:

public class MyClass
{

public void method () {}
protected void finalize () {} // CORRECTION
protected void method2 () {}

}

Reference: No references available.
Rule 13: Avoid_using_constant_interface_pattern

Severity: Medium
Rule: Implementing a constant interface causes this implementation detail to leak into the class's exported API.
Reason: Implementing a constant interface causes this implementation detail to leak into the class's exported API.

Usage Example:

public interface PhysicalConstants // VIOLATION
{

// Avogadro's number (1/mol)
static final double AVOGADROS_NUMBER = 6.02214199e23;

// Boltzmann constant (J/K)
static final double BOLTZMANN_CONSTANT = 1.3806503e-23;

// Mass of the electron (kg)
static final double ELECTRON_MASS = 9.10938188e-31;

}

Should be written as:

// Constant utility class
public class PhysicalConstants // CORRECTION
{

private PhysicalConstants() { } // Prevents instantiation
public static final double AVOGADROS_NUMBER = 6.02214199e23;
public static final double BOLTZMANN_CONSTANT = 1.3806503e-23;
public static final double ELECTRON_MASS = 9.10938188e-31;

}

Reference: Joshua Bloch: “Effective Java - Programming Language Guide”.
Addison Wesley, 2001, pp 69
Rule 14: Always_define_constants_in_an_interface

Severity: Medium
Rule: It is preferrable to logically group all constants in an interface.
Reason: It is preferrable to logically group all constants in an interface.

Usage Example:

public class MyClass
{

static final int MAX = 100;  // VIOLATION

 public int getMax () 
{
 return MAX;
}

}

Should be written as:

public class MyClass
{

public int getMax () 
{
  return Constants.MAX;
}

}

interface Constants
{
int MAX = 1000;
}

Reference: No references available.
Rule 15: Avoid_declaring_multiple_variables_of_different_types_in_same_statement

Severity: Low
Rule: Avoid declaring multiple variables of different types in a single declaration statement
Reason: Avoid declaring multiple variables of different types in a single declaration statement

Usage Example:

public class SinglePerLine
{

private int index, index1[]; // VIOLATION

public void method () 
{

int a, b[]; // VIOLATION
int c;
int d;

}

}

Should be written as:

public class SinglePerLine
{

private int index;  // CORRECTION
private int index1[]; // CORRECTION

public void method () 
{

int a; // CORRECTION
int b[]; // CORRECTION
int c;
int d;

}

}

Reference: http://java.sun.com/docs/codeconv/html/CodeConventions.doc5.html#2992
Rule 16: Avoid_declaring_multiple_variables_in_same_statement

Severity: Low
Rule: Avoid declaring multiple variables in a single declaration statement.
Reason: Avoid declaring multiple variables in a single declaration statement.

Usage Example:

public class Test
{

String s1, s2; // VIOLATION;

public Test() {
s1 = “hello”;
s2 = “world”;
}

public boolean method() {
int i = 0, j = 0; // VIOLATION
return (i == j);
}

public String toString() {
return s1 + " " + s2;
}

}

Should be written as:

public class Test
{

String s1;
String s2; // CORRECTION

public Test() {
s1 = “hello”;
s2 = “world”;
}

public boolean method() {
int i = 0;

  int j = 0;  // CORRECTION

return (i == j);
}

public String toString() {
return s1 + " " + s2;
}

}

Reference: http://java.sun.com/docs/codeconv/html/CodeConventions.doc5.html#2992
Rule 17: Declare_imports_in_alphabetical_order

Severity: Low
Rule: It is more presentable and less confusing if imports are declared in an alphabetical order.
Reason: It is more presentable and less confusing if imports are declared in an alphabetical order.

Usage Example:

import java.util.Vector;
import java.util.Stack; // VIOLATION

public class MyClass
{

}

Should be written as:

import java.util.Stack;
import java.util.Vector; // CORRECTION

public class MyClass
{

}

Reference: No references available.
Rule 18: Avoid_confusing_if

Severity: Low
Rule: Avoid confusing if conditions.
Reason: Avoid confusing if conditions.

Usage Example:

package com.rule;

public class Avoid_confusing_if_violation
{

public void method()
{
    int x = getValue();

    if(x != 10)         // Violation.
    {
        processOne();
    }
    else
    {
        processTwo();
    }
}

}

Should be written as:

package com.rule;

public class Avoid_confusing_if_correction
{

    int x = getValue();

    if(x == 10)     //Correction.
    {
        processTwo();
    }
    else    
    {
        processOne();
    }

}

Reference: Reference not available.
Rule 19: Declare_class_final

Severity: Low
Rule: Declare class as final class.
Reason: Declare class as final class.

Usage Example:

package com.rule;

public class Declare_class_final_violation // Violation.
{

int a;

private Declare_class_final()
{
    a = 0;
}
private Declare_class_final(int a)
{
    this.a = a;
}   

}

Should be written as:

package com.rule;

final public class Declare_class_final_correction //Correction
{

int a;

private Declare_class_final()
{
    a = 0;
}
private Declare_class_final(int a)
{
    this.a = a;
}

}

Reference: Reference not available.
Rule 20: Use_local_variable_instead_of_field

Severity: Low
Rule: Use local variable instead of declaring field.
Reason: Use local variable instead of declaring field.

Usage Example:

package com.rule;

public class Use_local_variable_instead_of_field_violation
{

int field1;
int field2;     // Violation.

public void method(int a)
{
    field1 = a + 10 ;
}

public void method1(int a)
{
    field1 = a + 20 ;
    field2 = a + 30 ;
}   

}

Should be written as:

package com.rule;

public class Use_local_variable_instead_of_field_correction
{

int field1;

public void method(int a)
{
    field1 = a + 10 ;
}

public void method1(int a)
{
    int field2;     //Correction.

    field1 = a + 20 ;
    field2 = a + 30 ;
}   

}

Reference: Reference not available.
Rule 21: Do_not_declare_unnecessary_constructor

Severity: Low
Rule: Avoid declaring unnecessary constructor.
Reason: Avoid declaring unnecessary constructor.

Usage Example:

package com.rule;

public class Do_not_declare_unnecessary_constructor_violation // Violation.
{

public Do_not_declare_unnecessary_constructor_violation()
{

}

}

Should be written as:

Reference: Reference not available.
Rule 22: Do_not_call_next_in_hasNext

Severity: Medium
Rule: Do not call next() in hasNext() method.
Reason: Do not call next() in hasNext() method.

Usage Example:

package com.rule;

class Do_not_call_next_in_hasNext implements Iterator
{

public void method()
{
    Iteratortest test = new Iteratortest();
    List list = new ArrayList();        
    list.add("AppPerfect");
 list.add("India");
}
public boolean hasNext()
{
    boolean b = hasNext();
    if (b)
    {
        currVal = next();       // Violation
    }
    return b;
}
public Object next()
{
    return next();
}
public void remove()
{
    remove();
}

}

Should be written as:

Reference: Reference Not Available.
Rule 23: Avoid_subclassing_java_lang_Thread

Severity: Medium
Rule: Avoid extending java.lang.Thread.
Reason: Avoid extending java.lang.Thread.

Usage Example:

public class Test
{

public static void main( String[] args ) 
{
    (new DontExtendThread ()).start();
}

public static class DontExtendThread extends Thread // VIOLATION
{
    public void run() 
    {
        System.out.println( "run method"  );
    }
}

}

Should be written as:

public class Test
{

public static void main( String[] args ) 
{
    new Thread(new DontExtendThread ()).start();
}

public static class DontExtendThread implements Runnable // CORRECTION
{
    public void run() 
    {
        System.out.println( "run method"  );
    }
}

}

Reference: No references available.
Rule 24: Avoid_duplicate_string_literals

Severity: Medium
Rule: Avoid duplicate string literals.
Reason: Avoid duplicate string literals.

Usage Example:

package com.rule;

public class Avoid_duplicate_string_literals
{

public void foo(Vector v, String s)
{
    if (s.equals("AppPerfect"))
    {
        //do something
    }
    int iSize = v.size();
    for (int i = 0; i < iSize; i++)
    {
        if (((String)v.get(i)).equals("AppPerfect"))
        {
        }
    }       
}

}

Should be written as:

package com.rule;

public class Avoid_duplicate_string_literals
{

private static final String APPPERFECT = "AppPerfect";
public void foo(Vector v, String s)
{
    if (s.equals(Avoid_duplicate_string_literals.APPPERFECT))
    {
        //do something
    }
    int iSize = v.size();
    for (int i = 0; i < iSize; i++)
    {
        if (((String)v.get(i)).equals(Avoid_duplicate_string_literals.APPPERFECT))
        {
        }
    }       
}

}

Reference: Reference not available.
Rule 25: Avoid_string_literals_except_in_constant_declarations

Severity: Medium
Rule: Hard-coded constant strings in the code are error-prone and hard to maintain.
Reason: Hard-coded constant strings in the code are error-prone and hard to maintain.

Usage Example:

public class Test
{
public static void main(String args[])
{
System.out.println(“Hello World!“); //VIOLATION
}
}

Should be written as:

public class Test
{
static final String WELCOME_MESSAGE= “Hello World!“;

public static void main(String args[])
{
System.out.println(WELCOME_MESSAGE); //FIXED
}
}

Reference: No references available.
Rule 26: Questionable_constant_field_name

Severity: Medium
Rule: Avoid questionable use of constant field name.
Reason: Avoid questionable use of constant field name.

Usage Example:

package com.rule;

public class Questionable_constant_field_name_violation
{

public int NUMBER = 10;     // Violation.

public void method()
{

}

}

Should be written as:

package com.rule;

public class Suspicious_constant_field_name_correction
{

public int number = 10;     //Correction.

public void method()
{

}

}

Reference: Reference not available.
Rule 27: Avoid_call_to_deprecated_methods_of_thread

Severity: Medium
Rule: Do not call deprecated method Thread.stop(), Thread.suspend() and Thread.resume().
Reason: Do not call deprecated method Thread.stop(), Thread.suspend() and Thread.resume().

Usage Example:

package com.rule;

class Avoid_call_to_deprecated_methods_of_thread_violation extends Thread
{

public void run()
{
    doSomething();
    if (condition)
    {
        thread.suspend();   //Violation
    }
    doSomething();
}

}

Should be written as:

Do not call deprecated method of thread.

Reference: http://rangiroa.essi.fr/cours/systeme1/thread/tutorial/threadPrimitiveDeprecation.html
Rule 28: Always_override_equals

Severity: Low
Rule: Always override equals method in bean classes.
Reason: Always override equals method in bean classes.

Usage Example:

package com.rule;

public class Always_override_equals_violation_Bean // VIOLATION
{

}

Should be written as:

package com.rule;

public class Always_override_equals_correction_Bean
{

public boolean equals(Object obj) // CORRECTION
{
    return super.equals(obj);
}

}

Reference: No reference available.
Rule 29: Avoid_continue_statements

Severity: Low
Rule: Avoid using continue statements.
Reason: Avoid using continue statements.

Usage Example:

public class AvoidContinueStatements
{
public static void main(String[] args)
{
int[] nums= new int[10];
for (int i= 0; i< 10; i++)
{
System.out.println(“Enter a positive number: “);
int num= getNumFromInput();
if (num> 0)
{
nums[i]= num;
continue; // VIOLATION
}
System.out.println(“Invalid number”);
}
}
}

Should be written as:

public class AvoidContinueStatements
{
public static void main(String[] args)
{
int[] nums= new int[10];
for (int i= 0; i< 10; i++)
{
System.out.println(“Enter a positive number: “);
int num= getNumFromInput();
if (num> 0)
{
nums[i]= num;
// CORRECTOIN
}

    else
    {
         System.out.println("Invalid number");
    }

}
}
}

Reference: No references available.
Rule 30: Specify_locale_for_SimpleDateFormat

Severity: Medium
Rule: Specify locale for SimpleDateFormat.
Reason: Specify locale for SimpleDateFormat.

Usage Example:

package com.rule;

public class Specify_locale_for_SimpleDateFormat_violation
{

public void testEquals()
{
    final SimpleDateFormat sdfObj = new SimpleDateFormat("yyyy.MM.dd G 'at' HH:mm:ss z");           // Violation.
}

}

Should be written as:

package com.rule;

public class Specify_locale_for_SimpleDateFormat_correction
{

public void testEquals()
{
    final Locale locale = Locale.FRENCH;

    final SimpleDateFormat sn1 = new SimpleDateFormat("yyyy.MM.dd G 'at' HH:mm:ss z",locale);       //Correction.

}

}

Reference: Reference not available.
Rule 31: Avoid_throw_in_finally

Severity: Medium
Rule: Avoid throwing exceptions from finally block.
Reason: Avoid throwing exceptions from finally block.

Usage Example:

package com.rule;

import java.io.File;
import java.io.FileInputStream;
import java.io.IOException;

public class Avoid_throw_in_finally_violation
{

public void method(File f) throws CustomException
{
    FileInputStream fis = null;
    try
    {
        fis = new FileInputStream(f);
    }
    catch (Exception e)
    {
        // ignore
    }
    finally
    {
        if(fis!=null)
        {
            try
            {
                fis.close();
            }
            catch (IOException e)
            {
                throw new CustomException(e); // VIOLATION
            }
        }
    }
}

class CustomException extends Exception
{
    Exception origException;
    CustomException(Exception orig)
    {
        origException = orig;
    }
}

}

Should be written as:

package com.rule;

import java.io.File;
import java.io.FileInputStream;
import java.io.IOException;

public class Avoid_throw_in_finally_violation
{

public void method(File f) throws CustomException
{
    FileInputStream fis = null;
    try
    {
        fis = new FileInputStream(f);
    }
    catch (Exception e)
    {
        // ignore
    }
    finally
    {
        if(fis!=null)
        {
            try
            {
                fis.close();
            }
            catch (IOException e)
            {
                // log exception
            }
        }
    }
}

}

Reference: No reference available.
Rule 32: Do_not_hide_class_fields_with_local_variables

Severity: High
Rule: Avoid hiding class fields with local variables
Reason: Avoid hiding class fields with local variables

Usage Example:

package com.rule;

public class Do_not_hide_class_fields_with_local_variables_violation
{
    String data;
    int val;
        public void method(String data_loc)
        {
            int val;        //VOILATION
            this.data=data_loc;
        }
    }

Should be written as:

package com.rule;

public class Do_not_hide_class_fields_with_local_variables_violation
{
    String data;
    int val;
        public void method(String data_loc)
        {
            int val_loc; //CORRECTION
            this.data=data_loc;
        }
}

Reference: Reference Not Available.
Rule 33: Do_not_hide_catch_blocks

Severity: High
Rule: Do not hide catch blocks.
Reason: Do not hide catch blocks.

Usage Example:

public class Test
{

public void aMethod()
{
    try
    {
        throw new java.io.CharConversionException();
    }
    catch (java.io.CharConversionException e)
    {
    }
    catch (java.io.IOException e) // VIOLATION
    {
    }
}

}

Should be written as:

Reference: No references available.
Rule 34: Avoid_catching_NullPointerException

Severity: High
Rule: Avoid catching NullPointerException.
Reason: Avoid catching NullPointerException.

Usage Example:

package com.rule;

class Avoid_Catching_Null_Pointer_Exception
{

public void method()
{
    try
    {
        //some code here
    }
    catch (NullPointerException e) //Violation
    {
    }

}

}

Should be written as:

Reference: This rule has no references.
Rule 35: Define_default_public_constructor_for_Externalizable_class

Severity: Medium
Rule: The Externalizable class should have a public default constructor defined.
Reason: The Externalizable class should have a public default constructor defined.

Usage Example:

package com.rule;

import java.io.Externalizable;
import java.io.IOException;
import java.io.ObjectInput;
import java.io.ObjectOutput;

public class Define_default_public_constructor_for_Externalizable_class_violation implements Externalizable // VIOLATION
{

Define_default_public_constructor_for_Externalizable_class_violation() // non-public default constructor
{
}

public void writeExternal(ObjectOutput out) throws IOException
{
}

public void readExternal(ObjectInput in) throws IOException, ClassNotFoundException
{
}

}

Should be written as:

package com.rule;

import java.io.Externalizable;
import java.io.IOException;
import java.io.ObjectInput;
import java.io.ObjectOutput;

public class Define_default_public_constructor_for_Externalizable_class_correction implements Externalizable
{

public Define_default_public_constructor_for_Externalizable_class_correction() // CORRECTION
{
}

public void writeExternal(ObjectOutput out) throws IOException
{
}

public void readExternal(ObjectInput in) throws IOException, ClassNotFoundException
{
}

}

Reference: http://java.sun.com/j2se/1.4.2/docs/api/java/io/Externalizable.html
http://www.codeguru.com/java/tij/tij0116.shtml
Rule 36: Missing_constructor

Severity: Medium
Rule: Define constructor for non-abstract classes.
Reason: Define constructor for non-abstract classes.

Usage Example:

package com.rule;

public class Missing_constructor_violation // Violation.
{

}

Should be written as:

package com.rule;

public class Missing_constructor_correction
{

public Missing_constructor_correction()     //Correction.
{

}

}

Reference: Reference not available.
Rule 37: Avoid_break_with_label

Severity: Low
Rule: Avoid break with label.
Reason: Avoid break with label.

Usage Example:

package com.rule;
class AvoidBreakWithLabel_Violation
{

public void method(boolean flag)
{
    outer: while(flag)
    {
        inner: while(flag)
        {
            if(!flag)
            {
                break outer; // Violation
            }
            //...
        }
    }
}

}

Should be written as:

package com.rule;
class AvoidBreakWithLabel_Correction
{

public void method(boolean flag)
{
    while(flag)
    {
        if(subMethod(flag)) // Correction
        {
            //...
        }
    }
}

public boolean subMethod(boolean flag)
{
    while(flag)
    {
        if(!flag)
        {
            return false;
        }
    }
    return true;
}

}

Reference: Reference not available.
Rule 38: Use_all_three_parts_of_for

Severity: Low
Rule: Specify initialization, condition and increment while using for statement.
Reason: Specify initialization, condition and increment while using for statement.

Usage Example:

package com.rule;
public class Use_all_three_parts_of_for_violation
{

public void method()
{
    for (int i=0; i<10;) // VIOLATION
    {
        // Statements
        i++;
    }
}

}

Should be written as:

package com.rule;
public class Use_all_three_parts_of_for_correction
{

public void method()
{
    for (int i=0; i<10; i++) // CORRECTION
    {
        // Statements
    }
}

}

Reference: http://java.sun.com/docs/codeconv/CodeConventions.pdf
Rule 39: Avoid_empty_zip_file_entry

Severity: Medium
Rule: Avoid empty zip file entry.
Reason: Avoid empty zip file entry.

Usage Example:

package com.rule;

public class Avoid_empty_zip_file_entry_violation
{

public void testEquals()
{
    String outFilename = "outfile.zip";
    ZipOutputStream outZip = new ZipOutputStream(new FileOutputStream(outFilename));
    String filename="file1.txt"

    outZip.putNextEntry(new ZipEntry(filename));

    outZip.closeEntry();    //Violation.
}

}

Should be written as:

package com.rule;

public class Avoid_empty_zip_file_entry_correction
{

public void testEquals()
{
    String outFilename = "outfile.zip";
    ZipOutputStream outZip = new ZipOutputStream(new FileOutputStream(outFilename));

    String filename="file1.txt"
    outZip.putNextEntry(new ZipEntry(filename));

    int len = 0;
    while ((len = in.read(buf)) > 0)
    {
out.write(buf, 0, len);     //Correction.

}

    outZip.closeEntry();
}

}

Reference: Reference not available.
Rule 40: Avoid_empty_jar_file_entry

Severity: Medium
Rule: Avoid empty jar file entry.
Reason: Avoid empty jar file entry.

Usage Example:

package com.rule;

public class Avoid_empty_jar_file_entry_violation
{

public void testEquals()
{
    String outFilename = "outfile.zip";
    JarOutputStream outZip = new JarOutputStream(new FileOutputStream(outFilename));
    String filename="file1.txt"

    outZip.putNextEntry(new ZipEntry(filename));

    outZip.closeEntry();    //Violation.
}

}

Should be written as:

package com.rule;

public class Avoid_empty_jar_file_entry_correction
{

public void testEquals()
{
    String outFilename = "outfile.zip";
    JarOutputStream outZip = new JarOutputStream(new FileOutputStream(outFilename));

    String filename="file1.txt"
    outZip.putNextEntry(new ZipEntry(filename));

    int len = 0;
    while ((len = in.read(buf)) > 0)
    {
out.write(buf, 0, len);     //Correction.

}

    outZip.closeEntry();
}

}

Reference: Reference not available.
Rule 41: Use_break_for_each_case

Severity: Medium
Rule: Use break for each case for better readability
Reason: Use break for each case for better readability

Usage Example:

package com.rule;

class Use_break_for_each_case_violation
{

public void method(int i)
{
    switch(i)
    {
     case 1:
        // some code
     break;
     case 2:
        // some code            // VIOLATION
     case 3:
        // some code
     break;
     case 4:
     case 5:
        // some code
    }
}

}

Should be written as:

package com.rule;

class Use_break_for_each_case_correction
{

public void method(int i)
{
    switch(i)
    {
     case 1: //same action for multiple cases
     case 2:
        // some code
     break;                 // CORRECTION
     case 3:
        // some code
            // throw some exception here
     case 4:
        // some code
     return i;
     case 5:
        // some code
     continue; // switch needs to be inside a loop
     case 6:
        // some code
    }
}

}

Reference: Reference Not Available.
Rule 42: Avoid_using_array_initializers

Severity: Low
Rule: Initializing arrays element-by-element can make the code easier to read.
Reason: Initializing arrays element-by-element can make the code easier to read.

Usage Example:

public class Test
{
public static void main(String[] args)
{
int[] a= {1, 2, 3}; //VIOLATION
}
}

Should be written as:

public class Test
{
public static void main(String[] args)
{
int[] a= new int[3]; //FIXED
a[0]= 1;
a[1]= 2;
a[2]= 3;
}
}

Reference: Not available.
Rule 43: Use_static_fields_methods_with_class

Severity: Medium
Rule: Static fields and methods are an attribute of the class, not an instance of the class. To improve clarity, refer to them using the class name instead of the instance variable name.
Reason: Static fields and methods are an attribute of the class, not an instance of the class. To improve clarity, refer to them using the class name instead of the instance variable name.

Usage Example:

package com.rule;
class Use_static_fields_methods_with_class_violation
{

public void setValue(Object obj)
{
    Base3 b = new Base3();
    b.obj = obj; // Violation
}

}
class Base3
{

public static Object obj;

}

Should be written as:

package com.rule;
class Use_static_fields_methods_with_class_violation
{

public void setValue(Object obj)
{
    Base3.obj = obj; // Correction
}

}
class Base3
{

public static Object obj;

}

Reference: http://java.sun.com/docs/codeconv/html/CodeConventions.doc9.html#587
Rule 44: Check_instanceOf_in_equals

Severity: Medium
Rule: Use 'instanceof' in equals method.
Reason: Use 'instanceof' in equals method.

Usage Example:

package com.rule;

class Check_instanceOf_in_equals_violation
{

private static Derived2 d = new Derived2();

public boolean isEqual(Object b)
{
    return d.equals(b);
}

public static final int TEN = 10;

public static void main(String[] args)
{
    d.setK(TEN);
    Base2 b1 = new Base2();
    b1.setK(TEN);
    Derived2 d1 = new Derived2();
    d1.setK(TEN);
}

}

class Base2
{

private int k=0;

public boolean equals(Object b) // VIOLATION
{
    boolean result = false;
    Base2 b1 =(Base2)b;
    result = b1.k == k;
    return result;
}

public final void setK(int i)
{
     k = i;
}

}

class Derived2 extends Base2
{

public boolean equals(Object b) // VIOLATION
{
    boolean result = false;
    result = super.equals(b);
    return result;
}

}

Should be written as:

package com.rule;

class Check_instanceOf_in_equals_correction
{

private static Derived1 d = new Derived1();

public boolean isEqual(Object b)
{
    return d.equals(b);
}

public static final int TEN = 10;

public static void main(String[] args)
{
    d.setK(TEN);
    Base1 b1 = new Base1();
    b1.setK(TEN);
    Derived1 d1 = new Derived1();
    d1.setK(TEN);
}

}

class Base1
{

private int k=0;

public boolean equals(Object b)
{
    boolean result = false;
    if(b instanceof  Base1) // CORRECTION
    {
        Base1 b1 =(Base1)b;
        result = b1.k == k;
    }
    return result;
}

public final void setK(int i)
{
     k = i;
}

}

class Derived1 extends Base1
{

public boolean equals(Object b)
{
    boolean result = false;
    if(b instanceof  Derived1) // CORRECTION
    {
        result = super.equals(b);
    }
    return result;
}

}

Reference: Joshua Bloch: “Effective Java - Programming Language Guide”.
Addison Wesley,
Rule 45: Check_for_equality_using_getClass

Severity: Medium
Rule: Use getClass() in equals implementation.
Reason: Use getClass() in equals implementation.

Usage Example:

public class UseGetClass
{

public int k;

public boolean equals ( Object o )      // VIOLATION
{
    if ( o instanceof UseGetClass )
    {
        UseGetClass temp = (UseGetClass)o;
        return temp.k == k; 
    }
    return false;
}    

}

Should be written as:

public class UseGetClass
{

public int k;

public boolean equals ( Object o )      
{
    if ( getClass() != o.getClass() )   // CORRECTION
    {
        return false;
    }   
    else if ( o instanceof UseGetClass )
    {
        UseGetClass temp = (UseGetClass)o;
        return temp.k == k; 
    }
    return false;
}    

}

Reference: Peter Haggar: “Practical Java - Programming Language Guide”.
Peter Haggar: “Practical Java - Programming Language Guide”. Addison Wesley, 2000, pp.44 -47
Rule 46: Avoid_empty_block_in_case

Severity: Medium
Rule: Avoid empty block in case statements.
Reason: Avoid empty block in case statements.

Usage Example:

package com.rule;
public class Avoid_empty_block_in_case_violation
{

public void method()
{
    switch (0)
    {
        case 0 : // VIOLATION
        {
        }
        case 1 :
        {
            // STATEMENTS
        }
    }
}

}

Should be written as:

package com.rule;
public class Avoid_empty_block_in_case_correction
{

public void method()
{
    switch (0)
    {
        case 0 : // CORRECTION
        case 1 :
        {
            // STATEMENTS
        }
    }
}

}

Reference: Reference Not Available.
Rule 47: Define_constructors_before_methods

Severity: Low
Rule: Always define all the constructors before defining any methods.
Reason: Always define all the constructors before defining any methods.

Usage Example:

package com.rule;

public class Define_constructors_before_methods_violation
{

public void method()
{
}

public Define_constructors_before_methods_violation() // VIOLATION
{
}

}

Should be written as:

package com.rule;

public class Define_constructors_before_methods_correction
{

public Define_constructors_before_methods_violation() // CORRECTION
{
}

public void method()
{
}

}

Reference: http://java.sun.com/docs/codeconv/html/CodeConventions.doc2.html#277
Rule 48: Alway_call_super_clone

Severity: High
Rule: Always call super.clone() from the clone method defined in your class.
Reason: Always call super.clone() from the clone method defined in your class.

Usage Example:

package com.rule;

import java.util.ArrayList;

public class Alway_call_super_clone_violation implements Cloneable
{

ArrayList alValues;

protected Object clone() throws CloneNotSupportedException
{
    Alway_call_super_clone_violation obj = new Alway_call_super_clone_violation();  // VIOLATION
    obj.alValues = new ArrayList(alValues);
    return obj;
}

}

Should be written as:

package com.rule;

import java.util.ArrayList;

public class Alway_call_super_clone_correction implements Cloneable
{

ArrayList alValues;

protected Object clone() throws CloneNotSupportedException
{
    Alway_call_super_clone_correction obj = (Alway_call_super_clone_correction) super.clone();      // CORRECTION
    obj.alValues = new ArrayList(alValues);
    return obj;
}

}

Reference: Reference not available.
Rule 49: Clone_method_not_implementing_Cloneable

Severity: High
Rule: A class containing the clone method must implement the Cloneable interface.
Reason: A class containing the clone method must implement the Cloneable interface.

Usage Example:

class A // VIOLATION
{
private int x;
public A(int i)

{

x = i;
}

public Object clone() 
    throws CloneNotSupportedException 
{

return super.clone();
}
}

public class CloneDemo2
{
public static void main(String args[])

    throws CloneNotSupportedException 
    {

A obj1 = new A(37);
A obj2 = (A)obj1.clone();
}
}

Should be written as:

class A implements Cloneable
{
private int x;
public A(int i)

{

x = i;
}

public Object clone() 
    throws CloneNotSupportedException 
{

return super.clone();
}
}

public class CloneDemo2
{
public static void main(String args[])

    throws CloneNotSupportedException 
    {

A obj1 = new A(37);
A obj2 = (A)obj1.clone();
}
}

Reference: http://java.sun.com/developer/JDCTechTips/2001/tt0306.html#cloning
Rule 50: Cloneable_class_not_implementing_clone_method

Severity: High
Rule: Class implements Cloneable but does not define or use the clone method.
Reason: Class implements Cloneable but does not define or use the clone method.

Usage Example:

public class Test implements Cloneable // VIOLATION
{

//...

}

Should be written as:

public class Test implements Cloneable
{

public Object clone() throws CloneNotSupportedException // FIXED
{
    return super.clone();
}

}

Reference: Not Available.
Rule 51: Always_comment_main_method

Severity: High
Rule: Always comment main method after debugging is over.
Reason: Always comment main method after debugging is over.

Usage Example:

package com.rule;

public class Always_comment_main_method_violation
{

public static void main(String[] args)  // Violation.
{
    // Some Code
}

}

Should be written as:

package com.rule;

public class Always_comment_main_method_correction
{
/*

public static void main(String[] args)      //Correction.
{
    // Some Code
}

*/

}

Reference: Reference not available.
Rule 52: Declare_package_with_intial

Severity: Low
Rule: Specify package for the class and make sure that it starts with com. or org.
Reason: Specify package for the class and make sure that it starts with com. or org.

Usage Example:

package rule; // VIOLATION

class Declare_package_with_intial_violation
{

public void method()
{
}

}

Should be written as:

package com.rule; // CORRECTION

class Declare_package_with_intial_correction
{

public void method()
{
}

}

Reference: Reference Not Available.
Rule 53: Avoid_unqualified_access_to_fields

Severity: Medium
Rule: Explicitly refer instance fields using “this” reference.
Reason: Explicitly refer instance fields using “this” reference.

Usage Example:

public class Test extends A
{

int field1;

public void aMethod()
{
    field1 = 2; // VIOLATION
    field2 = "hello"; // VIOLATION
}

}

class A
{

String field2;

}

Should be written as:

public class Test extends A
{

int field1;

public void aMethod()
{
    this.field1 = 2;
    this.field2 = "hello";
}

}

class A
{

String field2;

}

Reference: No references available.
Rule 54: Do_not_overload_finalize

Severity: Medium
Rule: Do not overload finalize method.
Reason: Do not overload finalize method.

Usage Example:

package com.rule;

public class Do_not_overload_finalize_violation
{

public void finalize(int a)// Violation
{
    //...
}

}

Should be written as:

Do not overload finalize().

Reference: www.refactorit.com/files/RefactorIT_Manual.pdf
Rule 55: Return_empty_Collection

Severity: Medium
Rule: Return empty collection instead of returning null value from method.
Reason: Return empty collection instead of returning null value from method.

Usage Example:

package com.rule;

import java.util.ArrayList;

public class Return_empty_Collection_violation
{

public List method()
{
    return null; // VIOLATION
}

}

Should be written as:

package com.rule;

import java.util.Collections;
import java.util.List;

public class Return_empty_Collection_correction
{

public List method()
{
    return Collections.EMPTY_LIST; // CORRECTION
}

}

Reference: http://www.javapractices.com/Topic59.cjp
Rule 56: Avoid_returning_null_instead_of_Enumeration

Severity: Medium
Rule: Returning null could result in null pointer exceptions.
Reason: Returning null could result in null pointer exceptions.

Usage Example:

import java.util.*;

public class NE
{

private Vector elements;

public void addElement( Integer element ) 
{
    if ( elements == null ) 
    {
        elements = new Vector(10);
    }
    elements.add( element );
}

public Enumeration getelements() 
{
    if ( elements == null ) 
    {
        return null;        // VIOLATION    
    }
    return elements.elements();
}

public static  void main(  String [] args ) throws Exception  
{
    NE ne = new NE();
    Enumeration enum = example.getelements(); 
    while ( enum.hasMoreElements() ) 
    {
        System.out.println( enum.nextElement() );
    }
}

}

Should be written as:

import java.util.*;

public class NE
{

private Vector elements;

public void addElement( Integer element ) 
{
    if ( elements == null ) 
    {
        elements = new Vector(10);
    }
    elements.add( element );
}

public Enumeration getelements() 
{
    return elements != null ? elements.elements() : 
    new Enumeration 
    {
        public boolean hasMoreElements()
        {
            return false;
        }

        public Object nextElement()
        {
            throw new UnsupportedOperationException();
        }
    };
}   

public static  void main(  String [] args ) throws Exception  
{
    NE ne = new NE();
    Enumeration enum = ne.getelements(); 
    while ( enum.hasMoreElements() ) 
    {
        System.out.println( enum.nextElement() );
    }
}

}

Reference: No references available.
Rule 57: Avoid_returning_null_instead_of_Iterator

Severity: Medium
Rule: Returning null could result in null pointer exceptions.
Reason: Returning null could result in null pointer exceptions.

Usage Example:

import java.util.*;

public class NE
{

private List elements;

public void addElement( Integer element ) 
{
    if ( elements == null ) 
    {
        elements = new ArrayList(10);
    }
    elements.add( element );
}

public Iterator getElements() 
{
    if ( elements == null ) 
    {
        return null;    // VIOLATION
    }
    return elements.iterator();
}

public static void main( String[] args ) throws Exception
{
    NE ne = new NE();
    Iterator iter = example.getElements(); 
    while ( iter.hasNext() ) 
    {
        System.out.println( iter.next() );  
    }
}

}

Should be written as:

import java.util.*;

public class NE
{
private List elements;

public void addElement( Integer element )
{

if ( elements == null ) 
{
    elements = new ArrayList(10);
}
elements.add( element );

}

public Iterator getElements()
{

return ( elements != null ) ? elements.iterator() :
new Iterator() {
    public boolean hasNext() 
    {
        return false;
    }

    public Object next() 
    {
        throw new UnsupportedOperationException();
    }

    public void remove() 
    {
        throw new UnsupportedOperationException();
    }
};

}

public static void main( String[] args )
{

NE ne = new NE();
Iterator iter = ne.getElements(); 
while ( iter.hasNext() )
{
    System.out.println( iter.next() );
}

}

}

Reference: No references available.
Rule 58: Avoid_subclassing_RuntimeException

Severity: Medium
Rule: Avoid extending RuntimeException.
Reason: Avoid extending RuntimeException.

Usage Example:

package com.rule;

class Avoid_subclassing_RuntimeException_violation extends RuntimeException // VIOLATION
{

//...

}

Should be written as:

class Avoid_subclassing_RuntimeException_correction extends Exception // CORRECTION
{

//...

}

Reference: http://java.sun.com/docs/books/tutorial/essential/exceptions/runtime.html
Rule 59: Avoid_duplicate_import_statements

Severity: Low
Rule: Do not import the same type or package again.
Reason: Do not import the same type or package again.

Usage Example:

package com.rule;

import java.awt.event.;
import java.awt.event.ActionListener;
import java.util.ArrayList;
import java.awt.event.
; // VIOLATION
import java.util.Collections;
import java.util.ArrayList; // VIOLATION
import java.util.Enumeration;

public class Avoid_duplicate_import_statements_violation implements ActionListener
{

public Enumeration method()
{
    ArrayList al = new ArrayList(1);
    return Collections.enumeration(al);
}

public void actionPerformed(ActionEvent e)
{
}

}

Should be written as:

package com.rule;

import java.awt.event.;
import java.awt.event.ActionListener; // IGNORED
import java.util.ArrayList;
//import java.awt.event.
; // CORRECTION
import java.util.Collections;
//import java.util.ArrayList; // CORRECTION
import java.util.Enumeration;

public class Avoid_duplicate_import_statements_correction implements ActionListener
{

public Enumeration method()
{
    ArrayList al = new ArrayList(1);
    return Collections.enumeration(al);
}

public void actionPerformed(ActionEvent e)
{
}

}

Reference: No reference available.
Rule 60: Avoid_numeric_literals

Severity: Medium
Rule: Code is generally easier to read and maintain if magic numbers (hard coded numeric literals) are replaced with descriptively named static final fields.
Reason: Code is generally easier to read and maintain if magic numbers (hard coded numeric literals) are replaced with descriptively named static final fields.

Usage Example:

package com.rule;

import java.util.ArrayList;

class Avoid_numeric_literals_violation
{

public void method()
{
    int k = 9;          // VIOLATION
    ArrayList al = new ArrayList(10);       // VIOLATION

    k = al.size();
}

}

Should be written as:

package com.rule;

import java.util.ArrayList;

class Avoid_numeric_literals_correction
{

public static final int INITVALUE = 9;
public static final int INITIALSIZE = 10;

public void method()
{
    int k = INITVALUE;      // CORRECTION
    ArrayList al = new ArrayList(INITIALSIZE);      // CORRECTION

    k = al.size();
}

}

Reference: http://builder.com.com/5100-6370-1061642.html
Rule 61: Reduce_scope_of_local_variable

Severity: High
Rule: Reduce scope of local variable so that it is only visible in the scope where it is used.
Reason: Reduce scope of local variable so that it is only visible in the scope where it is used.

Usage Example:

package com.rule;

public class Reduce_scope_of_local_variable_violation
{

private void method(int i)
{
    int var = 0; //Violation
    if(true)
    {
        switch(i)
        {
            case 1:
            {
                var = foo();
                var++;
                System.out.println(var);
            }
            case 2:
            {
                //code not using 'var'
            }
        }
    }   
}

}

Should be written as:

package com.rule;

public class Reduce_scope_of_local_variable_correction
{

private void method(int i)
{
    if(true)
    {
        switch(i)
        {
            case 1:
            {
                int var = foo(); //Correction
                var++;
                System.out.println(var);
            }
            case 2:
            {
                //code not using 'var'
            }
        }
    }   
}   

}

Reference: Reference not available.
Rule 62: Use_similar_import_style

Severity: Low
Rule: Use same style while importing.
Reason: Use same style while importing.

Usage Example:

package com.rule;

import java.awt.;
import java.util.ArrayList; // VIOLATION
import java.util.Collections; // VIOLATION
import java.awt.event.
;
import java.util.Enumeration; // VIOLATION

public class Use_similar_import_style_violation extends Frame implements ActionListener
{

public Enumeration method()
{
    ArrayList al = new ArrayList();
    return Collections.enumeration(al);
}

public void actionPerformed(ActionEvent e)
{
}

}

Should be written as:

package com.rule;

import java.awt.;
import java.util.
; // CORRECTION
import java.awt.event.*;

public class Use_similar_import_style_correction extends Frame implements ActionListener
{

public Enumeration method()
{
    ArrayList al = new ArrayList();
    return Collections.enumeration(al);
}

public void actionPerformed(ActionEvent e)
{
}

}

Reference: No references available.
Rule 63: Avoid_using_do_while_loops

Severity: Low
Rule: Since the condition is specified at the end of the loop, it makes the code difficult to read.
Reason: Since the condition is specified at the end of the loop, it makes the code difficult to read.

Usage Example:

public class MyClass
{

public static void main (String[] args) 
{
  String name= null;
  do  //VIOLATION
    {
    System.out.println("Please enter a name:");
name= getNameFromInput();
     } while (name== null); 
}

}

Should be written as:

public class MyClass
{

public static void main (String[] args) 
{
  String name= null;
    while (name== null)  // CORRECTION
    {
System.out.println("Please enter a name:");
name= getNameFromInput();
  } 
 }

}

Reference: No references available.
Rule 64: Always_use_braces_with_if_or_else

Severity: Medium
Rule: Use Braces around all statements when they are part of a control structure, such as a if-else statement.
Reason: Use Braces around all statements when they are part of a control structure, such as a if-else statement.

Usage Example:

package com.rule;

class Always_use_braces_with_if_or_else_violation
{

public int update(int i)
{
    final int TEN = 10;

    if(i<TEN)       // VIOLATION
        i = TEN;
    //...
    //...

    return i;
}

}

Should be written as:

package com.rule;

class Always_use_braces_with_if_or_else_correction
{

public int update(int i)
{
    final int TEN = 10;

    if(i<TEN)       
    {               // CORRECTION
        i = TEN;
    }
    //...
    //...

    return i;
}

}

Reference: http://java.sun.com/docs/codeconv/html/CodeConventions.doc6.html
Rule 65: Avoid_hardcoded_absolute_pathname

Severity: Medium
Rule: Avoid hardcoded absolute pathnames while creating file objects.
Reason: Avoid hardcoded absolute pathnames while creating file objects.

Usage Example:

package com.rule;

import java.io.File;
import java.io.BufferedReader;
import java.io.IOException;
import java.io.FileReader;

class Avoid_hardcoded_absolute_pathname_violation
{

public void method ()
{   
    File f = new File("C://InputFile.txt");     // VIOLATION

    File f1 = new File("C://SomeDirectory","InputFile.txt");        // VIOLATION

    File f2 = new File("//InputFile.txt");      // VIOLATION

    File f3 = new File("InputFile.txt");    

    try
    {
        BufferedReader in = new BufferedReader(new FileReader(f));
        String str;

        // Some Code ....

    }catch (IOException e)
    {
    }
    finally
    {
        in.close();
    }

}
}

Should be written as:

Reference: Reference not available.
Rule 66: Avoid_changing_method_arguments

Severity: High
Rule: Avoid changing method arguments.
Reason: Avoid changing method arguments.

Usage Example:

package com.rule;

public class Avoid_changing_method_arguments_violation
{

public void  foo(int num)
{
    for(int i = num-1; num-- >=0; )//Violation
    {
        //....
    }
}

}

class Reference
{

int var =9;

}

Should be written as:

package com.rule;

public class Avoid_changing_method_arguments_correction
{

public void  foo(int num)
{
    int iSize = num;  //Correction
    for(int i = iSize-1; iSize-- >=0;)
    {
        //...
    }
}

}

class Reference
{

int var =9;

}

Reference: Reference not available.
Rule 67: Method_next_should_throw_NoSuchElementException

Severity: Low
Rule: next() method of the class implementing java.util.Iterator should throw a NoSuchElementException.
Reason: next() method of the class implementing java.util.Iterator should throw a NoSuchElementException.

Usage Example:

package com.rule;
import java.util.Iterator;

public class Method_next_should_throw_NoSuchElementException_violation implements java.util.Iterator
{

public Object next() // Violation
{
    ++curr;
    return (arr.length > curr ? arr[curr] : null);
}

}

Should be written as:

package com.rule;
import java.util.Iterator;

public class Method_next_should_throw_NoSuchElementException_correction implements java.util.Iterator
{

public Object next() 
{
    ++curr;
    if(arr.length > curr)
    {
          return arr[curr];
    }
    else
    {
        throw new NoSuchElementException();// Correction
    } 
}

}

Reference: Reference not available.
Rule 68: Avoid_using_increment_or_decrement_operators_in_nested_expressions

Severity: Low
Rule: Compounding increment or decrement operators into method calls or mathematical operations make the code difficult to read.
Reason: Compounding increment or decrement operators into method calls or mathematical operations make the code difficult to read.

Usage Example:

public class MyClass
{

public void aMethod()
{
    int a = 0;
    anotherMethod(++a); // VIOLATION
}

public void anotherMethod( int a )
{
    //...
}

}

Should be written as:

public class MyClass
{

public void aMethod()
{
    int a = 0;
    ++a;
    anotherMethod(a); // CORRECTION
}

public void anotherMethod( int a )
{
    //...
}

}

Reference: No references available.
Rule 69: Define_package

Severity: Low
Rule: Specify package for the class.
Reason: Specify package for the class.

Usage Example:

import java.util.ArrayList; // VIOLATION
class Define_package_violation
{

private static final int SIZE = 10;
private ArrayList al = new ArrayList(SIZE);

public int method()
{
    return al.size();
}

}

Should be written as:

package com.rule; // CORRECTION

import java.util.ArrayList;

class Define_package_correction
{

private static final int SIZE = 10;
private ArrayList al = new ArrayList(SIZE);

public int method()
{
    return al.size();
}

}

Reference: http://jarticles.com/package/package_eng.html
Rule 70: Always_place_main_method_last

Severity: Low
Rule: Placing the main method last is one of the usual conventions followed across projects.
Reason: Placing the main method last is one of the usual conventions followed across projects.

Usage Example:

public class MyClass
{

public static void main (String args[])  // VIOLATION
{ 
System.out.println("Hello, world.");
}

 public void foo () 
{

}

}

Should be written as:

public class MyClass
{

public void foo () 
{

}

public static void main (String args[]) // CORRECTION
{  
  System.out.println("Hello, world.");
}

}

Reference: No references available.
Rule 71: Avoid_Storing_Array_Directly

Severity: High
Rule: Constructors and methods receiving arrays should clone objects and store the copy
Reason: Constructors and methods receiving arrays should clone objects and store the copy

Usage Example:

package com.rule;
public class Array_Is_Stored_Directly_Violation
{

String [] localArray;
String [] localCity;
 public static void main(String args[])
 {
    String [] names = {"abc","xyz"};
    String [] city = {"mno","pqr"};

    Array_Is_Stored_Directly_Violation objRule = new Array_Is_Stored_Directly_Violation();

    objRule.ArrayCopyFunction(names);
    objRule.ArrayCopyFunction1(names);
}
public void ArrayCopyFunction (String [] paramArray)
{
    this.localArray = paramArray;   // Violation.
}
public void ArrayCopyFunction1 (String [] paramArray,String [] city)
{
    String [] myArray;

    this.localCity=city;        // Violation.
    myArray = city;         // Violation.

    for(int i = 0 ; i < paramArray.length ; i++)
        localArray[i] = paramArray[i];
}

}

Should be written as:

Reference: Reference Not Available.
Rule 72: Avoid_trailing_return_in_methods_not_returning_values

Severity: Low
Rule: There should not be trailing return statements in methods not returning any values.
Reason: There should not be trailing return statements in methods not returning any values.

Usage Example:

package com.rule;

public class Avoid_trailing_return_in_methods_not_returning_values_violation
{

public void method()
{
    // statements
    return; // Violation
}

}

Should be written as:

package com.rule;

public class Avoid_trailing_return_in_methods_not_returning_values_correction
{

public void method()
{
    // statements
    // Correction
}

}

Reference: Reference not available.
Rule 73: Declare_logger_static_final

Severity: Low
Rule: Declare logger as static final.
Reason: Declare logger as static final.

Usage Example:

package com.rule;

import java.util.logging.Logger;

public class Declare_logger_static_final_violation
{

Logger log = Logger.getLogger("MyLogger");      // Violation

public void method()
{

}   

}

}

Should be written as:

package com.rule;

import java.util.logging.Logger;

public class Declare_logger_static_final_violation
{

static final Logger log = Logger.getLogger("MyLogger"); //Correction

public void method()
{

}

}

}

Reference: Reference not available.
Rule 74: Declare_jakarta_logger_private_static_final

Severity: Low
Rule: Declare jakarta logger private static final.
Reason: Declare jakarta logger private static final.

Usage Example:

package com.rule;

import java.util.logging.Logger;

public class Declare_jakarta_logger_private_static_final_violation
{

Logger log = Logger.getLogger("MyLogger");      // Violation

public void method()
{

}   

}

}

Should be written as:

package com.rule;

import java.util.logging.Logger;

public class Declare_jakarta_logger_private_static_final_violation
{

private static final Logger log = Logger.getLogger("MyLogger"); //Correction

public void method()
{

}

}

}

Reference: Reference not available.
Rule 75: Avoid_more_than_one_logger

Severity: Low
Rule: Avoid more than one logger.
Reason: Avoid more than one logger.

Usage Example:

package com.rule;

import java.util.logging.Logger;

public class Avoid_more_than_one_logger_violation // Violation
{

final static Logger log1 = Logger.getLogger("MyLogger");    
final static Logger log2 = Logger.getLogger("MyNewLogger");

public void method()
{

}   

}

}

Should be written as:

Reference: Reference not available.
Rule 76: Avoid_more_than_one_class_per_file

Severity: Low
Rule: Avoid more than one class per file.
Reason: Avoid more than one class per file.

Usage Example:

public class Class1
{
//…
}

class myClass // VIOLATION
{
//…
}

Should be written as:

place the classes in two seperates files.

Reference: No references available.
Rule 77: Organize_methods_by_name

Severity: Low
Rule: Makes code easier to read and decreases the chances of possible bugs.
Reason: Makes code easier to read and decreases the chances of possible bugs.

Usage Example:

public class MyClass
{

void foo () {}
void bar () {}
void foo (int a) { // VIOLATION
}

}

Should be written as:

public class MyClass
{

void foo () {}
void foo (int a) { // CORRECTION
}
void bar () {}

}

Reference: No references available.
Rule 78: Avoid_unnecessary_final_method

Severity: Low
Rule: Avoid unnecessary final methods.
Reason: Avoid unnecessary final methods.

Usage Example:

package com.rule;
final public class AvoidUnnecessaryFinalMethod_Violation
{

final public void method()  // Violated
{
    int i;
}

}

Should be written as:

package com.rule;
final public class AvoidUnnecessaryFinalMethod_Correction
{

 public void method()  // O.K
{
    int i;
}

}

Reference: Reference not available.
Rule 79: Avoid_Unnecessary_IfElse_Or_Ternary

Severity: Low
Rule: Avoid unnecessary if-else or ternary expressions.
Reason: Avoid unnecessary if-else or ternary expressions.

Usage Example:

class Avoid_Unnecessary_IfElse_Or_Ternary_Violation
{

public boolean isEvenNumber(int iNumber)
{
    if ((iNumber/2)*2 == iNumber)   //Violation
        return true;
    else
        return false;
}

private void checkSign(int i)
{
    boolean bPositive;
    if (i < 0)                  //Violation
        bPositive = false;
    else
        bPositive = true;

    boolean bNegative = (i < 0) ? true : false; //Violation
}

}

Should be written as:

class Avoid_Unnecessary_IfElse_Or_Ternary_Correction
{

public boolean isEvenNumber(int iNumber)
{
    return (iNumber/2)*2 == iNumber;  //Correction
}

private void checkSign(int i)
{
    boolean bPositive;
    bPositive = !(i < 0);       //Correction

    boolean bNegative = (i < 0); //Correction
}

}

Reference: http://java.sun.com/docs/codeconv/html/CodeConventions.doc9.html#547
Rule 80: Do_not_use_non_final_static_fields_during_initialization

Severity: Medium
Rule: Do not use 'non final' 'static' fields during initialization.
Reason: Do not use 'non final' 'static' fields during initialization.

Usage Example:

package com;
class Do_not_use_non_final_static_fields_during_initialization_Violation
{

static int max = 10;
int var = max;  // Violation

}

Should be written as:

package com;
class Do_not_use_non_final_static_fields_during_initialization_Correction
{

static final int max = 10;  // Fixed
int var = max;  // Fixed

}

Reference: Reference Not Available.
Rule 81: Space_after_typecast

Severity: Low
Rule: By convention, there should be a space after the type.
Reason: By convention, there should be a space after the type.

Usage Example:

package com.rule;

import java.util.ArrayList;
import java.util.Iterator;

public class Space_after_typecast_violation
{

public void method(ArrayList alNames)
{
    int size_alNames = alNames.size();
    for (Iterator iter = alNames.iterator(); size_alNames-- > 0;)
    {
        String name = (String)iter.next();  // VIOlATION
    }
}

}

Should be written as:

package com.rule;

import java.util.ArrayList;
import java.util.Iterator;

public class Space_after_typecast_correction
{

public void method(ArrayList alNames)
{
    int size_alNames = alNames.size();
    for (Iterator iter = alNames.iterator(); size_alNames-- > 0;)
    {
        String name = (String) iter.next(); // CORRECTION
    }
}

}

Reference: No reference available.
Rule 82: Use_chained_constructors

Severity: Medium
Rule: The class with multiple constructors should use constructor chaining
Reason: The class with multiple constructors should use constructor chaining

Usage Example:

package com.rule;

public class Use_chained_constructors_violation
{

private int ID;
private String name;

public Use_chained_constructors_violation()
{
    this(-1, null);
}

public Use_chained_constructors_violation(String nm) // VIOLATION
{
    ID = -1;
    name = nm;
}

public Use_chained_constructors_violation(int id, String nm) // VIOLATION
{
    ID = id;
    name = nm;
}

}

Should be written as:

package com.rule;

public class Use_chained_constructors_correction
{

private int ID;
private String name;

public Use_chained_constructors_correction()
{
    this(-1, null);
}

public Use_chained_constructors_correction(String nm)
{
    this(-1, nm);   // CORRECTION
}

public Use_chained_constructors_correction(int id, String nm)
{
    ID = id;
    name = nm;
}

}

Reference: No reference available.
Rule 83: Avoid_return_in_finally

Severity: Medium
Rule: Do not use return in finally block.
Reason: Do not use return in finally block.

Usage Example:

package com.rule;

public class Avoid_return_in_finally_violation
{

public int method(String str)
{
    try
    {
        return Integer.parseInt(str);
    }
    catch (NumberFormatException e)
    { }
    finally
    {
        return -1; // VIOLATION
    }
}

}

Should be written as:

package com.rule;

public class Avoid_return_in_finally_correction
{

public int method(String str)
{
    int val = -1;
    try
    {
        val = Integer.parseInt(str);
    }
    catch (NumberFormatException e)
    { }

    return val;     // CORRECTION
}

}

Reference: http://www.cs.arizona.edu/sumatra/hallofshame/
Rule 84: Avoid_declaring_constructors_public_for_non_public_classes

Severity: Medium
Rule: Avoid declaring constructors public for classes having private or package access.
Reason: Avoid declaring constructors public for classes having private or package access.

Usage Example:

package com.rule;
class Avoid_declaring_constructors_public_for_non_public_classes_Violation
{

public Avoid_declaring_constructors_public_for_non_public_classes_Violation  // Violation
{
    //.........
}

}

Should be written as:

package com.rule;
class Avoid_declaring_constructors_public_for_non_public_classes_Correction
{

Avoid_declaring_constructors_public_for_non_public_classes_Correction// Correction
{
    //.......
}

}

Reference: References not available.
Rule 85: Provide_default_case_with_switch

Severity: Medium
Rule: Add a default case to every switch statement.
Reason: Add a default case to every switch statement.

Usage Example:

package com.rule;

class Provide_default_case_with_switch_violation
{

public void method()
{
    final int ONE = 1;
    final int TWO = 2;
    int i=9;    
    switch(i)           // VIOLATION
    {
        case ONE:
        {
            //...
            //...
        }
        break;
        case TWO:
        {
            //...
            //...
        }
        break;
    }
}

}

Should be written as:

package com.rule;

class Provide_default_case_with_switch_correction
{

public void method()
{
    final int ONE = 1;
    final int TWO = 2;
    int i=9;
    switch(i)
    {
        case ONE:
        {
            //...
            //...
        }
        break;
        case TWO:
        {
            //...
            //...
        }
        default:        // CORRECTION
        break;
    }
}

}

Reference: http://java.sun.com/docs/codeconv/html/CodeConventions.doc6.html#454
Rule 86: Avoid_star_import

Severity: Low
Rule: Do not use “” in “import” statements
Reason: Do not use “
” in “import” statements

Usage Example:

package com.rule;

import java.util.*; // VIOLATION
class Avoid_star_import_violation
{

private final int TEN = 10;
private ArrayList al = new ArrayList(TEN);

public int method()
{
    return al.size();
}

}

Should be written as:

package com.rule;

import java.util.ArrayList; // CORRECTION
class Avoid_star_import_correction
{

private final int TEN = 10;
private ArrayList al = new ArrayList(TEN);

public int method()
{
    return al.size();
}

}

Reference: http://math.hws.edu/javanotes/c4/s5.html
Rule 87: Avoid_ambigious_method_invocation_from_inner_class

Severity: Medium
Rule: Without specifying the qualifier, the method invocation could lead to confusion.
Reason: Without specifying the qualifier, the method invocation could lead to confusion.

Usage Example:

public class Test
{

public void fubar()
{
    //...
}

class Inner extends A
{
    public void innerMethod()
    {       
        fubar(); // VIOLATION
    }
}

}

class A
{

public void fubar()
{

}

}

Should be written as:

public class Test
{

public void fubar()
{
    //...
}

class Inner extends A
{
    public void innerMethod()
    {       
        super.fubar(); // FIXED
    }
}

}

class A
{

public void fubar()
{

}

}

Reference: Not Available.
Rule 88: Redeclare_class_as_interface_with_only_abstract_methods_and_static_final_fields

Severity: Medium
Rule: Redeclare a class as an interface if the class has only “static final” fields and abstract methods.
Reason: Redeclare a class as an interface if the class has only “static final” fields and abstract methods.

Usage Example:

package com.rule;

public abstract class Redeclare_class_as_interface_with_only_abstract_methods_and_static_final_fields // Violation
{

static final int field=0;
abstract void method(); 

}

Should be written as:

package com.rule;
public interface Redeclare_class_as_interface_with_only_abstract_methods_and_static_final_fields //
correction
{

static final int field=0;
abstract void method(); 

}

Reference: “Nigel Warren, Philip Bishop: “Java in Practice - Design Styles and Idioms
for Effective Java”. Addison-Wesley, 1999. pp.26-29
Rule 89: Use_for_loops_instead_of_while_loops

Severity: Low
Rule: Use 'for' loops instead of 'while' loops.
Reason: Use 'for' loops instead of 'while' loops.

Usage Example:

package com.rule;
public class Use_for_loops_instead_of_while_loops_Violation
{

public void func()
{
    int i =10;
    while(i<15)// Violation
    {
        //...
        i++;
    }
}

}

Should be written as:

package com.rule;
public class Use_for_loops_instead_of_while_loops_Correction
{

public void func()
{
    for(int i = 10; i<15; i++)// Correction
    {
        //...
    }
}

}

Reference: No reference available.
Rule 90: Use_while_loop_instead_of_for_loop

Severity: Low
Rule: Use 'while' loop instead of 'for' loop.
Reason: Use 'while' loop instead of 'for' loop.

Usage Example:

package com.rule;

public class Use_while_loop_instead_of_for_loop_violation
{

public void method()
{
    int i = 0 ;
    for( ; i < 10 ;)    //Violation.
    {
        // Do Something.

        i++;
    }
}

}

Should be written as:

package com.rule;

public class Use_while_loop_instead_of_for_loop_correction
{

public void method()
{
    int i = 0 ;
    while(i < 10)   //Correction.
    {
        // Do Something.

        i++;
    }
}

}

Reference: Reference not available.
Rule 91: Declare_finalize_method_protected

Severity: Medium
Rule: Declare finalize method protected.
Reason: Declare finalize method protected.

Usage Example:

package com.rule;

public class Declare_finalize_method_protected_violation
{

public void finalize() throws Throwable         //Violation.
{

}

}

Should be written as:

package com.rule;

public class Declare_finalize_method_protected_correction
{

protected void finalize() throws Throwable          //Correction.
{

}

}

Reference: No reference available.
Rule 92: Avoid_subclassing_Error_or_Throwable

Severity: Medium
Rule: Do not subclass java.lang.Error or java.lang.Throwable
Reason: Do not subclass java.lang.Error or java.lang.Throwable

Usage Example:

package com.rule;

public class Avoid_subclassing_Error_or_Throwable_violation
{

class Avoid_subclassing_Error_or_Throwable_THROWABLE_violation extends Throwable        // VIOLATION
{
}

}

class Avoid_subclassing_Error_or_Throwable_ERROR_violation extends OutOfMemoryError // VIOLATION
{
}

class Avoid_subclassing_Error_or_Throwable_EXCEPTION_violation extends Exception
{
}

Should be written as:

package com.rule;

public class Avoid_subclassing_Error_or_Throwable_correction
{

class Avoid_subclassing_Error_or_Throwable_THROWABLE_correction extends Exception       // CORRECTION
{
}

}

class Avoid_subclassing_Error_or_Throwable_ERROR_correction extends Exception // CORRECTION
{
}

class Avoid_subclassing_Error_or_Throwable_EXCEPTION_correction extends Exception
{
}

Reference: Reference not available.
Rule 93: Do_not_hide_class_fields_with_method_parameters

Severity: High
Rule: Avoid hiding class fields with method Parameters
Reason: Avoid hiding class fields with method Parameters

Usage Example:

package com.rule;

public class Do_not_hide_class_fields_with_local_variables_violation
{

String data;
    public void method(String data) // VIOLATION
    {           
        this.data=data;
    }
}

}

Should be written as:

package com.rule;

public class Do_not_hide_class_fields_with_local_variables_violation
{

String data;
    public void method(String data_loc) // CORRECTION
    {           
        this.data=data_loc;
    }
}

}

Reference: Reference Not Available.
Rule 94: Do_not_use_deprecated_APIs

Severity: High
Rule: Avoid using the APIs that are marked as deprecated.
Reason: Avoid using the APIs that are marked as deprecated.

Usage Example:

package com.rule;

import java.awt.Component;

public class Do_not_use_deprecated_APIs_violation
{

public void method(Component cmp)
{
    cmp.resize(100, 100);               // VIOLATION
}

}

Should be written as:

package com.rule;

import java.awt.Component;

public class Do_not_use_deprecated_APIs_correction
{

public void method(Component cmp)
{
    cmp.setSize(100, 100);              // CORRECTION
}

}

Reference: http://java.sun.com/j2se/1.4.2/docs/tooldocs/windows/javadoc.html#@deprecated
Rule 95: Use_StringTokenizer_for_string_parsing

Severity: Low
Rule: Use 'StringTokenizer' instead of 'indexOf ()' or 'substring ()' for String parsing.
Reason: Use 'StringTokenizer' instead of 'indexOf ()' or 'substring ()' for String parsing.

Usage Example:

package com.rule;

public class Use_StringTokenizer_for_string_parsing_violation
{

void parseString (String list)
{
    int prev = 0;
    int ind = list.indexOf (',');
    while (ind != -1)
    {
        String item = list.substring (prev, ind);
        processWord(item);
        prev = ind + 1;
        ind = list.indexOf(',', prev); // VIOLATION
    }
    processWord(list.substring (prev));
}

private void processWord(String str)
{
    System.out.println(str);
}

}

Should be written as:

package com.rule;

import java.util.StringTokenizer;

public class Use_StringTokenizer_for_string_parsing_correction
{

void parseString2(String list)
{
    StringTokenizer tok = new StringTokenizer(list, ","); // CORRECTION
    while (tok.hasMoreElements())
    {
        String item = (String) tok.nextElement();
        processWord(item);
    }
}

private void processWord(String str)
{
    System.out.println(str);
}

}

Reference: No Reference Available.
Rule 96: Declare_for_loops_with_increment_statement

Severity: Medium
Rule: Declare “for” loops with an increment statement.
Reason: Declare “for” loops with an increment statement.

Usage Example:

package com.rule;

public class Declare_for_loops_with_increment_statement_violation
{

private String string;

public void method()
{

    int len = string.length();

    for (int i = 0; ; )     // VIOLATION
{
    //...
    if (i == len)
    {
        break;
    }
    i++;
}

}
}

Should be written as:

package com.rule;

public class Declare_for_loops_with_increment_statement_correction
{
private String string=“string”;

public void method()
{

    int len = string.length();
    for (int i = 0; i <= len; i++)      // CORRECTION
{
        //....
}

}
}

Reference: http://java.oreilly.com/news/javaperf_0900.html
Rule 97: Always_keep_default_as_last_case_in_switch_statement

Severity: Low
Rule: Always keep default as last case in switch statement.
Reason: Always keep default as last case in switch statement.

Usage Example:

package.com;
public class AlwaysKeep_default_as_last_case_in_switch_statement_Violation
{

public  void method()
{
  int i = 1;
  switch (i) 
     {
case 1:  System.out.println(i); break;
 default :  System.out.println("Hey, I am default!"); // Violation
case 2: System.out.println(i); break;
     }
}

}

Should be written as:

package.com;
public class AlwaysKeep_default_as_last_case_in_switch_statement_Correction
{

public  void method()
{
  int i = 1;
  switch (i)
     {
case 1:  System.out.println(i); break;
case 2: System.out.println(i); break;
        default :  System.out.println("Hey, I am default!"); // Correction
    }
}

}

Reference: Reference not available.
Rule 98: Avoid_continue_with_label

Severity: Low
Rule: Avoid continue with label.
Reason: Avoid continue with label.

Usage Example:

package com.rule;
public class AvoidContinueWithLabel_Violation
{
boolean found = false;
public void search(String search, String substring)
{
outer: for (int i = 0; i < search.length(); i++)
{
int n = substring.length();
int j = i;
int k = 0;
inner: while (n– != 0)
{
if (search.charAt(j++) != substring.charAt(k++))
{
continue outer;// Violation
}
}
found = true;

  break;

}
}
}

Should be written as:

package com.rule;
class AvoidContinueWithLabel_Correction
{
public boolean search(String search, String substring)
{
for (int i = 0; i < search.length(); i++)
{
int n = substring.length();
int j = i;
int k = 0;
while (n– != 0)
{
if (search.charAt(j++) != substring.charAt(k++))
{
return true;// Correction
}
}
}
}
}

Reference: Reference not available.
Rule 99: Do_not_use_public_static_final_array_fields

Severity: High
Rule: Do not use public static final array fields .
Reason: Do not use public static final array fields .

Usage Example:

package com.rule;
public class Do_not_use_public_static_final_array_fields_Violation
{

public static final String  arr[] = new String[10]; // Violation

}

Should be written as:

package com.rule;

import java.util.List;
import java.util.Collections;
import java.util.Arrays;

public class Do_not_use_public_static_final_array_fields_Correction
{

private static final String arr[] = new String[10];
public static final List = Collections.unmodifiableList(Arrays.asList(arr));    //Correction

}
}

Reference: http://www.javapractices.com/Topic38.cjp
Rule 100: Avoid_final_modifier_for_Collection

Severity: Medium
Rule: Avoid final modifier for Collection
Reason: Avoid final modifier for Collection

Usage Example:

class Avoid_final_modifier_for_Collection_violation
{

public void method ()
{   
    final Hashtable numbers = new Hashtable();      // VIOLATION

final List list = new ArrayList(); // VIOLATION
}
}

Should be written as:

class Avoid_final_modifier_for_Collection_violation
{

public void method ()
{   
    Hashtable numbers = new Hashtable();        // FIXED

List list = new ArrayList(); // FIXED
}
}

Reference: Reference not available.
Rule 101: Define_serialVersionUID

Severity: High
Rule: Always define serialVersionUID in all Serializable classes.
Reason: Always define serialVersionUID in all Serializable classes.

Usage Example:

package com.rule;

import java.awt.Component;
import java.io.Serializable;

public class Define_serialVersionUID_violation implements Serializable // VIOLATION
{

public class Define_serialVersionUID_violation_INNER implements Serializable    // VIOLATION
{
}

public void method()
{
    Component cmp = new Component(){    // VIOLATION
        Object customData;
    };
}

}

Should be written as:

package com.rule;

import java.awt.Component;
import java.io.Serializable;

public class Define_serialVersionUID_correction implements Serializable
{

private static final long serialVersionUID = 1234567890L;   // CORRECTION

public class Define_serialVersionUID_correction_INNER implements Serializable
{
    private static final long serialVersionUID = 1234567890L;   // CORRECTION
}

public void method()
{
    Component cmp = new Component() {
        private static final long serialVersionUID = 1234567890L;   // CORRECTION
        Object customData;
    };
}

}

Reference: http://www.javapractices.com/Topic45.cjp
http://www.javapractices.com/Topic70.cjp
Rule 102: Avoid_throwing_NullPointerException

Severity: High
Rule: Avoid throwing a NullPointerException.
Reason: Avoid throwing a NullPointerException.

Usage Example:

package com.rule

class Avoid_Throwing_Null_Pointer_Exception
{

public void method()
{
    //some code here
    throw new NullPointerException();       
}

}

Should be written as:

}

Reference: Reference Not Available.
Rule 103: Use_main_only_as_entry_point_method

Severity: Medium
Rule: Do not use method name as “main” for any methods other than the entry point method.
Reason: Do not use method name as “main” for any methods other than the entry point method.

Usage Example:

package com.rule;

public class Use_main_only_as_entry_point_method_violation
{

class Use_main_only_as_entry_point_method_INNER_violation
{
    public void main(String[] args)         // VIOLATION
    {
        System.out.println("Use_main_only_as_entry_point_method_INNER.main(args): ");
    }
}

static class Use_main_only_as_entry_point_method_INNER2_violation
{
    public static void main(String[] args) // not a violation
    {
        System.out.println("Use_main_only_as_entry_point_method_INNER2.main(args): ");
    }
}

private static void main(String[] args)     // VIOLATION
{
    System.out.println("Use_main_only_as_entry_point_method.main(args): ");
}

private static void main(String arg)        // VIOLATION
{
    System.out.println("Use_main_only_as_entry_point_method.main(arg): ");
}

public void main()                          // VIOLATION
{
    System.out.println("Use_main_only_as_entry_point_method.main(): ");
}

}

Should be written as:

package com.rule;

public class Use_main_only_as_entry_point_method_correction
{

class Use_main_only_as_entry_point_method_INNER_correction
{
    public void inner_main(String[] args)           // CORRECTION
    {
        System.out.println("Use_main_only_as_entry_point_method_INNER.main(args): ");
    }
}

static class Use_main_only_as_entry_point_method_INNER2
{
    public static void main(String[] args)
    {
        System.out.println("Use_main_only_as_entry_point_method_INNER2.main(args): ");
    }
}

private static void private_main(String[] args)     // CORRECTION
{
    System.out.println("Use_main_only_as_entry_point_method.main(args): ");
}

private static void main_single_arg(String arg)     // CORRECTION
{
    System.out.println("Use_main_only_as_entry_point_method.main(arg): ");
}

public void main_no_args()                          // CORRECTION
{
    System.out.println("Use_main_only_as_entry_point_method.main(): ");
}

}

Reference: http://java.sun.com/docs/books/tutorial/getStarted/application/main.html
Rule 104: Use_if_instead_of_switch

Severity: Medium
Rule: Using switch statements for few cases (usually two) is cumbersome and unclear.
Reason: Using switch statements for few cases (usually two) is cumbersome and unclear.

Usage Example:

public class Test
{

private void foo()
{
    int i = 3;
    switch ( i ) // VIOLATION
    {
        case 1:
            System.out.println("Is One");
            break;
        default:
            System.out.println("Is Not One");
            break;
    }
}

}

Should be written as:

public class Test
{

private void foo()
{
    int i = 3;
    if ( i == 1 ) // CORRECTION
    {
        System.out.println("Is One");
    }
    else
    {
        System.out.println("Is Not One");
    }
}

}

Reference: No references available.
Rule 105: Avoid_transient_for_non_serializable_classes

Severity: Low
Rule: Avoid transient modifier for non serializable classes.
Reason: Avoid transient modifier for non serializable classes.

Usage Example:

package com.rule;

public class Avoid_transient_for_non_serializable_classes_violation
{

transient int var = 98;  // Violation

}

Should be written as:

package com.rule;

public class Avoid_transient_for_non_serializable_classes_correction
{

int var = 98;  // Correction

}

Reference: Reference not available.
Rule 106: Provide_subclasses_of_Thread_a_run_method

Severity: High
Rule: Provide subclasses of Thread a run method”
Reason: Provide subclasses of Thread a run method”

Usage Example:

package com.rule;
public class Provide_subclasses_of_Thread_a_run_method_Violation extends Thread // Violates
{

public void foo()
{
    //...
}

}

Should be written as:

package com.rule;
public class Provide_subclasses_of_Thread_a_run_method_Correction extends Thread // Fixed
{

public void run()
{
    //...
}
    public void foo()
{
    //...
}

Reference: http://www.janeg.ca/scjp/threads/threadClass.html
Rule 107: Always_place_constants_on_one_side

Severity: Low
Rule: null
Reason: null

Usage Example:

package com.rule;

public class Always_place_constants_on_one_side_violation
{

private int count = 100;
public void restoreDefault()
{
    if(2000 < getCount()) // Violation
    {
        setCount(100);
    }
}

}

Should be written as:

package com.rule;

public class Always_place_constants_on_one_side_correction
{

private int count = 100;
public void restoreDefault()
{
    if( getCount() > 2000) // Correction
    {
        setCount(100);
    }
}

}

Reference: http://www.csa.iisc.ernet.in/old-website/Documentation/Tutorials/StyleGuides/netscape-codestyle.html
Rule 108: Avoid_nested_assignments

Severity: Medium
Rule: Avoid nested assignments for better readability
Reason: Avoid nested assignments for better readability

Usage Example:

package com.rule;

class Avoid_nested_assignments_violation
{

void method(int b, int c, int r)
{
    int d, a;
    d = (a = b + c) + r;    // VIOLATION
}

}

Should be written as:

package com.rule;

class Avoid_nested_assignments_correction
{

void method(int b, int c, int r)
{
    int d, a;
    a = b + c;      // CORRECTION
    d = a + r;      // CORRECTION

}

}

Reference: http://java.sun.com/docs/codeconv/html/CodeConventions.doc9.html#177
Rule 109: Return_zero_length_array

Severity: Medium
Rule: Return zero length array from methods instead of returning null.
Reason: Return zero length array from methods instead of returning null.

Usage Example:

package com.rule;

public class Return_zero_length_array_violation
{

public String[] parse(String str)
{
    if(str == null)
    {
        return null; // VIOLATION
    }
    String[] values = new String[(str.length() / 2) + 1];
    int i=0;
    int start = 0;
    while(i<values.length-1)
    {
        values[i] = str.substring(start, start+2);
        i++;
        start = i*2;
    }
    values[i] = str.substring(start);
    return values;
}

}

Should be written as:

package com.rule;

public class Return_zero_length_array_correction
{

public String[] parse(String str)
{
    if(str == null)
    {
        return new String[0]; // CORRECTION
    }
    String[] values = new String[(str.length() / 2) + 1];
    int i=0;
    int start = 0;
    while(i<values.length-1)
    {
        values[i] = str.substring(start, start+2);
        i++;
        start = i*2;
    }
    values[i] = str.substring(start);
    return values;
}

}

Reference: http://java.sun.com/developer/JDCTechTips/2002/tt0910.html#2
http://www.javapractices.com/Topic59.cjp
Rule 110: Do_not_call_constructor_in_clone_method

Severity: Medium
Rule: Avoid calling constructor of the class inside clone method.
Reason: Avoid calling constructor of the class inside clone method.

Usage Example:

package com.rule;

import java.util.ArrayList;

public class Do_not_call_constructor_in_clone_method_violation implements Cloneable
{

ArrayList alValues;

protected Object clone() throws CloneNotSupportedException
{
    Do_not_call_constructor_in_clone_method_violation obj = new Do_not_call_constructor_in_clone_method_violation();    // VIOLATION
    obj.alValues = new ArrayList(alValues);
    return obj;
}

}

Should be written as:

package com.rule;

import java.util.ArrayList;

public class Do_not_call_constructor_in_clone_method_correction implements Cloneable
{

ArrayList alValues;

protected Object clone() throws CloneNotSupportedException
{
    Do_not_call_constructor_in_clone_method_correction obj = (Do_not_call_constructor_in_clone_method_correction) super.clone();        // CORRECTION
    obj.alValues = new ArrayList(alValues);
    return obj;
}

}

Reference: Reference not available.
Rule 111: Avoid_nested_ternary_expressions

Severity: Low
Rule: Avoid nested ternary expressions.
Reason: Avoid nested ternary expressions.

Usage Example:

package com.rule;

public class Avoid_nested_ternary_expressions_violation
{

public int min(int a, int b)
{
    return  (a < b ? (a < 0 ? 0 : a) : b);  // Violation
}

}

Should be written as:

Avoid nested ternary expressions.

Reference: Reference not available.
Rule 112: Avoid_unnecessary_modifiers

Severity: Medium
Rule: Avoid using modifiers public, final and static for the fields of an interface.
Reason: Avoid using modifiers public, final and static for the fields of an interface.

Usage Example:

package com.rule;

public interface Avoid_unnecessary_modifiers_violation
{

public static final int VALUE = 3;      // VIOLATION

}

Should be written as:

package com.rule;

public interface Avoid_unnecessary_modifiers_correction
{

int VALUE = 3;      // CORRECTION

}

Reference: Reference Not Available.
Rule 113: Put_Declaration_at_begining_of_Block

Severity: Medium
Rule: Put declarations only at the beginning of blocks.
Reason: Put declarations only at the beginning of blocks.

Usage Example:

package com.rule;
class Put_Declaration_at_begining_of_Block_Violation
{

public void callMethod()
{
    int j;
    foo(j);
    foo(j+1);
    foo(j+2);
    String str = "anyname";  // Violation
        //...
}

public void foo(int l)
{
    //...
}

}

Should be written as:

package com.rule;
class Put_Declaration_at_begining_of_Block_Correction
{

public void callMethod()
{
    int j;
    String str = "anyname";  // Correction
    foo(j);
    foo(j+1);
    foo(j+2);
        //
}

public void foo(int k)
{
    //
}

}

Reference: http://java.sun.com/docs/codeconv/html/CodeConventions.doc5.html#2991
Rule 114: Avoid_unnecessary_else

Severity: Low
Rule: Avoid unnecessary else.
Reason: Avoid unnecessary else.

Usage Example:

com.rule;
public class Avoid_unnecessary_else_violation
{

public void search(Node nd, String name)
{
    if(name.equals(nd.data))
    {
        System.out.println("found");
        return ;
    }
    else  // Violation
    {
        search(nd.left, name);
        search(nd.right, name);
    }
}

}
class Node
{

String data;
Node left;
Node right;

}

Should be written as:

com.rule;
public class Avoid_unnecessary_else_correction
{

public void search(Node nd, String name)
{
    if(name.equals(nd.data))
    {
        System.out.println("found");
        return ;
    }// Corrected by writing the  code inside else  without else
    search(nd.left, name);
    search(nd.right, name);
}

}
class Node
{

String data;
Node left;
Node right;

}

Reference: Reference not available.
Rule 115: Do_not_use_JDBC_in_bean_class

Severity: Low
Rule: Avoid JDBC code in bean clases.
Reason: Avoid JDBC code in bean clases.

Usage Example:

package com.rule;

import java.sql.Connection;
import java.sql.DriverManager;
import java.sql.PreparedStatement;

public class Do_not_use_JDBC_in_bean_class_violation_Bean
{

Connection conn; // VIOLATION

public void method(String url) throws Exception
{
    conn = DriverManager.getConnection(url);
    String qry = "select * from Employees where join_date=?";
    PreparedStatement ps = conn.prepareStatement(qry); // VIOLATION
}

}

Should be written as:

Avoid using JDBC related code in bean classes.

Reference: No reference avaiable.
Rule 116: Declare_static_class_constructor_private

Severity: Medium
Rule: Declare static class constructor private.
Reason: Declare static class constructor private.

Usage Example:

package com.rule;

public class Declare_static_class_constructor_private_violation //Voilation
{

public static double RATE_INTEREST = 9.5;
public static int getInterest(int iPrinciple, int iDays)
{
    //...
}

}

Should be written as:

package com.rule;

public class Declare_static_class_constructor_private_correction
{

public static double RATE_INTEREST = 9.5;
private Declare_static_class_constructor_private_correction() //Correction
{
}
public static int getInterest(int iPrinciple, int iDays)
{
    //...
}

}

Reference: Reference not available.
Rule 117: Avoid_generic_exception_catching

Severity: Medium
Rule: Avoid catching generic Exception.
Reason: Avoid catching generic Exception.

Usage Example:

package com.rule;

import java.net.Socket;

class Avoid_generic_exception_catching_violation
{

public void method()
{
    int PORT = 5000;

    try
    {
        Socket sock = new Socket("localhost", PORT);
        sock.close();
    }
    catch(Exception e)      // VIOLATION
    {
        e.printStackTrace();
    }
}

}

Should be written as:

package com.rule;

import java.net.Socket;
import java.net.UnknownHostException;
import java.io.IOException;

class Avoid_generic_exception_catching_correction
{

public void method()
{
    int PORT = 5000;

    try
    {
        Socket sock = new Socket("localhost", PORT);
        sock.close();
    }
    catch(UnknownHostException uhe)     // CORRECTION
    {
        uhe.printStackTrace();
    }
    catch(IOException ioe)      // CORRECTION
    {
     ioe.printStackTrace();
    }
    catch(SecurityException se)     // CORRECTION
    {
     se.printStackTrace();
    }
}

}

Reference: http://www.object-arts.com/Lib/EducationCentre4/htm/guidelinesforuse.htm
http://www.javaworld.com/javaworld/jw-10-2003/jw-1003-generics-p2.html
Rule 118: Do_not_call_wait_or_notify_from_unsynchronized_method

Severity: High
Rule: Avoid calling wait() and notify() from an unsynchronized method .
Reason: Avoid calling wait() and notify() from an unsynchronized method .

Usage Example:

package com.rule;
public class Do_not_call_wait_or_notify_from_unsynchronized_method_Violation
{

public void method()
{
    try
    {
        wait ();  // VIOLATION
        notify(); // VIOLATION
    }
    catch (InterruptedException e) 
    {
      // ...
    }
}

}

Should be written as:

package com.rule;
public class Do_not_call_wait_or_notify_from_unsynchronized_method_Correction
{

public void method()
{
    // Fixed by removing wait and notify method.
}

}

Reference: Reference not available.
Rule 119: Always_use_braces_with_loop

Severity: Medium
Rule: Use Braces around all statements when they are part of a control structure, such as for, or while statement.
Reason: Use Braces around all statements when they are part of a control structure, such as for, or while statement.

Usage Example:

package com.rule;

class Always_use_braces_with_loop_violation
{

public void method1()
{
    final int TEN = 10;
    int k = 0;
    for(int i = 0; i < TEN; i++)    // VIOLATION
    k ++;
    int j = 0;
    while(j  <  TEN)    // VIOLATION
    j++;
}

}

Should be written as:

package com.rule;

class Always_use_braces_with_for_loop_correction
{

public void method1()
{
    final int TEN = 10;
    int k = 0;
    for(int i = 0; i < TEN; i++)
    {                           //CORRECTION
    k ++;
    }
    int j = 0;
    while(j  <  TEN)        
    {                       //CORRECTION
    j++;
    }
}

}

Reference: http://java.sun.com/docs/codeconv/html/CodeConventions.doc6.html
Rule 120: Avoid_too_many_nested_blocks

Severity: Medium
Rule: Avoid writing code which has too many nested blocks.
Reason: Avoid writing code which has too many nested blocks.

Usage Example:

package com.rule;

public class Avoid_too_many_nested_blocks_violation
{

public boolean method(int key)
{
    for(int j=0; j < 10; j++)
        while(true)
        {
            switch (key)                                            // not counted
            {
                case 1 :                                            // cases are not counted separately
                case 2 :                                            // instead case groups are counted
                    if(j%2 > 0)
                    {
                        try
                        {
                            synchronized(this)
                            {
                                int k=0;
                                do
                                {
                                    if(k>10)
                                    {
                                        break;
                                    }
                                    else
                                    {
                                        if(j/k == 1)
                                        {
                                            for(int l=0; l<5; l++)
                                            {
                                                if(l>1)             // VIOLATION
                                                {
                                                    return true;
                                                }
                                            }
                                        }
                                    }
                                    k++;
                                } while(true);
                            }
                        }
                        catch(Exception e)
                        {
                        }
                        finally
                        {
                        }
                    }
                    break;

                default :
                    break;
            }
        }
    return false;
}

}

Should be written as:

Try to break up the code in few methods and call them from this method.

Reference: No reference available.
Rule 121: Throw_subclass_of_exception

Severity: Medium
Rule: Avoid using 'throws' Exception; Always use a subclass of 'Exception'.
Reason: Avoid using 'throws' Exception; Always use a subclass of 'Exception'.

Usage Example:

package com.rule;
class Throw_subclass_of_exception_violation
{

public void method() throws Exception       // VIOLATION
{
    //...
}

}

Should be written as:

package com.rule;
class Throw_subclass_of_exception_correction
{

public void method() throws CustomException     // CORRECTION
{
    //...   
}

}
class CustomException extends Exception
{

//...

}

Reference: http://www.step-10.com/java/ExceptionalStrategies.html
Rule 122: Avoid_throwing_java_lang_Error

Severity: Medium
Rule: Avoid throwing unchecked exceptions.
Reason: Avoid throwing unchecked exceptions.

Usage Example:

public class MyClass
{

public void aMethod()
{
    throw new Error("Error Occurred"); // VIOLATION
}

}

Should be written as:

public class MyClass
{

public void aMethod() throws MyException
{
    throw new MyException("Error Occurred"); // CORRECTION
}

}

class MyException extends Exception
{

public Exception( String s )
{
    super(s);
}

}

Reference: No references available.
Rule 123: Avoid_throwing_java_lang_Throwable

Severity: Medium
Rule: Avoid throwing java.lang.Throwable.
Reason: Avoid throwing java.lang.Throwable.

Usage Example:

public class MyClass
{

public void aMethod() throws Throwable
{
    throw new Throwable("Error Occurred"); // VIOLATION
}

}

Should be written as:

public class MyClass
{

public void aMethod() throws MyException
{
    throw new MyException("Error Occurred"); // CORRECTION
}

}

class MyException extends Exception
{

public Exception( String s )
{
    super(s);
}

}

Reference: No references available.
Rule 124: Express_long_integer_constants_using_L_instead_of_l

Severity: Low
Rule: Express Long Integer constants with 'L' instead of 'l'.
Reason: Express Long Integer constants with 'L' instead of 'l'.

Usage Example:

package com.rule;
class ExpressLongIntegerConstantsUsing_L_instead_of_l_Violation
{

public final long eleven = 11l; // Violation

}

Should be written as:

package com.rule;
class ExpressLongIntegerConstantsUsing_L_instead_of_l_Correction
{

public final long eleven = 11L; // Correction

}

Reference: http://leepoint.net/notes-java/20language/12basic_types/21integers.html
Rule 125: Make_bean_class_serializable

Severity: Medium
Rule: Bean classes should be declared Serializable.
Reason: Bean classes should be declared Serializable.

Usage Example:

package com.rule;

public class Make_bean_class_serializable_violation_Bean // VIOLATION
{

}

Should be written as:

package com.rule;

public class Make_bean_class_serializable_correction_Bean implements Serializable // CORRECTION
{
}

Reference: http://java.sun.com/docs/books/tutorial/javabeans/persistence/
http://www.mscs.mu.edu/~lzeng/Component2001/exam/exama.html
Rule 126: Initialize_all_static_fields_explicitly

Severity: Medium
Rule: Explicitly initialize all static field variable.
Reason: Explicitly initialize all static field variable.

Usage Example:

package com;
class Initialize_all_static_fields_explicitly_Violation
{

static int max ;  // Violation
public void foo()
{
    Initialize_all_static_fields_explicitly_Violation.max = 10;
}

}

Should be written as:

package com;
class Initialize_all_static_fields_explicitly_Correction
{

static int max  = 10;// Correction

}

Reference: Reference Not Available.
Rule 127: Always_override_equals_alongwith_hashCode

Severity: Low
Rule: A class that overrides 'Object.hashCode()' should also override 'Object.equals()'.
Reason: A class that overrides 'Object.hashCode()' should also override 'Object.equals()'.

Usage Example:

public class Always_override_equals_alongwith_hashCode_violation // VIOLATION
{

public int hashCode()
{
    return super.hashCode();
}

}

Should be written as:

public class Always_override_equals_alongwith_hashCode_correction // CORRECTION
{

public int hashCode()
{
    return super.hashCode();
}
public boolean equals(Object obj)
{
    return super.equals(obj);
}

}

Reference: http://www.javaworld.com/javaworld/jw-01-1999/jw-01-object-p2.html
http://www.geocities.com/technofundo/tech/java/equalhash.html
Rule 128: Avoid_array_declarators_after_variable_name

Severity: Medium
Rule: Array declarator brackets should appear after the data type and not after the variable name.
Reason: Array declarator brackets should appear after the data type and not after the variable name.

Usage Example:

package com.rule;

class Avoid_array_declarators_after_variable_name
{

int intArr[]; //VIOLATION
public static void main(String sArr1[]) //VOILATION
{
    String[] sArr2 = new String[]{"temp"};
    int i = 0;
    for (String sCategories[] = {"A","B","C"}; i < sCategories.length; i++) //VIOLATION
    {
        System.out.println(sCategories[i]);
    }
}

}

Should be written as:

package com.rule;

class Avoid_array_declarators_after_variable_name_correction
{

int[] intArr; //CORRECTION
public static void main(String[] sArr1) //CORRECTION
{
    String[] sArr2 = new String[]{"temp"};
    int i = 0;
    for (String[] sCategories = {"A","B","C"}; i < sCategories.length; i++) ////CORRECTION
    {
        System.out.println(sCategories[i]);
    }
}

}

Reference: Reference Not Available
Rule 129: Avoid_using_lables_in_switch

Severity: Medium
Rule: Do not use labels inside switch statement block
Reason: Do not use labels inside switch statement block

Usage Example:

package com.rule;

public class Avoid_using_lables_in_switch_violation
{

public void method(int key)
{
    customLabel2:
    switch (key)
    {
        case 1:
            // handle 1
            break;

        case 2:
            // handle 2
            // break;

        case3:                          // VIOLATION
            // handle 2 + 3
            break;

        case 4:
        customLabel:                    // VIOLATION
            for(int j=0; j<3; j++)
            {
                System.out.println("---");
                for (int i = 0; i < 10; i++)
                {
                    System.out.println(i);
                    if(i==j)
                    {
                        continue customLabel;
                    }
                }
            }
            // handle 4
            break;

        default :
            break customLabel2;
    }
}

}

Should be written as:

Remove the unwanted lables and correct any typing mistakes.

Reference: Reference not available.
Rule 130: Avoid_long_method_chain

Severity: Medium
Rule: Avoid long method chain.
Reason: Avoid long method chain.

Usage Example:

package com.rule;

public class Avoid_long_method_chain_violation
{

public static void main(String args[])
{
Avoid_long_method_chain_violation a =new Avoid_long_method_chain_violation();       
    a.meth1().meth2().meth3().meth4();  // Violation;
}

}

Should be written as:

Avoid long method chain.

Reference: No reference
Rule 131: Do_not_use_JDBC_in_servlet_class

Severity: Low
Rule: Do not use JDBC code in servlet class.
Reason: Do not use JDBC code in servlet class.

Usage Example:

package com.rule;

import java.sql.Connection;
import java.sql.DriverManager;
import java.sql.PreparedStatement;

public class Do_not_use_JDBC_in_servlet_class
{

Connection conn;

public void method(String url) throws Exception
{
    conn = DriverManager.getConnection(url);// Violation
    String qry = "select * from Employees where join_date=?";
    PreparedStatement ps = conn.prepareStatement(qry); // Violation
}

}

Should be written as:

Avoid using JDBC code directly inside servlet class.

Reference: Reference not available.
Rule 132: Catch_exception_derived_from_exception

Severity: Medium
Rule: Avoid catching exception not derived from java.lang.Exception
Reason: Avoid catching exception not derived from java.lang.Exception

Usage Example:

package com.rule;

class Catch_exception_derived_from_exception_violation
{

public int method()
{
    int ZERO = 0;
    int TEN = 10;
    int result;

    try
    {
        result = TEN/ZERO;
        //...............
        //.....................
    }
    catch(Throwable th) // VIOLATION
    {
        result = TEN;
    }
    return result;
}

}

Should be written as:

package com.rule;

class Catch_exception_derived_from_exception_correction
{

public int method()
{
    int ZERO = 0;
    int TEN = 10;
    int result;

    try
    {
        result = TEN/ZERO;
        //...............
        //.....................
    }
    catch(ArithmeticException ae)   // CORRECTION
    {
        result = TEN;
    }
    return result;
}

}

Reference: Reference Not Available.
Rule 133: Avoid_methods_with_same_name_as_classname

Severity: Low
Rule: Do not define methods with same name as that of the class or interface.
Reason: Do not define methods with same name as that of the class or interface.

Usage Example:

package com.rule;

public class Avoid_methods_with_same_name_as_classname_violation
{

public Avoid_methods_with_same_name_as_classname_violation()
{
}

public void Avoid_methods_with_same_name_as_classname_violation()       // VIOLATION
{
}

public void Avoid_methods_with_same_name_as_classname_violation()
{
}

}

Should be written as:

Change the name of the method.

Reference: http://help.eclipse.org/help30/index.jsp?topic=/org.eclipse.jdt.doc.user/reference/ref-preferences-compiler.htm
Rule 134: Always_declare_serialVersionUID_static_final_long

Severity: High
Rule: Always declare serialVersionUID as final static long.
Reason: Always declare serialVersionUID as final static long.

Usage Example:

package com.rule;
import java.io.Serializable;

public class Always_declare_serialVersionUID_static_final_long_violation implements Serializable
{

private  long serialVersionUID = 123456789L;  //Violation

}

Should be written as:

package com.rule;
import java.io.Serializable;

public class Always_declare_serialVersionUID_static_final_long_correction implements Serializable
{

private static final long serialVersionUID = 123456789L;  //Correction

}

Reference: http://www.javapractices.com/Topic45.cjp
Rule 135: Always_override_hashCode_alongwith_equals

Severity: Low
Rule: A class that overrides 'Object.equals()' should also override 'Object.hashCode()'.
Reason: A class that overrides 'Object.equals()' should also override 'Object.hashCode()'.

Usage Example:

public class Always_override_hashCode_alongwith_equals_violation // VIOLATION
{

public boolean equals(Object obj)
{
    return super.equals(obj);
}

}

Should be written as:

public class Always_override_hashCode_alongwith_equals_correction // CORRECTION
{

public boolean equals(Object obj)
{
    return super.equals(obj);
}
public int hashCode()
{
    return super.hashCode();
}

}

Reference: http://www.javapractices.com/Topic28.cjp
http://www.cafeaulait.org/course/week4/38.html
http://www.javaworld.com/javaworld/jw-01-1999/jw-01-object-p2.html
http://www.geocities.com/technofundo/tech/java/equalhash.html
Rule 136: Always_override_toString_method

Severity: Medium
Rule: Always override toString() method.
Reason: Always override toString() method.

Usage Example:

package com.rule;

public class Always_override_toString_method_violation // Violation
{

}

Should be written as:

package com.rule;

public class Always_override_toString_method_correction
{

public String toString()// Correction
{
    //...
}

}

Reference: Reference not available.
Rule 137: Avoid_more_than_one_return

Severity: Medium
Rule: Never use more than one return statement in the body of a non-void method.
Reason: Never use more than one return statement in the body of a non-void method.

Usage Example:

package com.rule;

class Avoid_more_than_one_return_violation
{

public int method()
{
    Object obj = null;
    int i =0;

    if (obj == null)
    {
        return i++;     // VIOLATION
    }
    return i--;     // VIOLATION
}

}

Should be written as:

package com.rule;

class Avoid_more_than_one_return_correction
{

public int method()
{
    Object obj = null;
    int i =0;

    if (obj == null)
    {
        i++;
    }
    else
    {
        i--;
    }
    return i;       // CORRECTION
}

}

Reference: Reference Not Available.
Rule 138: Avoid_creating_local_variable_for_return

Severity: Medium
Rule: Avoid creating local variable for returning value from a method.
Reason: Avoid creating local variable for returning value from a method.

Usage Example:

package com.rule;

public class Avoid_creating_local_variable_for_return_violation
{

public int method()
{
    int i = doProcess();

    return  i;  // Violation.
}

}

Should be written as:

package com.rule;

public class Avoid_creating_local_variable_for_return_correction
{

public int method()
{
    return  doProcess();        //Correction.
}

}

Reference: Reference not available.
Rule 139: Declare_for_loops_with_condition_statement

Severity: Medium
Rule: If possible avoid empty for condition.
Reason: If possible avoid empty for condition.

Usage Example:

package com.rule;

public class Declare_for_loops_with_condition_statement_violation
{
private String string;

public void method()
{

    int len = string.length();
    for (int i = 0; ; i++)      // VIOLATION
{
    //...
    if (i == len)
    {
        break;
    }
}

}
}

Should be written as:

package com.rule;
public class Declare_for_loops_with_condition_statement_correction
{

private String string;

public void method()
{

    int len = string.length();
    for (int i = 0; i <= len; i++)      // CORRECTION
{
    //...
    if (i == len)
    {
        break;
    }
}

}
}

Reference: http://www.indiana.edu/~q320/Notes/loops.html
Rule 140: Avoid_unnecessary_comparison_with_null

Severity: Low
Rule: Avoid unnecessary comparison of references with null.
Reason: Avoid unnecessary comparison of references with null.

Usage Example:

package com.rule;

public class Avoid_unnecessary_comparison_with_null_violation
{

private void foo()
{
    String s = null;

    if (s == null) // Violation
    {
        //...
    }

    MyObj x = new MyObj();
    if (x == null)  // Violation
    {
        //...
    }
}

}

Should be written as:

Avoid such unnecessary comparisons.

Reference: Reference not available.
Rule 141: Avoid_empty_initializer_blocks

Severity: Medium
Rule: Avoid empty initializer blocks in your class.
Reason: Avoid empty initializer blocks in your class.

Usage Example:

package com.rule;
public class Avoid_empty_initializer_blocks_violation
{

{   // VIOLATION
}

}

Should be written as:

package com.rule;
public class Avoid_empty_initializer_blocks_violation
{

    // CORRECTION

}

Reference: Reference Not Available.
Rule 142: Avoid_Non_Static_Initializer_Blocks

Severity: High
Rule: Avoid non static initializer blocks in your class.
Reason: Avoid non static initializer blocks in your class.

Usage Example:

package com.rule;

class Avoid_Non_Static_Initializer_Blocks
{

Static int iCounter = 0;
int iVal = 0;
int iSr = 0;

{                   // Violation    
    iSr = ++iCounter;
}

Avoid_Non_Static_Initializer_Blocks(int i)
{
    iVal = i;
}

}

Should be written as:

package com.rule;

class Avoid_Non_Static_Initializer_Blocks
{

Static int iCounter = 0;
int iVal = 0;
int iSr = 0;

Avoid_Non_Static_Initializer_Blocks(int i)
{
    iVal = i;
    assignSr(); //correction
}

private static void assignSr()
{
    iSr = ++iCounter;
}

}

Reference:
Rule 143: Enforce_listener_method_signature

Severity: Medium
Rule: Enfource the standards for the listener methods of bean class.
Reason: Enfource the standards for the listener methods of bean class.

Usage Example:

package com.rule;

import java.awt.event.KeyAdapter;

public class Enforce_listener_method_signature_violation_Bean
{

public void addKeyListener(KeyAdapter kl) // VIOLATION
{
}
public void removeKeyListener(Object kl) // VIOLATION
{
}

}

Should be written as:

package com.rule;

import java.awt.event.KeyAdapter;

public class Enforce_listener_method_signature_correction_Bean
{

public void addKeyListener(KeyListener kl) // CORRECTION
{
}
public void removeKeyListener(KeyListener kl) // CORRECTION
{
}

}

Reference: No references available.
Rule 144: Initialize_All_Local_Variables_At_Declaration

Severity: Low
Rule: All local variables should be initialized in their declaration statement.
Reason: All local variables should be initialized in their declaration statement.

Usage Example:

public class Initialize_LocalVariables_At_Declaration
{

public void foo()
{
    int sum; //VOILATION
    final int[] nums = new int[]{1, 2, 3, 4};

    sum = 0;
    for(int i = 0; i < nums.length; i++)
    {
        sum += nums[i];
    }
}

}

Should be written as:

public class Initialize_LocalVariables_At_Declaration
{

public void foo()
{
    int sum = 0; //CORRECTION
    final int[] nums = new int[]{1, 2, 3, 4};

    sum = 0;
    for(int i = 0; i < nums.length; i++)
    {
        sum += nums[i];
    }
}

}

Reference: http://java.sun.com/docs/codeconv/CodeConventions.pdf
Rule 145: Avoid_abstract_method_call_in_abstract_class_constructor

Severity: Medium
Rule: Avoid calling abstract method from a constructor of an abstract class
Reason: Avoid calling abstract method from a constructor of an abstract class

Usage Example:

package com.rule;

abstract class Avoid_abstract_method_call_in_abstract_class_constructor_violation
{

public Avoid_abstract_method_call_in_abstract_class_constructor_violation()
{
    method();
}

public abstract void method();

}

Should be written as:

package com.rule;

abstract class Avoid_abstract_method_call_in_abstract_class_constructor_violation
{

public Avoid_abstract_method_call_in_abstract_class_constructor_violation()
{
    //method();
}

public abstract void method();

}

Reference: Nigel Warren, Philip Bishop: “Java in Practice - Design Styles and Idioms for Effective Java”. Addison-Wesley, 1999.
Rule 146: Always_use_notifyAll

Severity: Medium
Rule: Use java.lang.Object.notifyAll() instead of java.lang.Object.notify().
Reason: Use java.lang.Object.notifyAll() instead of java.lang.Object.notify().

Usage Example:

package com.rule;

class Always_use_notifyAll_violation
{

public void method()
{
    Object obj = null;
    //...
    //....
    obj.notify();   // VIOLATION
}

}

Should be written as:

package com.rule;

class Always_use_notifyAll_correction
{

public void method()
{   
    Object obj = null;
    //...
    //....
    obj.notifyAll();    // CORRECTION
}

}

Reference: http://www.infospheres.caltech.edu/resources/code_standards/recommendations.html
http://www.javapractices.com/Topic51.cjp
Rule 147: Do_not_change_for_loop_control_variable

Severity: Low
Rule: Do not change value of for loop control variable inside the body of the for loop.
Reason: Do not change value of for loop control variable inside the body of the for loop.

Usage Example:

package com.rule;

public class Do_not_change_for_loop_control_variable_violation
{

public void meth(int iLength)
{
    int[] arr = new int[iLength];
    for(int i = 0;  i<iLength ;  i++)  // Violation
    {
        //...
        if(skipNext)
        {
            i++;
        }
    }
}

}

Should be written as:

Avoid modifying the loop control variable.

Reference: Reference not available.
Rule 148: Avoid_importing_java_lang

Severity: Low
Rule: Avoid importing any classes from the package 'java.lang'.
Reason: Avoid importing any classes from the package 'java.lang'.

Usage Example:

package com.rule;

import java.lang.Integer; // VIOLATION
import java.util.ArrayList;

class Avoid_importing_java_lang_violation
{

private final Integer SIZE = new Integer(10);
private ArrayList al = new ArrayList(SIZE);

public void method()
{
    if(al != null)
    {
        al = null;
    }
}

}

Should be written as:

package com.rule;
//import java.lang.Integer; // CORRECTION
import java.util.ArrayList;

class Avoid_importing_java_lang_correction
{

private final Integer SIZE = new Integer(10);
private ArrayList al = new ArrayList(SIZE);

public void method()
{
    if(al != null)
    {
        al = null;
    }
}

}

Reference: http://java.sun.com/docs/books/jls/second_edition/html/packages.doc.html
Rule 149: Avoid_assignment_to_non_final_static_in_instance_method

Severity: Medium
Rule: Avoid assignment to non final static field in instance method.
Reason: Avoid assignment to non final static field in instance method.

Usage Example:

package com.rule;

public class Avoid_assignment_to_non_final_static_in_instance_method_violation
{

static int x;

public void method(int y)
{
    x = y;      // Violation.
}

}

Should be written as:

Reference: Reference not available.
Rule 150: Avoid_null_argument_in_equals

Severity: Medium
Rule: Avoid passing null argument in equals() method.
Reason: Avoid passing null argument in equals() method.

Usage Example:

package com.rule;

public class Avoid_null_argument_in_equals_violation
{

public void foo(String str)
{
    if(str.equals(null)) //Violation
    {
        //...
    }
}

}

Should be written as:

package com.rule;

public class Avoid_null_argument_in_equals_correction
{

public void foo(String str)
{
    if(str == nul)) //Correction
    {
        //...
    }
}

}

Reference: Reference not available.

你可能感兴趣的:(Java Code Convention Rules)