- 浏览: 936239 次
文章分类
最新评论
-
sunnyhappylg:
网上怎么复制了 这个页面内容这么多 没介绍怎么解决啊
服务器系统及软件常见漏洞 -
数据工厂:
我用JS实现的糗事百科的爬虫源码如下,运行步骤请参考我的git ...
[Python]网络爬虫(八):糗事百科的网络爬虫(v0.2)源码及解析 -
yzg0885:
解决了,谢谢你
Could not create the view: An unexpected exception was thrown. 电脑突然断电,myeclipse非正常关闭,出现错误 -
jjlin00:
楼主好,我今年报考南大软院,能分享计算机综合的资料吗,真心谢谢 ...
2013南京大学软件学院考研有感 -
govy.b:
楼主的资料能分享吗?QQ:282577229
2013南京大学软件学院考研有感
Java Possible Coding Errors
Java Possible Coding Errors
Rulesavailableinthiscategory:
- Use_proper_primitive_type_literals
- Do_not_instantiate_class_before_initializing_static_final_fields
- Do_not_create_threads_using_the_default_empty_run_method
- Avoid_calling_wait_on_Condition_object
- Possible_bug_in_method_invocation_on_an_immutable_object
- Possible_NPE_due_to_earlier_check_against_null
- Possible_overflow_in_average_computation_for_large_numbers
- Avoid_comparing_with_one_to_check_if_number_is_odd
- Possible_bug_in_control_flow_statement
- Remainder_of_32-bit_signed_random_integer_could_be_negative
- Remainder_of_hashCode_could_be_negative
- Possible_ConcurrentModificationException
- Possible_bug_in_the_usage_of_loop_variables
- Avoid_more_than_one_getter_or_setter_per_field
- Possible_null_pointer_exception_during_constructor_execution
- Ensure_boxing_unboxing_correct_behaviour
- Possible_typos_in_wrapper_class
- Always_compare_chars_with_values_within_their_range
- Avoid_using_put_putAll_and_get_methods_for_java.util.Properties_objects
- Avoid_dangling_else_statements
- Avoid_calling_equals_on_unrelated_types
- Avoid_unconditional_wait
- Avoid_waiting_with_two_locks_held
- Avoid_calling_notify_on_unlocked_objects
- Interface_method_conflicts_with_protected_Object_method
- Avoid_using_char_array_in_string_concatenation
- Avoid_calling_wait_on_unlocked_objects
- Avoid_calling_Thread_sleep_with_lock_held
- Avoid_declaring_variables_of_type_ThreadGroup
- Possible_bug_in_assigning_value_to_boolean
- Questionable_Octate_Escape_In_String
- Switch_case_does_not_cover_all_enums
- Invalid_regular_expression_syntax
- Possibly_incorrect_regular_expression_pattern
- Avoid_adding_collection_to_itself
- Always_rethrow_ThreadDeath
- Avoid_possible_typos_in_switch_statement
- Use_System_dot_exit_with_care
- Avoid_wrong_increment_in_for
- Never_call_overridable_method_from_constructor
- Avoid_assigning_values_to_method_parameter
- Avoid_non_Serializable_field_inside_Serializable_Class
- Avoid_serializable_class_extending_a_class_without_a_zero_arg_constructor
- Always_null_pointer_exception
- Possible_null_pointer_exception_passing_null_value_as_method_parameter
- Always_class_cast_exception
- Avoid_calling_applet_methods_relying_on_stubs_in_constructor
- Avoid_double_checked_locking
- Avoid_immediate_dereference_of_readLine
- Result_of_readLine_not_used
- Declare_Runnable_run_as_synchronized
- Avoid_TODO_comments
- Avoid_using_spin_locks
- Avoid_down_casting_to_concrete_collection
- Bad_cast_to_another_abstract_collection
- Avoid_empty_statement
- Avoid_fields_with_closely_similar_names
- Avoid_mutable_exception
- Do_not_cast_to_lower_precision
- Avoid_casting_without_check
- Do_not_cast_integer_division_to_double
- Do_not_cast_integer_multiplication_to_long
- Use_random_nextInt
- Avoid_casting_random_value_to_integer
- Overwritten_increment
- Overwritten_decrement
- Invalid_month_argument
- Do_not_call_run_explicitly
- Avoid_catching_IllegalMonitorStateException
- Always_call_swing_methods_in_swing_event_thread
- Erroneous_use_of_binary_AND_with_ZERO
- Erroneous_use_of_binary_AND
- Declare_Object_as_parameter_for_compareTo_method
- Always_explicitly_initialize_all_fields_in_a_constructor
- Avoid_passing_decimal_literals_to_BigDecimal_constructor
- Use_string_equals_method
- Avoid_circular_initialization_for_static_fields
- Always_ensure_get_set_methods_access_correct_fields
- Declare_fields_of_user-defined_Exception_as_final_or_private
- Avoid_overloading_methods_on_argument_types
- Private_field_is_never_written
- Do_not_call_synchronized_method_from_synchronized_method
- Always_place_literals_first_in_string_comparison
- Avoid_equals_operator_for_decimal_point_values
- Avoid_returning_java_lang_Object
- Avoid_invoking_runFinalizersOnExit
- Avoid_contiguous_non_String_values_during_concatenation
- Conditional_expression_always_evaluates_to_constant_value
- Avoid_accessing_uninitialized_fields_in_constructors
- Avoid_accessing_uninitialized_fields
- Avoid_Serializable_class_having_non_Serializable_parent
- Avoid_comparison_with_float_NaN
- Declare_get_method_synchronized
- Avoid_using_float_or_double
- Avoid_assigning_variable_to_same_variable
- Erroneous_use_of_binary_OR
- Avoid_unsynchronized_lazy_initialization_of_static_field
- Avoid_using_volatile_modifier_for_array
- Avoid_synchronization_on_mutable_field
- Avoid_methods_with_closely_similar_names
- Use_serializable_objects_as_argument
- Do_not_call_methods_that_use_AppletStub
- readResolve_method_should_have_java_lang_Object_as_its_return_type
- Avoid_setSize_in_componentResized
- Avoid_unnecessary_call_to_Math_ceil
- Avoid_unnecessary_call_to_Math_class_method
- Always_use_method_return_values
- Always_check_return_value_of_input_stream_read
- Always_check_return_value_of_input_stream_skip
- Erroneous_indexOf_check
- Calling_equals_of_final_classes
- Possible_infinite_recursion
- Possible_infinite_loop
- instanceOf_will_always_return_false
- Avoid_classes_that_are_not_accessible
- Avoid_rethrowing_an_exception_in_a_catch_clause
- Avoid_initializing_array_dimensions_with_negative_values
- Use_Equals_Instead_Equality_Operator
- Possible_spelling_mistake_while_overriding_method
- Do_not_use_zero_as_index_with_resuset
- Do_not_use_zero_as_index_with_PreparedStatement
- Always_call_wait_inside_while_or_doWhile_loop
- Always_call_Condition_await_inside_a_loop
- Avoid_public_semaphores
- Do_not_call_interrupted_method_on_thread_object
- Avoid_unnecessary_comparison_of_two_null_references
- Avoid_unnecessary_comparison_of_non_null_reference_with_null_reference
- Avoid_unnecessary_comparison_with_int
- Do_not_start_Thread_in_constructor
- Classes_or_interfaces_having_same_name_as_java_file_should_be_public
- Always_ensure_only_one_class_or_interface_has_same_name_as_java_file
- Avoid_returning_this
- Avoid_calling_getResource_on_getClass
- Non_instantiable_class_should_contain_non_private_static_method
- Do_not_override_synchronized_method_with_unsynchronized_method
Rule1:Use_proper_primitive_type_literals
Severity:Medium
Rule:Useproperprimitivetypeliteralswhereeveravailable.
Reason:Useproperprimitivetypeliteralswhereeveravailable.
UsageExample:
packagecom.rule; publicclassUse_proper_primitive_type_literals_violation { publicvoidmethod() { floatf2=0;//VIOLATION } }
Shouldbewrittenas:
packagecom.rule; publicclassUse_proper_primitive_type_literals_correction { publicvoidmethod() { floatf2=0.0f;//CORRECTION } }
Reference:ReferenceNotAvailable.
Rule2:Do_not_instantiate_class_before_initializing_static_final_fields
Severity:Medium
Rule:Creatinganinstanceoftheclassbeforeinitializingstaticfinalfieldscancauseerrors.
Reason:Creatinganinstanceoftheclassbeforeinitializingstaticfinalfieldscancauseerrors.
UsageExample:
packagecom.rule; publicclassDo_not_instantiate_class_before_initializing_static_final_fields_violation { privatestaticfinallongMAX_VALUE; privatestaticDo_not_instantiate_class_before_initializing_static_final_fields_violationinstance; static { instance=newDo_not_instantiate_class_before_initializing_static_final_fields_violation();//VIOLATION MAX_VALUE=1000; } }
Shouldbewrittenas:
packagecom.rule; publicclassDo_not_instantiate_class_before_initializing_static_final_fields_correction { privatestaticfinallongMAX_VALUE; privatestaticDo_not_instantiate_class_before_initializing_static_final_fields_correctioninstance; static { MAX_VALUE=1000; instance=newDo_not_instantiate_class_before_initializing_static_final_fields_correction();//CORRECTION } }
Reference:Noreferenceavailable.
Rule3:Do_not_create_threads_using_the_default_empty_run_method
Severity:High
Rule:Sincethethreadhasnotasktoexecute,itsimplywastestimeanddegradesperformance.
Reason:Sincethethreadhasnotasktoexecute,itsimplywastestimeanddegradesperformance.
UsageExample:
classNoopThreadextendsThread { publicNoopThread() { } publicNoopThread(Strings,ThreadGrouptg) { super(tg,s); } publicNoopThread(Runnabler) { super(r); } publicvoidtest1(){ Threadt=newNoopThread(); t.start(); } publicvoidtest2(){ Threadt=newThread("CoolThread");//VIOLATION t.start(); } publicvoidtest3(){ ThreadGrouptg=newThreadGroup("MyCoolThreadGroup"); Threadt=newThread(tg,"CoolThread");//VIOLATION t.start(); } publicvoidrun() { super.run(); //... } }
Shouldbewrittenas:
classNoopThreadextendsThread { privateRunnabler=null; publicNoopThread() { } publicNoopThread(Strings,ThreadGrouptg) { super(tg,s); } publicNoopThread(Runnabler) { super(r); this.r=r; } publicvoidtest1(){ Threadt=newNoopThread(); t.start(); } publicvoidtest2(){ Threadt=newThread(r,"CoolThread");//FIXED t.start(); } publicvoidtest3(){ ThreadGrouptg=newThreadGroup("MyCoolThreadGroup"); Threadt=newThread(tg,r,"CoolThread");//FIXED t.start(); } publicvoidrun() { super.run(); //... } }
Reference:NotAvailable.
Rule4:Avoid_calling_wait_on_Condition_object
Severity:Medium
Rule:WaitingforaConditionshouldbedoneusingoneoftheawaitmethodsdefinedbytheConditioninterface.
Reason:WaitingforaConditionshouldbedoneusingoneoftheawaitmethodsdefinedbytheConditioninterface.
UsageExample:
importjava.util.concurrent.locks.*; publicclassTest { intx; voidwaitOnCondition(Conditioncond)throwsInterruptedException { while(x==0) { cond.wait();//VIOLATION } } }
Shouldbewrittenas:
importjava.util.concurrent.locks.*; publicclassTest { intx; voidwaitOnCondition(Conditioncond)throwsInterruptedException { while(x==0) { cond.await();//FIXED } } }
Reference:NotAvailable.
Rule5:Possible_bug_in_method_invocation_on_an_immutable_object
Severity:Medium
Rule:Anoperationonanimmutableobjectwon'tchangetheobjectitself.
Reason:Anoperationonanimmutableobjectwon'tchangetheobjectitself.
UsageExample:
importjava.math.*; publicclassTest { voidfubar() { BigDecimalbd=newBigDecimal(10); bd.add(newBigDecimal(5));//VIOLATION } }
Shouldbewrittenas:
importjava.math.*; publicclassTest { voidfubar() { BigDecimalbd=newBigDecimal(10); bd=bd.add(newBigDecimal(5));//FIXED } }
Rule6:Possible_NPE_due_to_earlier_check_against_null
Severity:Medium
Rule:Thevariablereferencedatthispointisknowntobenullduetoanearliercheckagainstnull.
Reason:Thevariablereferencedatthispointisknowntobenullduetoanearliercheckagainstnull.
UsageExample:
publicclassTest { publicvoidfubar() { ObjectnullObject=null; if(nullObject==null) { try { System.out.println("hello"); nullObject="notnull"; } catch(RuntimeExceptionex) { System.out.println(nullObject.getClass());//VIOLATION } } } }
Shouldbewrittenas:
publicclassTest { publicvoidfubar() { ObjectnullObject=null; if(nullObject!=null)//FIXED { try { System.out.println("hello"); nullObject="notnull"; } catch(RuntimeExceptionex) { System.out.println(nullObject.getClass()); } } } }
Reference:NotAvailable.
Rule7:Possible_overflow_in_average_computation_for_large_numbers
Severity:Medium
Rule:Ifthesumofthetwonumbersisgreaterthanthemaximumpositiveintvalue,thenitoverflowstoanegativevalue,andthevaluestaysnegativewhendividedbytwo.
Reason:Ifthesumofthetwonumbersisgreaterthanthemaximumpositiveintvalue,thenitoverflowstoanegativevalue,andthevaluestaysnegativewhendividedbytwo.
UsageExample:
publicclassTest { publicstaticintbinarySearch(int[]a,intkey) { intlow=0; inthigh=a.length-1; while(low<=high) { intmid=(low+high)/2;//VIOLATION intmidVal=a[mid]; if(midVal<key) { low=mid+1; } elseif(midVal>key) { high=mid-1; } else { returnmid;//keyfound } } return-(low+1);//keynotfound. } }
Shouldbewrittenas:
publicclassTest { publicstaticintbinarySearch(int[]a,intkey) { intlow=0; inthigh=a.length-1; while(low<=high) { intmid=(low+high)>>>1;//FIXED intmidVal=a[mid]; if(midVal<key) { low=mid+1; } elseif(midVal>key) { high=mid-1; } else { returnmid;//keyfound } } return-(low+1);//keynotfound. } }
Reference:http://googleresearch.blogspot.com/2006/06/extra-extra-read-all-about-it-nearly.html
Rule8:Avoid_comparing_with_one_to_check_if_number_is_odd
Severity:Medium
Rule:Itwontworkfornegativenumbers.
Reason:Itwontworkfornegativenumbers.
UsageExample:
publicclassTest { publicbooleanisOdd(intx) { returnx%2==1;//VIOLATION } }
Shouldbewrittenas:
publicclassTest { publicbooleanisOdd(intx) { returnx%2!=0;//FIXED } }
Reference:NotAvailable.
Rule9:Possible_bug_in_control_flow_statement
Severity:Medium
Rule:Havinganemptystatementasthebodymighthavenotbeenintended.
Reason:Havinganemptystatementasthebodymighthavenotbeenintended.
UsageExample:
publicclassTest { publicstaticvoidmain(String[]args) { if(args.length==1);//VIOLATION System.out.println(args[0]); } }
Shouldbewrittenas:
publicclassTest { publicstaticvoidmain(String[]args) { if(args.length==1)//FIXED System.out.println(args[0]); } }
Reference:NotAvailable.
Rule10:Remainder_of_32-bit_signed_random_integer_could_be_negative
Severity:Medium
Rule:Pleaseensurethatthepossibilityoftheresultoftheremainderoperationbeingnegativeishandled.
Reason:Pleaseensurethatthepossibilityoftheresultoftheremainderoperationbeingnegativeishandled.
UsageExample:
importjava.security.SecureRandom; importjava.util.Random; classTest { Randomr=newRandom(); SecureRandomsr=newSecureRandom(); publicintgetRandomElement(inta[]) { returna[r.nextInt()%a.length];//VIOLATION } publicintgetSecureRandomElement(inta[]) { returna[sr.nextInt()%a.length];//VIOLATION } }
Shouldbewrittenas:
importjava.security.SecureRandom; importjava.util.Random; classTest { Randomr=newRandom(); SecureRandomsr=newSecureRandom(); publicintgetRandomElement(inta[]) { intindex=r.nextInt()%a.length; if(index!=-1) { returna[index];//FIXED } } publicintgetSecureRandomElement(inta[]) { intindex=sr.nextInt()%a.length; if(index!=-1) { returna[sr.nextInt()%a.length];//FIXED } } }
Reference:NotAvailable.
Rule11:Remainder_of_hashCode_could_be_negative
Severity:Medium
Rule:Pleaseensurethatthepossibilityoftheresultoftheremainderoperationbeingnegativeishandled.
Reason:Pleaseensurethatthepossibilityoftheresultoftheremainderoperationbeingnegativeishandled.
UsageExample:
publicclassTest { publicstaticObjectgetHashBucket(Objecta[],Objectx) { returna[x.hashCode()%a.length];//VIOLATION } publicstaticObjectgetHashBucket2(Objecta[],Objectx) { inti=x.hashCode()%a.length;//VIOLATION returna[i]; } }
Shouldbewrittenas:
publicclassTest { publicstaticObjectgetHashBucket(Objecta[],Objectx) { returna[Math.abs(x.hashCode()%a.length)];//FIXED } publicstaticObjectgetHashBucket2(Objecta[],Objectx) { inti=Math.abs(x.hashCode()%a.length);//FIXED returna[i]; } }
Reference:NotAvailable.
Rule12:Possible_ConcurrentModificationException
Severity:Medium
Rule:PossibilityofaConcurrentModificationExceptiontobethrownatruntime.
Reason:PossibilityofaConcurrentModificationExceptiontobethrownatruntime.
UsageExample:
importjava.util.*; publicclassTest { publicvoidsomeMethod(Collectioncollection) { Iteratoriter=collection.iterator(); while(iter.hasNext()) { Objectelement=iter.next(); collection.remove(element);//VIOLATION } } }
Shouldbewrittenas:
importjava.util.*; publicclassTest { publicvoidsomeMethod(Collectioncollection) { Iteratoriter=collection.iterator(); while(iter.hasNext()) { iter.remove();//FIXED } } }
Reference:NotAvailable.
Rule13:Possible_bug_in_the_usage_of_loop_variables
Severity:High
Rule:Thereisahighprobabilitythatthewrongvariablewasusedintheloop.
Reason:Thereisahighprobabilitythatthewrongvariablewasusedintheloop.
UsageExample:
publicclassTest { publicvoidmyMethod() { int[]a=newint[5]; for(inti=0;i<a.length;i++) { int[]b=newint[5]; for(intj=0;j<b.length;j++) { b[i]=1;//VIOLATION } } for(intj=0;j<a.length;i++)//VIOLATION { System.out.println("Theindexis:"+j); } } }
Shouldbewrittenas:
publicclassTest { publicvoidmyMethod() { int[]a=newint[5]; for(inti=0;i<a.length;i++) { int[]b=newint[5]; for(intj=0;j<b.length;j++) { b[j]=1;//FIXED } } for(intj=0;j<a.length;j++)//FIXED { System.out.println("Theindexis:"+j); } } }
Reference:NotAvailable.
Rule14:Avoid_more_than_one_getter_or_setter_per_field
Severity:Medium
Rule:Itispossiblethatthesecondgetterorsetterwasmeanttoaccessorsetanotherfield.
Reason:Itispossiblethatthesecondgetterorsetterwasmeanttoaccessorsetanotherfield.
UsageExample:
publicclassTest { privateObject_obj,_obj1; publicObjectgetObj() { return_obj; } publicObjectgetObj1(intnum)//VIOLATION { return_obj; } }
Shouldbewrittenas:
publicclassTest { privateObject_obj,_obj1; publicObjectgetObj() { return_obj; } publicObjectgetObj1(intnum) { return_obj1; //FIXED } }
Reference:NotAvailable.
Rule15:Possible_null_pointer_exception_during_constructor_execution
Severity:High
Rule:Violatesonpossiblecasesofmethodinvocationsfromconstructorswhichthrowanullpointerexception.
Reason:Violatesonpossiblecasesofmethodinvocationsfromconstructorswhichthrowanullpointerexception.
UsageExample:
publicclassTest { publicTest() { methodThrowingNPE(); //VIOLATION } protectedvoidmethodThrowingNPE() { //... } } classSubextendsTest { Sub() { //... } protectedvoidmethodThrowingNPE() { Objects=null; inti=2; if(i==3) { s=newObject(); } System.out.println(s.toString()); } }
Shouldbewrittenas:
Reference:Noreferencesavailable.
Rule16:Ensure_boxing_unboxing_correct_behaviour
Severity:MediumRule:Autoboxingcapabilitycanleadtounexpectedbehaviorespeciallywhenpassingarguments.Reason:Autoboxingcapabilitycanleadtounexpectedbehaviorespeciallywhenpassingarguments.
UsageExample:
publicclassTest { publicstaticvoidmain(String[]args) { Integernumber=newInteger(10); newTest().foo(number/10);//VIOLATION } privatevoidfoo(inti) { System.out.println("primitive="+i); } privatevoidfoo(Integeri) { System.out.println("wrapper="+i); } }
Shouldbewrittenas:
Intheabovecodefoo(int)methodwillbecalledandnotfoo(Integer);pleaseensureifthisisexpectedbehaviour.
Reference:NoreferencesAvailable.
Rule17:Possible_typos_in_wrapper_class
Severity:Medium
Rule:Possibletyposinargumentstowrapperclasses.
Reason:Possibletyposinargumentstowrapperclasses.
UsageExample:
publicclassTypos { Integeri=newInteger("15A");//VIOLATION publicBooleanmyMethod() { returnBoolean.valueOf("true");//VIOLATION,wouldreturn"false" } }
Shouldbewrittenas:
publicclassTypos { Integeri=newInteger("10"); //CORRECTION publicBooleanmyMethod() { returnBoolean.valueOf("true");//CORRECTION } }
Reference:Noreferencesavailable.
Rule18:Always_compare_chars_with_values_within_their_range
Severity:Medium
Rule:Iftheconstantisnotwithintherangeofpossible"char"value,thebooleanwouldalwaysresulttotrueorfalse.
Reason:Iftheconstantisnotwithintherangeofpossible"char"value,thebooleanwouldalwaysresulttotrueorfalse.
UsageExample:
publicclassAlwaysCompareCharsWithValuesWithinTheirRange { publicstaticStringgetAsciiString(StringinString) { StringBufferoutStringBuffer=newStringBuffer(); for(inti=0;i<inString.length();i++) { charcurrentChar=inString.charAt(i); if(currentChar>-1&¤tChar<256) //VIOLATION { outStringBuffer.append(currentChar); } } returnoutStringBuffer.toString(); } }
Shouldbewrittenas:
publicclassAlwaysCompareCharsWithValuesWithinTheirRange { publicstaticStringgetAsciiString(StringinString) { StringBufferoutStringBuffer=newStringBuffer(); for(inti=0;i<inString.length();i++) { charcurrentChar=inString.charAt(i); if(currentChar<256) //CORRECTION { outStringBuffer.append(currentChar); } } returnoutStringBuffer.toString(); } }
Reference:
Rule19:Avoid_using_put_putAll_and_get_methods_for_java.util.Properties_objects
Severity:Medium
Rule:Using'put'and'putAll'mightallownon-stringentries,whichshouldbeavoidedandgetPropertydirectlyreturnsastringasareturnvalue.
Reason:Using'put'and'putAll'mightallownon-stringentries,whichshouldbeavoidedandgetPropertydirectlyreturnsastringasareturnvalue.
UsageExample:
publicclassPropClass { java.util.Propertiesproperties=newjava.util.Properties(); publicStringsomeMethod() { properties.put("A","someString");//VIOLATION return(String)properties.get("A");//VIOLATION } }
Shouldbewrittenas:
publicclassPropClass { java.util.Propertiesproperties=newjava.util.Properties(); publicStringsomeMethod() { properties.setProperty("A","someString");//CORRECTION returnproperties.getProperty("A");//CORRECTION } }
Reference:http://java.sun.com/j2se/1.4.2/docs/api/java/util/Properties.html
Rule20:Avoid_dangling_else_statements
Severity:Medium
Rule:Danglingelsestatementleadtoambiguityandpossibleerrorinlogic.
Reason:Danglingelsestatementleadtoambiguityandpossibleerrorinlogic.
UsageExample:
publicclassAvoidDanglingElseStatements { voidmethod() { intnum=23; if(num<24)//VIOLATION:shouldhave"{}"braces if(num<5) num++; else num--; } }
Shouldbewrittenas:
publicclassAvoidDanglingElseStatements { voidmethod() { intnum=23; if(num<24) { //CORRECTION if(num<5) num++; } else { num--; } } }
Reference:Noreferencesavailable.
Rule21:Avoid_calling_equals_on_unrelated_types
Severity:Medium
Rule:Thisequalscomparisonwillalwaysreturnfalse.
Reason:Thisequalscomparisonwillalwaysreturnfalse.
UsageExample:
importjava.util.ArrayList; importjava.util.Collection; importjava.util.Vector; publicclassTest { publicvoidaMethod() { Collectional=newArrayList(); Collectionv=newVector(); if(al.equals(v))//VIOLATION { System.out.println("Neverhere"); } } }
Shouldbewrittenas:
Reference:Noreferencesavailable.
Rule22:Avoid_unconditional_wait
Severity:MediumRule:Thecalltojava.lang.Object.wait()isnotwithinaconditionalcontrolflow.Reason:Thecalltojava.lang.Object.wait()isnotwithinaconditionalcontrolflow.
UsageExample:
publicclassTest { voidclueless()throwsException { synchronized(this) { this.wait();//VIOLATION } } }
Shouldbewrittenas:
Reference:Noreferencesavailable.
Rule23:Avoid_waiting_with_two_locks_held
Severity:MediumRule:Avoidwaitingonamonitorwhiletwolocksareheld.Reason:Avoidwaitingonamonitorwhiletwolocksareheld.
UsageExample:
publicclassTest { Objectlock=newObject(); Objectvalue; publicsynchronizedvoidnotifyMethod(Objectv) { synchronized(lock) { value=v; lock.notifyAll(); } } publicsynchronizedObjectwaitMethod()throwsInterruptedException { synchronized(lock) { while(value==null) { lock.wait();//VIOLATION } returnvalue; } } publicvoidsomeMethod(Objecta,Objectb) { try { synchronized(a) { synchronized(b) { a.wait();//VIOLATION } } }catch(InterruptedExceptione) { System.out.println("Interrupted"); } } }
Shouldbewrittenas:
Reference:Noreferencesavailable.
Rule24:Avoid_calling_notify_on_unlocked_objects
Severity:CriticalRule:Thismethodcallsnotify()ornotifyAll()withoutobviouslyholdingalockontheobject.Reason:Thismethodcallsnotify()ornotifyAll()withoutobviouslyholdingalockontheobject.
UsageExample:
publicclassTest { publicvoidbar(Objecta,Objectb)throwsInterruptedException{ synchronized(a){ b.notify();//VIOLATION b.notifyAll();//VIOLATION } } }
Shouldbewrittenas:
publicclassTest { publicvoidbar(Objecta,Objectb)throwsInterruptedException{ synchronized(b){ b.notify(); b.notifyAll(); } } }
Reference:Noreferencesavailable.
Rule25:Interface_method_conflicts_with_protected_Object_method
Severity:Critical
Rule:ThisinterfacehasamethodwhichisincompatiblewiththeprotectedObjectmethod.
Reason:ThisinterfacehasamethodwhichisincompatiblewiththeprotectedObjectmethod.
UsageExample:
interfacesomeInterface { intclone();//VIOLATION }
Shouldbewrittenas:
Reference:Noreferencesavailable.
Rule26:Avoid_using_char_array_in_string_concatenation
Severity:CriticalRule:ThechararrayisnotconvertedtoanequivalentString.Reason:ThechararrayisnotconvertedtoanequivalentString.
UsageExample:
publicclassTest { publicvoidaMethod() { Stringh="hello"; char[]arr={'w','o','r','l','d'}; Stringmsg=h+""+arr;//VIOLATION } }
Shouldbewrittenas:
publicclassTest { publicvoidaMethod() { Stringh="hello"; char[]arr={'w','o','r','l','d'}; Stringworld=String.valueOf(arr); Stringmsg=h+""+world; } }
Reference:Noreferencesavailable.
Rule27:Avoid_calling_wait_on_unlocked_objects
Severity:Critical
Rule:Thismethodcallswait()withoutobviouslyholdingalockontheobject.
Reason:Thismethodcallswait()withoutobviouslyholdingalockontheobject.
UsageExample:
publicclassTest { publicvoidfoo(Objecta,Objectb)throwsInterruptedException { synchronized(a) { b.wait();//VIOLATION } } }
Shouldbewrittenas:
Reference:Noreferencesavailable.
Rule28:Avoid_calling_Thread_sleep_with_lock_held
Severity:MediumRule:AvoidcallingThread.sleep(),whilelockheld.Reason:AvoidcallingThread.sleep(),whilelockheld.
UsageExample:
packagecom.rule; publicclassAvoid_calling_Thread_sleep_with_lock_held_violation { publicsynchronizedvoidmethod() { longtime=100000; try { Thread.sleep(time); //Violation. } catch(InterruptedExceptione) { //HandleException. } } }
Shouldbewrittenas:
packagecom.rule; publicclassAvoid_calling_Thread_sleep_with_lock_held_correction { publicsynchronizedvoidmethod() { try { wait();//Correction. } catch(InterruptedExceptione) { //HandleException. } } }
Reference:Referencenotavailable.
Rule29:Avoid_declaring_variables_of_type_ThreadGroup
Severity:Medium
Rule:AvoiddeclaringvariablesoftypeThreadGroup
Reason:AvoiddeclaringvariablesoftypeThreadGroup
UsageExample:
publicclassThreadGroupTest { publicstaticvoidmain(String[]args) { ThreadGroupsquares=newThreadGroup("Squares");//VIOLATION Threadt1=newThread(squares,newT(),"t1"); Threadt2=newThread(squares,newT(),"t2"); t1.start(); t2.start(); System.out.println("ThreadGroupnameis:"+squares.getName()); System.out.println("Therearecurrently"+squares.activeCount()+"threadsrunning"); System.out.println("ThemaximumpriorityofaThreadthatcanbecontained within"+squares.getName()+"is"+squares.getMaxPriority()); System.out.println("Therearecurrently"+squares.activeGroupCount()+"activegroups"); System.out.println(squares.getName()+"parentis"+squares.getParent()); } } classTimplementsRunnable { privateintsquare; publicvoidrun() { for(inti=1;i<5;i++) { square=i*i; System.out.println("Thread"+Thread.currentThread().getName()+ "hasapriorityof"+Thread.currentThread().getPriority()+ ":"+square); } } }
Shouldbewrittenas:
AvoidusingThreadGroup.
Reference:JoshuaBloch:"EffectiveJava-ProgrammingLanguageGuide"
Rule30:Possible_bug_in_assigning_value_to_boolean
Severity:Low
Rule:Mostprobablythiswassupposedtobeabooleancomparisonusing==,notanassignmentusing=
Reason:Mostprobablythiswassupposedtobeabooleancomparisonusing==,notanassignmentusing=
UsageExample:
classTest { publicvoidtest1(booleanb) { if(b=true)//VIOLATION { System.out.println("Hi"); } } publicvoidtest2(inta,intb,intc,intd,booleane) { if(e=false)//VIOLATION { System.out.println("Hi"); } } publicvoidtest3(booleanb) { while(b=true)//VIOLATION { System.out.println("Wow"); } } }
Shouldbewrittenas:
classTest { publicvoidtest1(booleanb) { if(b)//FIXED { System.out.println("Hi"); } } publicvoidtest2(inta,intb,intc,intd,booleane) { if(!e)//FIXED { System.out.println("Hi"); } } publicvoidtest3(booleanb) { while(b)//FIXED { System.out.println("Wow"); } } }
Reference:NotAvailable.
Rule31:Questionable_Octate_Escape_In_String
Severity:High
Rule:AvoidquestionableuseofOctateEscapeInString
Reason:AvoidquestionableuseofOctateEscapeInString
UsageExample:
packagecom.rule; classQuestionable_Octate_Escape_In_String_violation { publicvoidmethod() { Stringstr="Allowed:\012"; Stringstr1="Allowed:\377"; System.out.println("suspicious:\128"); //Violation. Stringstr2="suspicious:\318\013"; //Violation. Stringstr3="suspicious:\013\318"; //Violation. } }
Shouldbewrittenas:
Reference:Noreferenceavailable
Rule32:Switch_case_does_not_cover_all_enums
Severity:HighRule:Thecompilercanoptionallyflagincompleteenumswitchstatements.Reason:Thecompilercanoptionallyflagincompleteenumswitchstatements.
UsageExample:
publicclassBadSwitch { voidfubar(Colorsc) { switch(c)//VIOLATION { caseBLUE: caseWHITE: { //.... break; } } } } enumColors { BLUE,WHITE,RED; }
Shouldbewrittenas:
publicclassBadSwitch { voidfubar(Colorsc) { switch(c)//FIXED { caseRED: { //.. break; } caseBLUE: caseWHITE: { //.... break; } } } } enumColors { BLUE,WHITE,RED; }
Reference:Noreferenceavailable.
Rule33:Invalid_regular_expression_syntax
Severity:High
Rule:Thesyntaxoftheregularexpressionisinvalid.
Reason:Thesyntaxoftheregularexpressionisinvalid.
UsageExample:
importjava.util.regex.*; publicclassWillThrowPatternSyntaxException { voidx(Strings)throwsException { Pattern.matches("][",s);//VIOLATION } }
Shouldbewrittenas:
Pleaseverifytheregexpattern.
Reference:Noreferencesavailable.
Rule34:Possibly_incorrect_regular_expression_pattern
Severity:High
Rule:AStringfunctionisbeinginvokedand"."isbeingpassedtoaparameterthattakesaregularexpressionasanargument.
Reason:AStringfunctionisbeinginvokedand"."isbeingpassedtoaparameterthattakesaregularexpressionasanargument.
UsageExample:
publicclassTest { publicvoidfubar(Strings) { s.replaceAll(".","/");//VIOLATION } }
Shouldbewrittenas:
Pleaseensurethisisintended.
Reference:NotAvailable.
Rule35:Avoid_adding_collection_to_itself
Severity:High
Rule:Avoidaddingacollectiontoitself.
Reason:Avoidaddingacollectiontoitself.
UsageExample:
packagecom.rule; importjava.util.ArrayList; importjava.util.Collection; publicclassAvoid_adding_collection_to_itself_violation { publicvoidmethod() { Collectionc=newArrayList(); c.add("Item1"); c.add("Item2"); c.addAll(c); //Violation. } }
Shouldbewrittenas:
Reference:Referencenotavailable.
Rule36:Always_rethrow_ThreadDeath
Severity:MediumRule:AlwaysrethrowThreadDeathError.Reason:AlwaysrethrowThreadDeathError.
UsageExample:
packagecom.rule; /** *@authorAdministrator * */ publicclassAlways_rethrow_ThreadDeath_violation { publicstaticvoidmain(Stringargs[]) { newThread() { publicvoidrun() { run1(); } privatevoidrun1() { for(inti=0;i<100;i++) { try { doStop(i); } catch(ThreadDeathth)//Violation { System.out.println("th.getClass()="+th.getClass()); th.printStackTrace(); } System.out.println("i="+i); } } privatevoiddoStop(inti) { if(i==5) stop(); } }.start(); } }
Shouldbewrittenas:
packagecom.rule; publicclassAlways_rethrow_ThreadDeath_correction { publicstaticvoidmain(Stringargs[]) { newThread() { publicvoidrun() { run1(); } privatevoidrun1() { for(inti=0;i<100;i++) { try { doStop(i); } catch(ThreadDeathth) { System.out.println("th.getClass()="+th.getClass()); th.printStackTrace(); throwth;//Correction } System.out.println("i="+i); } } privatevoiddoStop(inti) { if(i==5) stop(); } }.start(); } }
Reference:http://java.sun.com/j2se/1.4.2/docs/api/java/lang/ThreadDeath.html
Rule37:Avoid_possible_typos_in_switch_statement
Severity:Medium
Rule:Labelsshouldnotappearinswitchstatementsbecausetheywillnotbeused.
Reason:Labelsshouldnotappearinswitchstatementsbecausetheywillnotbeused.
UsageExample:
publicclassMyClass { staticintmethod(inti){ switch(i){ case4: case3://VIOLATION:labeltypo i++; break; case25: unusedlabel://VIOLATION:unusedlabel. break; } returni; } }
Shouldbewrittenas:
publicclassMyClass { staticintmethod(inti){ switch(i){ case4: case3://CORRECTION i++; break; case25: //CORRECTION break; } returni; } }
Reference:Noreferencesavailable.
Rule38:Use_System_dot_exit_with_care
Severity:High
Rule:UseSystem.exitwithcare.
Reason:UseSystem.exitwithcare.
UsageExample:
packagecom.rule; publicclassUse_System_dot_exit_with_care_violation { publicstaticvoidmain(String[]s) { intia[]={1,2,3,4,5,6,7,8,9,10,11,12,13}; (newThreadDoSum(ia)).start(); System.exit(0);//Violation } } classThreadDoSumextendsThread { int[]ia=null; publicThreadDoSum(intia[]) { this.ia=ia; } publicvoidrun() { intsum=0; for(inti=0;i<ia.length;i++) { sum+=ia[i]; } System.out.println(sum); } }
Shouldbewrittenas:
packagecom.rule; publicclassUse_System_dot_exit_with_care_correction { publicstaticvoidmain(String[]s) { intia[]={1,2,3,4,5,6,7,8,9,10,11,12,13}; (newThreadDoSum(ia)).start(); return;//Correction } } classThreadDoSumextendsThread { int[]ia=null; publicThreadDoSum(intia[]) { this.ia=ia; } publicvoidrun() { intsum=0; for(inti=0;i<ia.length;i++) { sum+=ia[i]; } System.out.println(sum); } }
Reference:http://www.javapractices.com/Topic86.cjp
http://www.devx.com/tips/Tip/14560
Rule39:Avoid_wrong_increment_in_for
Severity:Medium
Rule:Avoidwrongincrementinforloop.
Reason:Avoidwrongincrementinforloop.
UsageExample:
packagecom.rule; classAvoid_wrong_increment_in_for_violation { publicvoidmethod() { intarray[]={10,20,30,40}; intlength=array.length; intj=0; for(inti=0;i<length;j++) //Violation. { //SomeCode... } } }
Shouldbewrittenas:
packagecom.rule; classAvoid_wrong_increment_in_for_Correction { publicvoidmethod() { intarray[]={10,20,30,40}; intlength=array.length; for(inti=0;i<length;i++) //Correction. { //SomeCode... } } }
Reference:Referencenotavailable.
Rule40:Never_call_overridable_method_from_constructor
Severity:High
Rule:Nevercalloverridablemethodfromconstructor.
Reason:Nevercalloverridablemethodfromconstructor.
UsageExample:
publicclassNever_call_overridable_method_from_constructor_violation { publicstaticvoidmain(String[]a) { Childc=newChild(); System.out.println(c.type);//isnulleventhoughChild'sinititlize()wasexecuted. } publicNever_call_overridable_method_from_constructor_violation() { inititlize();//Violation } publicvoidinititlize() { } } classChildextendsNever_call_overridable_method_from_constructor_violation { publicStringtype=null; publicChild() { super(); } publicvoidinititlize() { type="CHART"; } }
Shouldbewrittenas:
Donotcalloverridablemethodinsideconstructor.
Reference:http://www.javapractices.com/Topic11.cjp
Rule41:Avoid_assigning_values_to_method_parameter
Severity:High
Rule:Itcanleadtopossibleerrors.
Reason:Itcanleadtopossibleerrors.
UsageExample:
publicclassTest { publicvoidmethod(int[]a) { a[0]=0;//VIOLATION } }
Shouldbewrittenas:
publicclassTest { publicvoidmethod(int[]a) { finalintlen=a.length; int[]b=newint[len]; System.arraycopy(a,0,b,0,len); b[0]=0;//FIXED } }
Reference:Notavailable.
Rule42:Avoid_non_Serializable_field_inside_Serializable_Class
Severity:Critical
Rule:Avoidnon-SerializableandnonprimitiveinstancefieldinsideSerializableclass.
Reason:Avoidnon-SerializableandnonprimitiveinstancefieldinsideSerializableclass.
UsageExample:
packagecom.rule; importjava.io.*; publicclassAvoid_non_Serializable_field_inside_Serializable_class_violationimplementsSerializable { MyClassmc=newMyClass();//Violation privateintiNum=90; publicstaticvoidmain(Stringargs[])throwsIOException { FileOutputStreamout=newFileOutputStream("Test"); ObjectOutputStreamoos=newObjectOutputStream(out); oos.writeObject(newAvoid_non_Serializable_field_inside_Serializable_class_violation()); oos.flush(); } } classMyClass { intj=89; }
Shouldbewrittenas:
AvoidnonSerializablefieldinsideSerializableclass.
Reference:Referencenotavailable.
Rule43:Avoid_serializable_class_extending_a_class_without_a_zero_arg_constructor
Severity:Critical
Rule:Ifanynon-serializablesuperclassesdon'thaveazero-argumentconstructor,serializationwillfail.
Reason:Ifanynon-serializablesuperclassesdon'thaveazero-argumentconstructor,serializationwillfail.
UsageExample:
publicclassSomeClassimplementsjava.io.Serializable extendsSuperClass//VIOLATION { SomeClass() { super(0); } } classSuperClass { SuperClass(inti){} }
Shouldbewrittenas:
publicclassSomeClassimplementsjava.io.Serializable extendsSuperClass { SomeClass() { super(0); } } classSuperClass { SuperClass(inti){} SuperClass(){}//CORRECTION }
Reference:Noreferencesavailable.
Rule44:Always_null_pointer_exception
Severity:Critical
Rule:Thiscodewoulddefinitelythrowajava.lang.NullPointerException.
Reason:Thiscodewoulddefinitelythrowajava.lang.NullPointerException.
UsageExample:
publicclassErroneous_null_check_violation { publicvoidaMethod() { Objectx=newObject(); if(x==null) { System.out.println(x.toString());//VIOLATION } } }
Shouldbewrittenas:
Reference:Referencenotavailable.
Rule45:Possible_null_pointer_exception_passing_null_value_as_method_parameter
Severity:CriticalRule:Apossibly-nullvalueispassedtoamethodwhichunconditionallydereferencesitresultinginanullpointerexception.Reason:Apossibly-nullvalueispassedtoamethodwhichunconditionallydereferencesitresultinginanullpointerexception.
UsageExample:
publicclassTest { publicvoidfubar() { Objects=null; //... System.out.println(getStringRepresentation(s));//VIOLATION } privateStringgetStringRepresentation(Objects) { returns.toString(); } }
Shouldbewrittenas:
publicclassTest { publicvoidfubar() { Objects=null; //... System.out.println(getStringRepresentation(s)); } privateStringgetStringRepresentation(Objects) { returns!=null?s.toString():"";//FIXED } }
Reference:NotAvailable.
Rule46:Always_class_cast_exception
Severity:Critical
Rule:Thiscodewoulddefinitelythrowajava.lang.ClassCastException.
Reason:Thiscodewoulddefinitelythrowajava.lang.ClassCastException.
UsageExample:
importjava.util.Hashtable; importjava.util.Vector; publicclassTest { Hashtablebaz() { returnnewHashtable(); } Vector[]faz() { returnnewVector[10]; } intf2() { Objecto=faz(); return((Hashtable[])o).length;//VIOLATION } inthx() { Objecto=baz(); return((Vector)o).size();//VIOLATION } }
Shouldbewrittenas:
Reference:Noreferencesavailable.
Rule47:Avoid_calling_applet_methods_relying_on_stubs_in_constructor
Severity:CriticalRule:ThiscodeintheconstructorcallsmethodsintheparentAppletthatrelyontheAppletstub.Reason:ThiscodeintheconstructorcallsmethodsintheparentAppletthatrelyontheAppletstub.
UsageExample:
importjava.applet.Applet; importjava.net.URL; publicclassTestextendsApplet { publicTest() { URLu1=getDocumentBase();//VIOLATION URLu2=getCodeBase();//VIOLATION if(u1.equals(u2)) return; if(getParameter("bad")!=null)//VIOLATION return; if(getAppletContext()!=null)//VIOLATION return; } }
Shouldbewrittenas:
Reference:Noreferencesavailable.
Rule48:Avoid_double_checked_locking
Severity:CriticalRule:Avoiddoublecheckedlocking.Reason:Avoiddoublecheckedlocking.
UsageExample:
packagecom.rule; publicclassAvoid_double_checked_locking { ObjectobjOne=null; if(objOne==null) { synchronized(this) { if(objOne==null) //Violation. { objOne=null; } } } }
Shouldbewrittenas:
Reference:http://www.javaworld.com/javaworld/jw-02-2001/jw-0209-double.html.
Rule49:Avoid_immediate_dereference_of_readLine
Severity:MediumRule:AvoidimmediatedereferenceofresultofreadLine()method.Reason:AvoidimmediatedereferenceofresultofreadLine()method.
UsageExample:
packagecom.rule; importjava.io.BufferedReader; importjava.io.IOException; importjava.io.FileReader; classAvoid_immediate_dereference_of_readLine_violation { publicvoidmethod() { BufferedReaderin=newBufferedReader(newFileReader("InputFile.txt")); if(in.readLine().equals("AppPerfect")) //Violation { //SomeCode... } } }
Shouldbewrittenas:
packagecom.rule; importjava.io.BufferedReader; importjava.io.IOException; importjava.io.FileReader; classAvoid_immediate_dereference_of_readLine_Correction { publicvoidmethod() { BufferedReaderin=newBufferedReader(newFileReader("InputFile.txt")); Stringstr=in.readLine(); if(str!=null) { if(str.equals("AppPerfect")) //Correction { //SomeCode... } } } }
Reference:Referencenotavailable.
Rule50:Result_of_readLine_not_used
Severity:Medium
Rule:ResultofreadLine()isnotused.
Reason:ResultofreadLine()isnotused.
UsageExample:
packagecom.rule; importjava.io.BufferedReader; importjava.io.IOException; importjava.io.FileReader; publicclassResult_of_readLine_not_used_violation { publicvoidmethod() { BufferedReaderin=newBufferedReader(newFileReader("InputFile.txt")); Stringstr=null; if(in.readLine()!=null) //Violation { str=in.readLine(); } } }
Shouldbewrittenas:
packagecom.rule; importjava.io.BufferedReader; importjava.io.IOException; importjava.io.FileReader; publicclassResult_of_readLine_not_used_correction { publicvoidmethod() { BufferedReaderin=newBufferedReader(newFileReader("InputFile.txt")); Stringstr=null; if((str=in.readLine())!=null) //Correction. { str; } } }
Reference:Referencenotavailable.
Rule51:Declare_Runnable_run_as_synchronized
Severity:Low
Rule:Therunmethodshouldbedeclaredassynchronized.
Reason:Therunmethodshouldbedeclaredassynchronized.
UsageExample:
packagecom.rule; publicclassDeclare_Runnable_run_as_synchronized_violationimplementsRunnable { publicvoidrun()//VIOLATION { System.out.println("Declare_Runnable_run_as_synchronized_violation.run()"); } }
Shouldbewrittenas:
packagecom.rule; publicclassDeclare_Runnable_run_as_synchronized_correctionimplementsRunnable { publicsynchronizedvoidrun()//CORRECTION { System.out.println("Declare_Runnable_run_as_synchronized_correction.run()"); } }
Reference:Noreferenceavailable.
Rule52:Avoid_TODO_comments
Severity:Low
Rule:TODOcommentsleftinthecodecouldindicatethattheimplementationisincompleteorsomebugneedstobefixed.
Reason:TODOcommentsleftinthecodecouldindicatethattheimplementationisincompleteorsomebugneedstobefixed.
UsageExample:
publicclassMyClass { publicvoidmyMethod() { //TODOAuto-generatedmethodstub//VIOLATION } }
Shouldbewrittenas:
publicclassMyClass { publicvoidmyMethod() { //... //FIXED,TODOcommentisremoved } }
Reference:Notavailable.
Rule53:Avoid_using_spin_locks
Severity:Low
Rule:Avoidusingprimitivespinlocks.
Reason:Avoidusingprimitivespinlocks.
UsageExample:
publicclassTest { booleanflag; voidwaitForTrue() { for(;flag;);//VIOLATION } Testfoo; Testbar; voidwaitForNonNull() { while(foo==null);//VIOLATION } staticvoidwaitForNonNullIndirect(intx,Testbaz) { while(baz.foo==null);//VIOLATION while(baz.foo.bar==null);//VIOLATION } staticbooleansflag; staticvoidwaitForStatic() { do { }while(!sflag);//VIOLATION } }
Shouldbewrittenas:
Reference:Noreferencesavailable.
Rule54:Avoid_down_casting_to_concrete_collection
Severity:HighRule:Avoiddowncastingtoconcretecollection.Reason:Avoiddowncastingtoconcretecollection.
UsageExample:
publicclassTest { Lista; publicVectorswap(Listb) { Vectorv=(Vector)a; a=(Vector)b;//VIOLATION returnv; } }
Shouldbewrittenas:
Reference:Noreferencesavailable.
Rule55:Bad_cast_to_another_abstract_collection
Severity:HighRule:Avoidcastingjava.util.Collectionorjava.util.Iterabletoanotherabstractcollection.Reason:Avoidcastingjava.util.Collectionorjava.util.Iterabletoanotherabstractcollection.
UsageExample:
importjava.util.Hashtable; importjava.util.Map; importjava.util.Set; publicclassTest { Mapbar() { returnnewHashtable(); } intd() { Mapm=bar(); Sets=(Set)m.values();//VIOLATION returns.size(); } }
Shouldbewrittenas:
Reference:Noreferencesavailable.
Rule56:Avoid_empty_statement
Severity:MediumRule:DonotuseemptystatementsReason:Donotuseemptystatements
UsageExample:
packagecom.rule; publicclassAvoid_empty_statement { publicvoidsaveAndExit(booleanbExit) { for(i=0;i<fileCount;saveFile(i++)); //violation if(bExit) { exitEditor(); }; //Violation } }
Shouldbewrittenas:
packagecom.rule; publicclassAvoid_empty_statement { publicvoidsaveAndExit() { for(i=0;i<fileCount;saveFile(i++)) { //Correction } if(bExit) { exitEditor(); } //Correction } }
Reference:http://www.faqs.org/docs/javap/c3/s6.html
Rule57:Avoid_fields_with_closely_similar_names
Severity:Low
Rule:Avoidfieldswithcloselysimilarnames
Reason:Avoidfieldswithcloselysimilarnames
UsageExample:
packagecom.rule; publicclassAvoid_fields_with_closely_similar_names_violation { intfield; intField;//VIOLATION }
Shouldbewrittenas:
packagecom.rule; publicclassAvoid_fields_with_closely_similar_names_correction { intfield1; intfield2;//CORRECTION }
Reference:Referencenotavailable.
Rule58:Avoid_mutable_exception
Severity:Low
Rule:Fieldsaremutable.
Reason:Fieldsaremutable.
UsageExample:
publicclasssomeExceptionextendsException { privateStringmessage;//VIOLATION publicsomeException(Stringmessage) { //... } }
Shouldbewrittenas:
publicclasssomeExceptionextendsException { privatefinalStringmessage; publicsomeException(Stringmessage) { //... } }
Reference:Noreferencesavailable.
Rule59:Do_not_cast_to_lower_precision
Severity:Medium
Rule:Avoidcastingprimitivetypestolowerprecisiondatatypes.
Reason:Avoidcastingprimitivetypestolowerprecisiondatatypes.
UsageExample:
packagecom.rule; publicclassDo_not_cast_to_lower_precision { voidmethod(longl,doubled,floatf,Stringstr) { shorts=(short)l; //VIOLATION inti=s; i=(int)f; //VIOLATION f=(float)d; //VIOLATION method((byte)i); Objectobj=(Object)str; } voidmethod(byteb) { } }
Shouldbewrittenas:
Tryusingdatatypesofproperprecision.
Reference:ReferenceNotAvailable.
Rule60:Avoid_casting_without_check
Severity:Medium
Rule:Thiscodecouldpossiblythrowajava.lang.ClassCastException.
Reason:Thiscodecouldpossiblythrowajava.lang.ClassCastException.
UsageExample:
importjava.util.ArrayList; importjava.util.Collection; importjava.util.List; importjava.util.Vector; publicclassTest { publicstaticvoidmain(String[]args) { Collectionh=newArrayList(); inti=2; if(i==3) { h=newVector(); } Listj=(Vector)h;//VIOLATION if(hinstanceofArrayList) { j=(ArrayList)h; } } }
Shouldbewrittenas:
Reference:Noreferencesavailable.
Rule61:Do_not_cast_integer_division_to_double
Severity:MediumRule:Donotcastresultofintegerdivisiontoadouble.Reason:Donotcastresultofintegerdivisiontoadouble.
UsageExample:
packagecom.rule; classDo_not_cast_integer_division_to_double_violation { publicvoidmethod() { intx=2; inty=5; doublevalue1=x/y; //Violation. } }
Shouldbewrittenas:
packagecom.rule; classDo_not_cast_integer_division_to_double_Correction { publicvoidmethod() { intx=2; inty=5; doublevalue1=(double)x/y; //Correction. } }
Reference:Referencenotavailable.
Rule62:Do_not_cast_integer_multiplication_to_long
Severity:Medium
Rule:Ifthemultiplicationisdoneusinglongarithmetic,youcanavoidthepossibilitythattheresultwilloverflow.
Reason:Ifthemultiplicationisdoneusinglongarithmetic,youcanavoidthepossibilitythattheresultwilloverflow.
UsageExample:
publicclassTest { longconvertDaysToMilliseconds(intdays) { return1000*3600*24*days;//VIOLATION } }
Shouldbewrittenas:
publicclassTest { staticfinallongMILLISECONDS_PER_DAY=24L*3600*1000;//FIXED longconvertDaysToMilliseconds(intdays) { returndays*MILLISECONDS_PER_DAY; } }
Reference:NotAvailable.
Rule63:Use_random_nextInt
Severity:Medium
Rule:Userandom.nextInt()insteadof(int)(random.nextDouble()).
Reason:Userandom.nextInt()insteadof(int)(random.nextDouble()).
UsageExample:
packagecom.rule; importjava.util.Random; publicclassUse_random_nextInt_violation { publicvoidmethod() { Randomr=newRandom(); inti=(int)(r.nextDouble()*100); //Violation. } }
Shouldbewrittenas:
packagecom.rule; importjava.util.Random; publicclassUse_random_nextInt_correction { publicvoidmethod() { Randomr=newRandom(); inti=r.nextInt(100); //Corection. } }
Reference:Referencenotavailable.
Rule64:Avoid_casting_random_value_to_integer
Severity:Medium
Rule:Avoidcastingrandomvaluefrom0to1tointegerbeforeitsuse.
Reason:Avoidcastingrandomvaluefrom0to1tointegerbeforeitsuse.
UsageExample:
importjava.util.Random; publicclassAvoid_casting_random_value_to_integer_violation { publicvoidmethod() { Randomr=newRandom(3); inti=(int)r.nextFloat();//Violation. } }
Shouldbewrittenas:
importjava.util.Random; publicclassAvoid_casting_random_value_to_integer_violation { publicvoidmethod() { Randomr=newRandom(); inti=r.nextInt(3); } }
Reference:http://java.sun.com/developer/JDCTechTips/2001/tt0925.html#tip1
Rule65:Overwritten_increment
Severity:Medium
Rule:Avoidoverwritingtheincrementofavariable.
Reason:Avoidoverwritingtheincrementofavariable.
UsageExample:
packagecom.rule; publicclassOverwritten_increment_violation { publicvoidmethod() { inti=10; i=i++; //Violation. } }
Shouldbewrittenas:
packagecom.rule; publicclassOverwritten_increment_correction { publicvoidmethod() { inti=10; i++; //Correction. } }
Reference:Referencenotavailable.
Rule66:Overwritten_decrement
Severity:Medium
Rule:Avoidoverwritingthedecrementofavariable.
Reason:Avoidoverwritingthedecrementofavariable.
UsageExample:
packagecom.rule; publicclassOverwritten_decrement_violation { publicvoidmethod() { inti=10; i=i--; //Violation. } }
Shouldbewrittenas:
packagecom.rule; publicclassOverwritten_decrement_correction { publicvoidmethod() { inti=10; i--; //Correction. } }
Reference:Referencenotavailable.
Rule67:Invalid_month_argument
Severity:Medium
Rule:Avoidpassingwrongmonthvalue.
Reason:Avoidpassingwrongmonthvalue.
UsageExample:
packagecom.rule; importjava.util.Date; importjava.util.Calendar; importjava.util.GregorianCalendar; publicclassInvalid_month_argument_violation { publicvoidmethod() { Datedate=newDate(); date.setMonth(12); //Violation. Calendarcal=newGregorianCalendar(); cal.set(Calendar.MONTH,14); //Violation. } }
Shouldbewrittenas:
packagecom.rule; importjava.util.Date; importjava.util.Calendar; importjava.util.GregorianCalendar; publicclassInvalid_month_argument_correction { publicvoidmethod() { Datedate=newDate(); date.setMonth(0); //Correction Calendarcal=newGregorianCalendar(); cal.set(Calendar.MONTH,2); //Correction } }
Reference:Referencenotavailable.
Rule68:Do_not_call_run_explicitly
Severity:High
Rule:CallingrunmethodofRunnableobjectdirectlywillnotcreateanewthread.
Reason:CallingrunmethodofRunnableobjectdirectlywillnotcreateanewthread.
UsageExample:
packagecom.rule; publicclassDo_not_call_run_explicitly_violation { publicvoidmethod(Do_not_call_run_explicitly_violation1obj) { obj.run();//VIOLATION } } classDo_not_call_run_explicitly_violation1implementsRunnable { publicvoidrun() { } }
Shouldbewrittenas:
packagecom.rule; publicclassDo_not_call_run_explicitly_correction { publicvoidmethod(Do_not_call_run_explicitly_violation1obj) { newThread(obj).start();//CORRECTION } } classDo_not_call_run_explicitly_violation1implementsRunnable { publicvoidrun() { } }
Reference:http://java.sun.com/j2se/1.4.2/docs/api/java/lang/Runnable.html
http://java.sun.com/j2se/1.4.2/docs/api/java/lang/Thread.html
Rule69:Avoid_catching_IllegalMonitorStateException
Severity:Medium
Rule:CatchingIllegalMonitorStateExceptionrepresentsalogicalerrorinthecode.
Reason:CatchingIllegalMonitorStateExceptionrepresentsalogicalerrorinthecode.
UsageExample:
packagecom.rule; publicclassAvoid_catching_IllegalMonitorStateException_violation { publicvoidmethod(Objectobj) { try { obj.wait(1000); } catch(InterruptedExceptione) { e.printStackTrace(); } catch(IllegalMonitorStateExceptione)//VIOLATION { e.printStackTrace(); } } }
Shouldbewrittenas:
packagecom.rule; publicclassAvoid_catching_IllegalMonitorStateException_correction { publicvoidmethod(Objectobj) { try { //usepropersynchronization synchronized(obj)//CORRECTION { obj.wait(1000); } } catch(InterruptedExceptione) { e.printStackTrace(); } } }
Reference:NoReferenceavailable.
Rule70:Always_call_swing_methods_in_swing_event_thread
Severity:Medium
Rule:Certainswingmethodsshouldonlybecalledinswingeventthread.
Reason:Certainswingmethodsshouldonlybecalledinswingeventthread.
UsageExample:
packagecom.rule; importjavax.swing.JFrame; publicclassAlways_call_swing_methods_in_swing_event_thread_violation { publicstaticvoidmain(Stringargs[]) { JFrameframe=newJFrame(); frame.setTitle("Title"); frame.setSize(200,100); frame.show(); //Violation frame.pack(); //Violation frame.setVisible(true); //Violation } }
Shouldbewrittenas:
packagecom.rule; importjavax.swing.JFrame; publicclassAlways_call_swing_methods_in_swing_event_thread_correctionimplementsRunnable { finalFrameframe; publicFrameShower(Frameframe) { this.frame=frame; } publicvoidrun() { frame.show(); //Correction } publicstaticvoidmain(Stringargs[]) { JFrameframe=newJFrame(); frame.setTitle("Title"); frame.setSize(200,100); Runnablerunner=newFrameShower(frame); } }
Reference:http://java.sun.com/developer/JDCTechTips/2003/tt1208.html#1
Rule71:Erroneous_use_of_binary_AND_with_ZERO
Severity:Medium
Rule:AvoiderroneoususeofbinaryANDoperatorwithzero.
Reason:AvoiderroneoususeofbinaryANDoperatorwithzero.
UsageExample:
packagecom.rule; publicclassErroneous_use_of_binary_AND_with_ZERO_violation { publicstaticfinalintHSCROLLBAR=1; publicstaticfinalintVSCROLLBAR=2; publicstaticfinalintNONE=0; publicstaticfinalintBOTHSCROLLBARS=3; publicbooleancheck(intattribs) { return((attribs&NONE)==NONE); } }
Shouldbewrittenas:
Nocorrectionavailable.
Reference:Referencenotavailable.
Rule72:Erroneous_use_of_binary_AND
Severity:Medium
Rule:AvoidexpressioninvolingspecificuseofbitwiseANDoperatorthatalwaysevaluatetofalse.
Reason:AvoidexpressioninvolingspecificuseofbitwiseANDoperatorthatalwaysevaluatetofalse.
UsageExample:
packagecom.rule; publicclassErroneous_use_of_BAND_violation { publicstaticfinalintHSCROLLBAR=1; publicstaticfinalintVSCROLLBAR=2; publicstaticfinalintNONE=0; publicstaticfinalintBOTHSCROLLBARS=3; publicbooleancheck(intattribs) { return((attribs&VSCROLLBAR)==BOTHSCROLLBARS); } }
Shouldbewrittenas:
Nocorrectionavailable.
Reference:Referencenotavailable.
Rule73:Declare_Object_as_parameter_for_compareTo_method
Severity:Medium
Rule:IfcompareTomethodisdeclared,itshouldhavetheparameteroftypejava.lang.Object.
Reason:IfcompareTomethodisdeclared,itshouldhavetheparameteroftypejava.lang.Object.
UsageExample:
packagecom.rule; publicclassDeclare_Object_as_parameter_for_compareTo_method_violation { publicintcompareTo(Declare_Object_as_parameter_for_compareTo_method_violationo)//VIOLATION { return0; } }
Shouldbewrittenas:
packagecom.rule; publicclassDeclare_Object_as_parameter_for_compareTo_method_correction { publicintcompareTo(Objecto)//CORRECTION { return0; } }
Reference:Noreferenceavailable.
Rule74:Always_explicitly_initialize_all_fields_in_a_constructor
Severity:Medium
Rule:Explicitlyintializeallfieldsconstructor.
Reason:Explicitlyintializeallfieldsconstructor.
UsageExample:
publicclassInit { privateinti=5; privateintj; privateintk; publicInit() { this(12); k=0; } publicInit(intval)//VIOLATION:kisnotinitialized. { j=val; } }
Shouldbewrittenas:
publicclassInit { privateinti=5; privateintj; privateintk; publicInit() { this(12); } publicInit(intval) { j=val; k=0; //CORRECTION } }
Reference:Noreferencesavailable.
Rule75:Avoid_passing_decimal_literals_to_BigDecimal_constructor
Severity:Medium
Rule:Thisshouldbeavoidedbecausedecimalliteralsarenotpreciselyequaltotheirdesiredvalues.
Reason:Thisshouldbeavoidedbecausedecimalliteralsarenotpreciselyequaltotheirdesiredvalues.
UsageExample:
importjava.math.*; publicclassTest { publicvoidmethod() { BigDecimalbd=newBigDecimal(.1);//VIOLATION } }
Shouldbewrittenas:
Usethe'BigDecimal'constructorwhichtakesaStringasanargumentinstead oftheonewhichtakesadoublesincethisconstructorwillproduceaprecise value. importjava.math.*; publicclassTest { publicvoidmethod() { BigDecimalbd=newBigDecimal(".1");//FIXED } }
Reference:Notavailable.
Rule76:Use_string_equals_method
Severity:Medium
Rule:UseequalsmethodforStringcomparison.
Reason:UseequalsmethodforStringcomparison.
UsageExample:
packagecom.rule; publicclassUse_string_equals_method_violation { publicvoidfoo() { Stringstr="compare"; Stringtemp=newString("compare"); if(str==temp)//Violation { //... System.out.println("samecontent"); } } }
Shouldbewrittenas:
packagecom.rule; publicclassUse_string_equals_method_correction { publicvoidfoo() { Stringstr="compare"; Stringtemp=newString("compare"); if(str.equals(temp))//Correction { //... System.out.println("samecontent"); } } }
Reference:Referencenotavailable.
Rule77:Avoid_circular_initialization_for_static_fields
Severity:Medium
Rule:Initializationsthatdependonstaticfieldsfromdifferentclassesorfilesshouldbeavoided.
Reason:Initializationsthatdependonstaticfieldsfromdifferentclassesorfilesshouldbeavoided.
UsageExample:
publicclassNoCirc { publicstaticvoidmain(Stringargs[]) { //Iftheorderisswitched,theresultwouldbedifferent IC2ref2=newIC2(); IC1ref1=newIC1(); System.out.println(IC1.a+""+IC2.b); } } classIC1 { staticinta=IC2.b+1;//VIOLATION } classIC2 { staticintb=IC1.a;//VIOLATION }
Shouldbewrittenas:
publicclassNoCirc { publicstaticvoidmain(Stringargs[]) { IC2ref2=newIC2(); IC1ref1=newIC1(); System.out.println(IC1.a+""+IC2.b); } } classIC1 { staticinta=IC2.b+1;//CORRECTION } classIC2 { staticintb=0;//CORRECTION }
Reference:Noreferencesavailable.
Rule78:Always_ensure_get_set_methods_access_correct_fields
Severity:High
Rule:Ifthegetterorsettersaresettingfieldsotherthantheonementionedinitname,thenitcouldbeapossiblebug.
Reason:Ifthegetterorsettersaresettingfieldsotherthantheonementionedinitname,thenitcouldbeapossiblebug.
UsageExample:
publicclassAlwaysEnsureGetSetMethodsAccessCorrectFields { privateString_str1; privateString_str2; publicvoidsetStr1(Stringstr)//VIOLATION { _str2=str; } publicStringgetStr2()//VIOLATION { return_str1; } }
Shouldbewrittenas:
publicclassAlwaysEnsureGetSetMethodsAccessCorrectFields { privateString_str1; privateString_str2; publicvoidsetStr1(Stringstr)//CORRECTION { _str1=str; } publicStringgetStr2()//CORRECTION { return_str2; } }
Reference:Noreferencesavailable.
Rule79:Declare_fields_of_user-defined_Exception_as_final_or_private
Severity:Medium
Rule:Declarethefieldsasfinalorprivatesoastopreventthemfromunauthorizedmodifications.
Reason:Declarethefieldsasfinalorprivatesoastopreventthemfromunauthorizedmodifications.
UsageExample:
publicclassMyExceptionextendsjava.lang.Exception//VIOLATION { StringextraMessage; intseverity; //... }
Shouldbewrittenas:
publicclassMyExceptionextendsjava.lang.Exception { finalStringextraMessage; privateseverity; //... }
Reference:
Rule80:Avoid_overloading_methods_on_argument_types
Severity:Medium
Rule:Methodoverloadingbasedontheargument'sdatatypeshouldbeavoided.
Reason:Methodoverloadingbasedontheargument'sdatatypeshouldbeavoided.
UsageExample:
packagecom.rule; publicclassAvoid_overloading_methods_on_argument_types_violation { voidmethod(IntegerintVal)//VIOLATION { //handleInteger } voidmethod(StringstrVal) { //handleString } }
Shouldbewrittenas:
packagecom.rule; publicclassAvoid_overloading_methods_on_argument_types_correction { voidmethod(Objectval)//CORRECTION { if(valinstanceofInteger) { //handleInteger } elseif(valinstanceofString) { //handleString } } }
Reference:Noreferenceavailable.
Rule81:Private_field_is_never_written
Severity:Medium
Rule:Novaluewasassignedtoprivatefield.
Reason:Novaluewasassignedtoprivatefield.
UsageExample:
packagecom.rule; publicclassPrivate_field_is_never_written_violation { privateStringname;//VIOLATION publicvoiddebug() { System.out.println("name="+name); } }
Shouldbewrittenas:
packagecom.rule; publicclassPrivate_field_is_never_written_correction { // privateStringname;//CORRECTION publicvoiddebug() { // System.out.println("name="+name); } }
Reference:Noreferenceavailable
Rule82:Do_not_call_synchronized_method_from_synchronized_method
Severity:Critical
Rule:Donotcallsynchronizedmethodfromsynchronizedmethod.
Reason:Donotcallsynchronizedmethodfromsynchronizedmethod.
UsageExample:
packagecom.rule; publicclassDo_not_call_synchronized_method_from_synchronized_method_violation { publicsynchronizedvoidmeth() { Testtt=newTest(); //... tt.foo();//Violation } } classTest { publicsynchronizedvoidfoo() { //... } }
Shouldbewrittenas:
Avoidcallingsynchronizedmethodfromsynchronizedmethod.
Reference:http://www.onjava.com/pub/a/onjava/2004/10/20/threads2.html
Rule83:Always_place_literals_first_in_string_comparison
Severity:High
Rule:Alwaysplaceliteralsfirstinstringcomparison.
Reason:Alwaysplaceliteralsfirstinstringcomparison.
UsageExample:
packagecom.rule; publicclassAlways_place_literals_first_in_string_comparison_violation { publicvoidmethod() { Stringstr="AppPerfect"; if(str.equals("AppPerfect")) //Violation. { } } }
Shouldbewrittenas:
packagecom.rule; publicclassAlways_place_literals_first_in_string_comparison_correction { publicvoidmethod() { Stringstr="AppPerfect"; if("AppPerfect".equals(str)) //Correction. { } } }
Reference:Referencenotavailable.
Rule84:Avoid_equals_operator_for_decimal_point_values
Severity:Medium
Rule:Donotuseequalsoperatorfordecimalpointvaluestoavoidpossibleerrors
Reason:Donotuseequalsoperatorfordecimalpointvaluestoavoidpossibleerrors
UsageExample:
packagecom.rule; classAvoid_equals_operator_for_decimal_point_values_violation { publicbooleanisEqual(floatf1,floatf2) { returnf1==f2; } }
Shouldbewrittenas:
Insteadofcheckingforexactequality,checkforsufficientequality.Thatisfindthedifferenceoftwovaluesandseeifitsinthepermissiblelimits. packagecom.rule; classAvoid_equals_operator_for_decimal_point_values_correction { publicbooleanisEqual(floatf1,floatf2) { return(Math.abs(f1-f2)<0.01); } }
Reference:http://www-106.ibm.com/developerworks/java/library/j-jtp0114/
Rule85:Avoid_returning_java_lang_Object
Severity:Medium
Rule:Avoidreturningjava.lang.Object.
Reason:Avoidreturningjava.lang.Object.
UsageExample:
publicclassNoObject { privateStringstr; publicNoObject(Stringstr) { super(); this.str=str; } publicObjectgetMyString()//VIOLATION { returnstr; } publicstaticvoidmain(String[]args)throwsException { NoObjectno=newNoObject("Test"); Stringstr=(String)no.getMyString(); System.out.println(str); } }
Shouldbewrittenas:
publicclassNoObject { privateStringstr; publicNoObject(Stringstr) { super(); this.str=str; } publicStringgetMyString()//CORRECTION { returnstr; } publicstaticvoidmain(String[]args)throwsException { NoObjectno=newNoObject("Test"); Stringstr=no.getMyString(); System.out.println(str); } }
Reference:Noreferencesavailable.
Rule86:Avoid_invoking_runFinalizersOnExit
Severity:High
Rule:AvoidinvokingSystem.runFinalizersOnExitorRuntime.runFinalizersOnExit.
Reason:AvoidinvokingSystem.runFinalizersOnExitorRuntime.runFinalizersOnExit.
UsageExample:
packagecom.rule; publicclassAvoid_invoking_runFinalizersOnExit_violation { publicvoidmethod() { Object[]oa=getObjects(); process(oa); System.runFinalizersOnExit(true); //Violation. Runtime.runFinalizersOnExit(true); //Violation. } }
Shouldbewrittenas:
Reference:Referencenotavailable.
Rule87:Avoid_contiguous_non_String_values_during_concatenation
Severity:MediumRule:AvoidcontiguousnonStringvaluesduringStringconcatenation.Reason:AvoidcontiguousnonStringvaluesduringStringconcatenation.
UsageExample:
packagecom.rule; publicclassAvoid_contiguous_non_String_values_during_concatenation_violation { publicvoidmethod() { intprinciple=100; intinterest=10; System.out.println("Netpayable="+principle+interest+"rupees");//VIOLATION } }
Shouldbewrittenas:
packagecom.rule; publicclassAvoid_contiguous_non_String_values_during_concatenation_correction { publicvoidmethod() { intprinciple=100; intinterest=10; inttotal=principle+interest System.out.println("Netpayable="+total+"rupees");//CORRECTION } }
Reference:ReferenceNotAvailable.
Rule88:Conditional_expression_always_evaluates_to_constant_value
Severity:Medium
Rule:Aconditionalexpressionthatalwaysevaluatestofalseismostlylikelyapossiblebug.
Reason:Aconditionalexpressionthatalwaysevaluatestofalseismostlylikelyapossiblebug.
UsageExample:
publicclassMyClass { publicvoidprocess(intarray_size,booleanb1,booleanb2) { if(array_size<0&&array_size>100) //VIOLATION thrownewIllegalArgumentException("invalidarraysize"); } }
Shouldbewrittenas:
publicclassMyClass { publicvoidprocess(intarray_size,booleanb1,booleanb2) { if(array_size<0||array_size>100) //CORRECTION thrownewIllegalArgumentException("invalidarraysize"); } }
Reference:Noreferencesavailable.
Rule89:Avoid_accessing_uninitialized_fields_in_constructors
Severity:Medium
Rule:Donotuseanyclassfieldsthathavenotassignedanyvalueinconstructors.
Reason:Donotuseanyclassfieldsthathavenotassignedanyvalueinconstructors.
UsageExample:
packagecom.rule; publicclassAvoid_accessing_uninitialized_fields_in_constructors_violation { privateStringname; privateintid; publicAvoid_accessing_uninitialized_fields_in_constructors_violation(intID) { name="name"+id;//VIOLATION id=ID; } }
Shouldbewrittenas:
packagecom.rule; publicclassAvoid_accessing_uninitialized_fields_in_constructors_correction { privateStringname; privateintid; publicAvoid_accessing_uninitialized_fields_in_constructors_correction(intID) { name="name"+ID;//CORRECTION id=ID; } }
Reference:Noreferenceavailable.
Rule90:Avoid_accessing_uninitialized_fields
Severity:Medium
Rule:Donotuseanyclassfieldsthathavenotassignedanyvalueinmethods.
Reason:Donotuseanyclassfieldsthathavenotassignedanyvalueinmethods.
UsageExample:
packagecom.rule; publicclassAvoid_accessing_uninitialized_fields_violation { privateStringname; privateintid; publicvoidmethod() { name="name"+id;//VIOLATION id=ID; } }
Shouldbewrittenas:
packagecom.rule; publicclassAvoid_accessing_uninitialized_fields_correction { privateStringname; privateintid; publicvoidmethod() { name="name"+ID;//CORRECTION id=ID; } }
Reference:Noreferenceavailable.
Rule91:Avoid_Serializable_class_having_non_Serializable_parent
Severity:Critical
Rule:Theerrorisdetectedatruntime.
Reason:Theerrorisdetectedatruntime.
UsageExample:
packagecom.rule; publicclassAvoid_Serializable_class_having_non_Serializable_parent_violationextendsSuperimplementsjava.io.Serializable//VIOLATION { Avoid_Serializable_class_having_non_Serializable_parent_violation() { super(0); } } classSuper { Super(inti) { } }
Shouldbewrittenas:
packagecom.rule; publicclassAvoid_Serializable_class_having_non_Serializable_parent_correctionextendsSuperimplementsjava.io.Serializable { Avoid_Serializable_class_having_non_Serializable_parent_violation() { super(); } } classSuper { Super() { } }
Reference:http://java.sun.com/j2se/1.5.0/docs/api/java/io/Serializable.html
Rule92:Avoid_comparison_with_float_NaN
Severity:Medium
Rule:AvoidcomparisonwithFloat.NaNandDouble.NaN.
Reason:AvoidcomparisonwithFloat.NaNandDouble.NaN.
UsageExample:
packagecom.rule; publicclassAvoid_comparison_with_float_NaN_violation { publicvoidmethod() { if(performDivision(0.0f,0.0f)==Float.NaN)//Violation { System.out.println("NotaNumber"); } else { System.out.println("aNumber"); } } publicfloatperformDivision(floatf1,floatf2) { returnf1/f2; } }
Shouldbewrittenas:
packagecom.rule; publicclassAvoid_comparison_with_float_NaN_correction { publicvoidmethod() { if(Float.isNan(performDivision(0.0,0.0)))//Correction { System.out.println("NotaNumber"); } else { System.out.println("aNumber"); } } publicfloatperformDivision(floatf1,floatf2) { returnf1/f2; } }
Reference:http://www.concentric.net/~Ttwang/tech/javafloat.htm
Rule93:Declare_get_method_synchronized
Severity:High
Rule:Ifthesetmethodissynchronized,thegetmethodshouldalsobesynchronized.
Reason:Ifthesetmethodissynchronized,thegetmethodshouldalsobesynchronized.
UsageExample:
packagecom.rule; publicclassDeclare_get_method_synchronized_violation { privateintvalue; publicintgetValue()//VIOLATION { returnvalue; } publicsynchronizedvoidsetValue(intval) { value=val; } }
Shouldbewrittenas:
packagecom.rule; publicclassDeclare_get_method_synchronized_correction { privateintvalue; publicsynchronizedintgetValue()//CORRECTION { returnvalue; } publicsynchronizedvoidsetValue(intval) { value=val; } }
Reference:Noreferenceavailable.
Rule94:Avoid_using_float_or_double
Severity:High
Rule:Floatanddoubledonotprovideexactresultsandshouldnotbeusedwhereexactresultsarerequired.
Reason:Floatanddoubledonotprovideexactresultsandshouldnotbeusedwhereexactresultsarerequired.
UsageExample:
publicclassBadFloatAndDouble { publicstaticvoidmain(String[]args) { doublefunds=1.0; intitemsBought=0; for(doubleprice=.10;funds>=price;price+=.10)//VIOLATION { funds-=price;//VIOLATION itemsBought++; } System.out.println(itemsBought+"itemsbought."); System.out.println("Change:$"+funds);//VIOLATION } }
Shouldbewrittenas:
publicclassBadFloatAndDouble { publicstaticvoidmain(String[]args) { finalBigDecimalTEN_CENTS=newBigDecimal(".10"); intitemsBought=0; BigDecimalfunds=newBigDecimal("1.00"); for(BigDecimalprice=TEN_CENTS;funds.compareTo(price)>=0; price=price.add(TEN_CENTS)) { itemsBought++; funds=funds.subtract(price); } System.out.println(itemsBought+"itemsbought."); System.out.println("Moneyleftover:$"+funds); } }
Reference:JoshuaBloch:"EffectiveJava-ProgrammingLanguageGuide"AddisonWesley,2001,pp.149-151
Rule95:Avoid_assigning_variable_to_same_variable
Severity:Critical
Rule:Avoidassigningvariabletosamevariable.
Reason:Avoidassigningvariabletosamevariable.
UsageExample:
packagecom.rule; publicclassAvoid_assigning_variable_to_same_variable_violation { privateintiVar; Avoid_assigning_variable_to_same_variable_violation(intiVar) { iVar=iVar;//Violation } }
Shouldbewrittenas:
packagecom.rule; publicclassAvoid_assigning_variable_to_same_variable_correction { privateintiVar; Avoid_assigning_variable_to_same_variable_violation(intiVar) { this.iVar=iVar;//Correction } }
Reference:Referencenotavailable.
Rule96:Erroneous_use_of_binary_OR
Severity:Medium
Rule:AvoiderroneoususeofbinaryORoperator.
Reason:AvoiderroneoususeofbinaryORoperator.
UsageExample:
packagecom.rule; publicclassErroneous_use_of_binary_OR_violation { publicstaticfinalintHSCROLLBAR=1; publicstaticfinalintVSCROLLBAR=2; publicstaticfinalintNONE=0; publicstaticfinalintBOTHSCROLLBARS=3; publicbooleancheck(intattribs) { return((attribs|BOTHSCROLLBARS)==HSCROLLBAR); } }
Shouldbewrittenas:
Nocorrectionavailable.
Reference:Referencenotavailable.
Rule97:Avoid_unsynchronized_lazy_initialization_of_static_field
Severity:Critical
Rule:Avoidunsynchronizedlazyinitializationofnon-volatilestaticfield.
Reason:Avoidunsynchronizedlazyinitializationofnon-volatilestaticfield.
UsageExample:
packagecom.rule; publicclassAvoid_Lazy_initialization_of_unsynchronized_static_field_violation { privatestaticSingletoninstance=null; publicstaticSingletongetInstance() { if(instance==null) instance=newSingleton();//Violation returninstance; } }
Shouldbewrittenas:
Reference:http://www.cs.umd.edu/users/pugh/java/memoryModel/jsr-133-faq.html
Rule98:Avoid_using_volatile_modifier_for_array
Severity:HighRule:Avoidusingvolatilemodifierforarray.Reason:Avoidusingvolatilemodifierforarray.
UsageExample:
packagecom.rule; publicclassAvoid_using_volatile_modifier_for_array_violation { publicstaticvolatileinti=10; publicstaticvolatileint[]array={10,20,30}; //Violation. }
Shouldbewrittenas:
Reference:Referencenotavailable.
Rule99:Avoid_synchronization_on_mutable_field
Severity:CriticalRule:Avoidsynchronizationonobjectswhosereferencesaremutable.Reason:Avoidsynchronizationonobjectswhosereferencesaremutable.
UsageExample:
packagecom.rule; publicclassAvoid_synchronization_on_mutable_field_violation { MyClassmyClass=newMyClass(); publicvoidfoo() { synchronized(myClass)//Violation { //... } } }
Shouldbewrittenas:
Avoidsynchronizationonobjectswhosereferencesaremutable.
Reference:Referencenotavailable.
Rule100:Avoid_methods_with_closely_similar_names
Severity:Low
Rule:Avoidmethodsinsameclasswhichdifferonlyincase.
Reason:Avoidmethodsinsameclasswhichdifferonlyincase.
UsageExample:
packagecom.rule; publicclassAvoid_methods_with_closely_similar_names_violation { publicvoidmethod() { } publicvoidMethod()//VIOLATION { } }
Shouldbewrittenas:
packagecom.rule; publicclassAvoid_methods_with_closely_similar_names_correction { publicvoidmethod1() { } publicvoidmethod2()//CORRECTION { } }
Reference:Referencenotavailable.
Rule101:Use_serializable_objects_as_argument
Severity:Medium
Rule:TheobjectspassedtosomeofthemethodsneedtobeSerializable.
Reason:TheobjectspassedtosomeofthemethodsneedtobeSerializable.
UsageExample:
packagecom.rule; importjava.io.IOException; importjava.io.ObjectOutputStream; importjava.io.OutputStream; publicclassUse_serializable_objects_as_argument_violation { publicvoidmethod1(ObjectOutputStreamoos)throwsException { oos.writeObject(this);//VIOLATION } classUSOAAV_ObjectOutputStreamextendsObjectOutputStream { USOAAV_ObjectOutputStream(OutputStreamos)throwsIOException { super(os); } } }
Shouldbewrittenas:
packagecom.rule; importjava.io.IOException; importjava.io.ObjectOutputStream; importjava.io.OutputStream; publicclassUse_serializable_objects_as_argument_correctionimplementsSerializable//Correction { publicvoidmethod1(ObjectOutputStreamoos)throws Exception { oos.writeObject(this); } classUSOAAV_ObjectOutputStreamextendsObjectOutputStream { USOAAV_ObjectOutputStream(OutputStreamos)throwsIOException { super(os); } } }
Reference:Noreferenceavailable.
Rule102:Do_not_call_methods_that_use_AppletStub
Severity:High
Rule:ThemethodsofAppletthatuseAppletStubshouldnotbecalledfromconstructor.
Reason:ThemethodsofAppletthatuseAppletStubshouldnotbecalledfromconstructor.
UsageExample:
packagecom.rule; importjava.applet.Applet; publicclassDo_not_call_methods_that_use_AppletStub_violationextendsApplet { privateStringdocBase; publicDo_not_call_methods_that_use_AppletStub_violation() { docBase=getDocumentBase().toString();//VIOLATION } }
Shouldbewrittenas:
packagecom.rule; importjava.applet.Applet; publicclassDo_not_call_methods_that_use_AppletStub_correctionextendsApplet { privateStringdocBase; publicvoidinit()//CORRECTION { docBase=getDocumentBase().toString(); } }
Reference:http://java.sun.com/j2se/1.4.2/docs/api/java/applet/AppletStub.html
Rule103:readResolve_method_should_have_java_lang_Object_as_its_return_type
Severity:Critical
Rule:ThisistheconventiontobefollowedforthereadResolvemethodtoberecognizedbytheserializationmechanism.
Reason:ThisistheconventiontobefollowedforthereadResolvemethodtoberecognizedbytheserializationmechanism.
UsageExample:
importjava.io.ObjectStreamException; importjava.io.Serializable; publicclassTestimplementsSerializable { publicTestreadResolve()throwsObjectStreamException//VIOLATION { returnnull; } }
Shouldbewrittenas:
importjava.io.ObjectStreamException; importjava.io.Serializable; publicclassTestimplementsSerializable { publicObjectreadResolve()throwsObjectStreamException//VIOLATION { returnnull; } }
Reference:NotAvailable.
Rule104:Avoid_setSize_in_componentResized
Severity:High
Rule:DonotcallsetSizemethodinsidethecomponentResizedmethod
Reason:DonotcallsetSizemethodinsidethecomponentResizedmethod
UsageExample:
packagecom.rule; importjava.awt.BorderLayout; importjava.awt.Color; importjava.awt.Component; importjava.awt.Frame; importjava.awt.Panel; importjava.awt.event.ComponentAdapter; importjava.awt.event.ComponentEvent; publicclassAvoid_setSize_in_componentResized_violationextendsFrame { publicAvoid_setSize_in_componentResized_violation() { Panelpan=newPanel(); pan.setBackground(Color.blue); this.add(pan,BorderLayout.CENTER); pan.addComponentListener(newComponentAdapter(){ publicvoidcomponentResized(ComponentEvente) { setSize(); Frameparent=Avoid_setSize_in_componentResized_violation.this; parent.setSize(200,200); //VIOLATION parent.validate(); } publicvoidsetSize() { } }); this.addComponentListener(newComponentAdapter(){ publicvoidcomponentResized(ComponentEvente) { e.getComponent().setSize(10,10); //VIOLATION ((Component)e.getSource()).setSize(20,20); //VIOLATION setSize(100,100); //VIOLATION } }); } }
Shouldbewrittenas:
RemovecallstosetSizemethodsfromcomponentResizedmethod.
Reference:ReferenceNotAvailable.
Rule105:Avoid_unnecessary_call_to_Math_ceil
Severity:Medium
Rule:AvoidunnecessarycalltoMath.ceil().
Reason:AvoidunnecessarycalltoMath.ceil().
UsageExample:
packagecom.rule; publicclassAvoid_unnecessary_call_to_Math_ceil_violation { publicvoidmethod() { inti=10; doubleresult=Math.ceil((double)i); //Violation } }
Shouldbewrittenas:
packagecom.rule; publicclassAvoid_unnecessary_call_to_Math_ceil_correction { publicvoidmethod() { doublei=10.2; doubleresult=Math.ceil(i); //Correction } }
Reference:Referencenotavailable.
Rule106:Avoid_unnecessary_call_to_Math_class_method
Severity:Medium
Rule:AvoidunnecessarycalltoamethodofMathclass.
Reason:AvoidunnecessarycalltoamethodofMathclass.
UsageExample:
packagecom.rule; publicclassAvoid_unnecessary_call_to_Math_class_method_violation { publicstaticfinaldoubleNUMBER=-10.2; publicvoidmethod() { doubled=Math.abs(NUMBER); //Violation. } }
Shouldbewrittenas:
packagecom.rule; publicclassAvoid_unnecessary_call_to_Math_class_method_correction { publicstaticfinaldoubleNUMBER=-10.2; publicstaticfinaldoubleABSNUMBER=10.2; publicvoidmethod() { doubled=ABSNUMBER; //Correction. } }
Reference:Referencenotavailable.
Rule107:Always_use_method_return_values
Severity:Low
Rule:Thereturnvalueofthemethodcallshouldnotbeignored.
Reason:Thereturnvalueofthemethodcallshouldnotbeignored.
UsageExample:
packagecom.rule; publicclassAlways_use_method_return_values { publicvoidfubar() { StringsomeString=getString(); someString.trim(); } privateStringgetString() { return"hello"; } }
Shouldbewrittenas:
packagecom.rule; publicclassAlways_use_method_return_values { publicvoidfubar() { StringsomeString=getString(); someString=someString.trim(); } privateStringgetString() { return"hello"; } }
Reference:Noreferenceavailable.
Rule108:Always_check_return_value_of_input_stream_read
Severity:Low
Rule:ThereturnvalueofthemethodcallInputStream.read(byte[]b)andInputStream.read(byte[]b,intoff,intlen)shouldalwaysbechecked.
Reason:ThereturnvalueofthemethodcallInputStream.read(byte[]b)andInputStream.read(byte[]b,intoff,intlen)shouldalwaysbechecked.
UsageExample:
packagecom.rule; importjava.io.InputStream; importjava.io.FileInputStream; importjava.io.IOException; publicclassAlways_check_return_value_of_input_stream_read_violation { publicvoidmethod() { InputStreamin=null; try { in=newFileInputStream("Filename.txt"); in.read(b,3,10); //Violation. } catch(IOExceptionioe) { //HandleException. } finally { in.close(); } } }
Shouldbewrittenas:
packagecom.rule; importjava.io.InputStream; importjava.io.FileInputStream; importjava.io.IOException; publicclassAlways_check_return_value_of_input_stream_read_correction { publicvoidmethod() { InputStreamin=null; try { in=newFileInputStream("Filename.txt"); inti=in.read(b,3,10); //Correction //Checkvalueofi. } catch(IOExceptionioe) { //HandleException. } finally { in.close(); } } }
Reference:Referencenotavailable.
Rule109:Always_check_return_value_of_input_stream_skip
Severity:Low
Rule:ThereturnvalueofthemethodcallInputStream.skip(longn)shouldalwaysbechecked.
Reason:ThereturnvalueofthemethodcallInputStream.skip(longn)shouldalwaysbechecked.
UsageExample:
packagecom.rule; importjava.io.InputStream; importjava.io.FileInputStream; importjava.io.IOException; publicclassAlways_check_return_value_of_input_stream_skip_violation { publicvoidmethod() { InputStreamin=null; try { longcount=100000; in=newFileInputStream("Filename.txt"); in.skip(count); //Violation. } catch(IOExceptionioe) { //HandleException. } finally { in.close(); } } }
Shouldbewrittenas:
packagecom.rule; importjava.io.InputStream; importjava.io.FileInputStream; importjava.io.IOException; publicclassAlways_check_return_value_of_input_stream_skip_correction { publicvoidmethod() { InputStreamin=null; try { longcount=100000; in=newFileInputStream("Filename.txt"); inti=in.skip(count); //Correction //Checkvalueofi. } catch(IOExceptionioe) { //HandleException. } finally { in.close(); } } }
Reference:Referencenotavailable.
Rule110:Erroneous_indexOf_check
Severity:Low
Rule:TheconditionshouldcheckwhetherindexOfreturnsnegativeornon-negativevalue.
Reason:TheconditionshouldcheckwhetherindexOfreturnsnegativeornon-negativevalue.
UsageExample:
publicclassSomeClass { publicvoidaMethod() { Strings="hello"; if(s.indexOf("e")>0)//VIOLATION { //... } if(s.indexOf("s")<1)//VIOLATION { //... } if(s.indexOf("h")>=1)//VIOLATION { //.... } If(s.indexOf("o")<=0)//VIOLATION { //... } } }
Shouldbewrittenas:
publicclassSomeClass { publicvoidaMethod() { Strings="hello"; if(s.indexOf("e")>=0) { //... } if(s.indexOf("s")==-1) { //... } if(s.indexOf("h")!=-1) { //.... } If(s.indexOf("o")==-1) { //... } } }
Reference:Referencenotavailable.
Rule111:Calling_equals_of_final_classes
Severity:Low
Rule:Thiscodecallsequalsonanobjectofafinalclasswhichdoesn'thaveequals()methodoverriden.
Reason:Thiscodecallsequalsonanobjectofafinalclasswhichdoesn'thaveequals()methodoverriden.
UsageExample:
publicfinalclassTest { publicvoidcheck(Testne) { if(ne.equals(this))//VIOLATION { System.out.println("it'sequal"); } } }
Shouldbewrittenas:
CheckifequalsneedstobeoverrideninclassTestornot.
Reference:Noreferencesavailable.
Rule112:Possible_infinite_recursion
Severity:Critical
Rule:Possibleinfiniterecursion.
Reason:Possibleinfiniterecursion.
UsageExample:
packagecom.rule; importcom.appperfect.common.dstruct.Color; importcom.appperfect.common.dstruct.Font; publicclassPossible_infinite_recursion_violation { publicvoidshowMessage(Strings,Fontf) { showMessage(s,f,null); } publicvoidshowMessage(Strings,Fontf,Colorfg) { showMessage(s,f,fg);//Violation } publicvoidshowMessage(Strings,Fontf,Colorfg,Colorbg) { //..codethatrendersactually } }
Shouldbewrittenas:
Nocorrectionavailable.
Reference:Referencenotavailable.
Rule113:Possible_infinite_loop
Severity:Critical
Rule:Possibleinfiniteloop.
Reason:Possibleinfiniteloop.
UsageExample:
importjava.util.List; importjava.util.Iterator; publicclassTest { publicvoidmethod(Listl) { booleanbool=true; do { //... }while(bool);//VIOLATION Iteratoriter; for(iter=l.iterator();iter.hasNext();)//VIOLATION { //... } while(true)//VIOLATION { //... } } }
Shouldbewrittenas:
importjava.util.List; importjava.util.Iterator; publicclassTest { publicvoidmethod(Listl) { booleanbool=true; do { //... bool=false;//FIXED }while(bool); Iteratoriter; for(iter=l.iterator();iter.hasNext();) { //... System.err.println(iter.next());//FIXED } while(true) { //... break;//FIXED } } }
Reference:NotAvailable.
Rule114:instanceOf_will_always_return_false
Severity:Medium
Rule:ThisinstanceOfcheckwillalwaysreturnfalse.
Reason:ThisinstanceOfcheckwillalwaysreturnfalse.
UsageExample:
importjava.util.ArrayList; importjava.util.Collection; importjava.util.Vector; publicclassTest { publicstaticvoidmain(String[]args) { Collections=newArrayList(); if(sinstanceofVector)//VIOLATION { //... } else { //... } } }
Shouldbewrittenas:
Reference:Noreferencesavailable.
Rule115:Avoid_classes_that_are_not_accessible
Severity:MediumRule:Fields,methods,andtypesthatarenot"private"andnot"static"areuselessiftheonlyconstructorsavailableareprivate.Reason:Fields,methods,andtypesthatarenot"private"andnot"static"areuselessiftheonlyconstructorsavailableareprivate.
UsageExample:
publicclassTest//VIOLATION { privatestaticTest_test; privateTest() { } publicTestgetInstance() { if(_test==null) { _test=newTest(); } return_test; } }
Shouldbewrittenas:
publicclassTest//FIXED { privateTest_test; privateTest() { } publicstaticTestgetInstance() { if(_test==null) { _test=newTest(); } return_test; } }
Reference:NotAvailable.
Rule116:Avoid_rethrowing_an_exception_in_a_catch_clause
Severity:Low
Rule:Removingitimprovescodereadabilityandmakescodelesserror-prone.
Reason:Removingitimprovescodereadabilityandmakescodelesserror-prone.
UsageExample:
publicclassTest { publicvoidmethod()throwsException { try { //... } catch(Exceptione)//VIOLATION { throwe; } } }
Shouldbewrittenas:
publicTest { publicvoidmethod()throwsException { //FIXED:try-catchstatementisremoved //... } }
Reference:NotAvailable.
Rule117:Avoid_initializing_array_dimensions_with_negative_values
Severity:Critical
Rule:Whenanarrayisdeclaredwithanegativedimenson,aNegativeArraySizeExceptionwouldbethrown.
Reason:Whenanarrayisdeclaredwithanegativedimenson,aNegativeArraySizeExceptionwouldbethrown.
UsageExample:
publicclassTest { privatestaticfinalintA_SIZE=10; privatestaticfinalintB_SIZE=15; privatestaticint[]diffSet=newint[A_SIZE-B_SIZE];//VIOLATION }
Shouldbewrittenas:
publicclassTest { privatestaticfinalintA_SIZE=10; privatestaticfinalintB_SIZE=15; privatestaticint[]diffSet=newint[A_SIZE-B_SIZE>=0?A_SIZE-B_SIZE:0];//FIXED }
Reference:NotAvailable.
Rule118:Use_Equals_Instead_Equality_Operator
Severity:Medium
Rule:Useequals()insteadof'=='operator.
Reason:Useequals()insteadof'=='operator.
UsageExample:
packagecom.rule; publicclassUseEqualsInsteadEqualityOperator_Violation { privatevoidfoo() { Stringstr="compare"; Stringtemp=newString("compare"); if(str==temp)//Violation { //... } } }
Shouldbewrittenas:
packagecom.rule; publicclassUseEqualsInsteadEqualityOperator_Correction { privatevoidfoo() { Stringstr="compare"; Stringtemp=newString("compare"); if(str.equals(temp))//Correction { //... } } }
Reference:http://www.devx.com/tips/Tip/14219
Rule119:Possible_spelling_mistake_while_overriding_method
Severity:Medium
Rule:Possiblespellingmistakewhileoverridingmethod.
Reason:Possiblespellingmistakewhileoverridingmethod.
UsageExample:
packagecom.rule; publicclassPossible_spelling_mistake_while_overriding_method_violation { publicStringToString()//VIOLATION { returnsuper.toString(); } }
Shouldbewrittenas:
packagecom.rule; publicclassPossible_spelling_mistake_while_overriding_method_correction { publicStringtoString()//CORRECTION { returnsuper.toString(); } }
Reference:ReferenceNotAvailable.
Rule120:Do_not_use_zero_as_index_with_resuset
Severity:Critical
Rule:TheindexforgetandupdatemethodsofResultSetstartsfrom1.
Reason:TheindexforgetandupdatemethodsofResultSetstartsfrom1.
UsageExample:
packagecom.rule; importjava.sql.ResultSet; importjava.sql.SQLException; publicclassDo_not_use_zero_as_index_with_ResultSet_violation { publicStringgetName(ResultSetrs)throwsSQLException { returnrs.getString(0);//VIOLATION } publicvoidsetName(ResultSetrs,Stringname)throwsSQLException { rs.updateString(0,name);//VIOLATION } }
Shouldbewrittenas:
packagecom.rule; importjava.sql.ResultSet; importjava.sql.SQLException; publicclassDo_not_use_zero_as_index_with_ResultSet_correction { publicStringgetName(ResultSetrs)throwsSQLException { returnrs.getString(1);//CORRECTION } publicvoidsetName(ResultSetrs,Stringname)throwsSQLException { rs.updateString(1,name);//CORRECTION } }
Reference:http://java.sun.com/j2se/1.4.2/docs/guide/jdbc/getstart/resultset.html
http://java.sun.com/j2se/1.4.2/docs/api/java/sql/ResultSet.html
Rule121:Do_not_use_zero_as_index_with_PreparedStatement
Severity:Critical
Rule:TheindexforthesettersofPreparedStatementstartfrom1.
Reason:TheindexforthesettersofPreparedStatementstartfrom1.
UsageExample:
importjava.sql.PreparedStatement; importjava.sql.SQLException; publicclassTest { publicvoidsetName(PreparedStatementps,Stringname)throwsSQLException { ps.setObject(0,name);//VIOLATION } }
Shouldbewrittenas:
importjava.sql.PreparedStatement; importjava.sql.SQLException; publicclassTest { publicvoidsetName(PreparedStatementps,Stringname)throwsSQLException { ps.setObject(1,name);//FIXED } }
Reference:NotAvailable.
Rule122:Always_call_wait_inside_while_or_doWhile_loop
Severity:High
Rule:Alwayscallwaitfromwithinawhileordo-whileloop.
Reason:Alwayscallwaitfromwithinawhileordo-whileloop.
UsageExample:
packagecom.rule; publicclassAlwaysCall_wait_inside_while_or_doWhile_loop_Violation { intavailable=0; synchronizedpublicvoidconsume() { try { if(available<0) { wait();//VIOLATION } } catch(InterruptedExceptione) { //consume } } }
Shouldbewrittenas:
packagecom.rule; publicclassAlwaysCall_wait_inside_while_or_doWhile_loop_Correction { intavailable=0; synchronizedpublicvoidconsume() { try { while(available<0) { wait();//CORRECTION } } catch(InterruptedExceptione) { //consume } } }
Reference:http://today.java.net/cs/user/create/cs_msg?x-lr=cs_msg/7296&x-lr2=a/131
Rule123:Always_call_Condition_await_inside_a_loop
Severity:High
Rule:Iftheobjectisusedformultipleconditions,theconditionthecallerintendedtowaitformightnotbetheonethatactuallyoccurred.
Reason:Iftheobjectisusedformultipleconditions,theconditionthecallerintendedtowaitformightnotbetheonethatactuallyoccurred.
UsageExample:
publicclassTest { voidfubar(Conditioncond)throwsInterruptedException//VIOLATION { cond.await(); } }
Shouldbewrittenas:
publicclassTest { intx; voidfubar(Conditioncond)throwsInterruptedException { while(x==0) { cond.wait();//FIXED } } }
Reference:NotAvailable.
Rule124:Avoid_public_semaphores
Severity:High
Rule:Avoidusingwait(),notify()ornotifyAll()onthe"this"reference.
Reason:Avoidusingwait(),notify()ornotifyAll()onthe"this"reference.
UsageExample:
importjava.util.*; publicclassTestextendsThread { ArrayListobjects=newArrayList(); publicstaticvoidmain(String[]args) { finalTesttest=newTest(); Threadt1=newThread() { publicvoidrun() { try { test.add(newObject()); } catch(InterruptedExceptione) { e.printStackTrace(); } } }; t1.start(); Threadt2=newThread() { publicvoidrun() { try { test.add(newObject()); } catch(InterruptedExceptione) { e.printStackTrace(); } } }; t2.start(); } publicsynchronizedvoidadd(Objectobj)throwsInterruptedException { while(objects.size()==10) { wait();//VIOLATION } objects.add(obj); if(objects.size()==1) { notify(); } } }
Shouldbewrittenas:
Considerusingaprivatemembervariabletocontrolsynchronization.
Reference:Noreferenceavailable.
Rule125:Do_not_call_interrupted_method_on_thread_object
Severity:High
Rule:ThestaticmethodinterruptedinThreadclassshouldnotbecalledonathreadobject.
Reason:ThestaticmethodinterruptedinThreadclassshouldnotbecalledonathreadobject.
UsageExample:
packagecom.rule; publicclassDo_not_call_interrupted_method_on_thread_object_violation { publicvoidmethod(Threadth) { booleanb=th.interrupted();//VIOLATION } }
Shouldbewrittenas:
packagecom.rule; publicclassDo_not_call_interrupted_method_on_thread_object_correction { publicvoidmethod(Threadth) { booleanb=th.isInterrupted();//CORRECTION } }
Reference:http://java.sun.com/j2se/1.4.2/docs/api/java/lang/Thread.html#interrupted()
http://java.sun.com/j2se/1.4.2/docs/api/java/lang/Thread.html#isInterrupted()
Rule126:Avoid_unnecessary_comparison_of_two_null_references
Severity:Low
Rule:Avoidunnecessarycomparisonoftworeferenceswhicharedefinitelynull.
Reason:Avoidunnecessarycomparisonoftworeferenceswhicharedefinitelynull.
UsageExample:
publicclassTest { publicvoidfubar() { Objectob1=null; Objectob2=null; //... if(ob1!=ob2)//VIOLATION { //... } } }
Shouldbewrittenas:
Checkiftheob1andob2aretoalwaysremainnull,thentheconditioncanberemoved.
Reference:NotAvailable.
Rule127:Avoid_unnecessary_comparison_of_non_null_reference_with_null_reference
Severity:Low
Rule:Avoidunnecessarycomparisonoftworeferenceswhereoneisdefinitelynonnullandtheotherisdefinitelynull.
Reason:Avoidunnecessarycomparisonoftworeferenceswhereoneisdefinitelynonnullandtheotherisdefinitelynull.
UsageExample:
publicclassTest { publicvoidfubar() { Objectob1=null; Objectob2=null; //... ob2=newObject(); //... if(ob1==ob2)//VIOLATION { //... } } }
Shouldbewrittenas:
Ifonevalueisalwaysgoingtobenullandtheotheralwaysnon-null,thentheconditioncanberemoved.
Reference:NotAvailable.
Rule128:Avoid_unnecessary_comparison_with_int
Severity:Medium
Rule:Thiswillreturnaconstantvalue.
Reason:Thiswillreturnaconstantvalue.
UsageExample:
publicclassTest { intmethod(intx) { for(inti=0;i<=Integer.MAX_VALUE;i++)//VIOLATION { if(i*i==x) { returni; } } return0; } intmethod2(intx) { if(x<0||x>Integer.MAX_VALUE)//VIOLATION { return-1; } returnx; } }
Shouldbewrittenas:
Pleaserecheckcondition.
Reference:NotAvailable.
Rule129:Do_not_start_Thread_in_constructor
Severity:Low
Rule:Thestart()methodofathreadshouldnotbecalledinit'sconstructor.
Reason:Thestart()methodofathreadshouldnotbecalledinit'sconstructor.
UsageExample:
packagecom.rule; publicclassDo_not_start_Thread_in_constructor_violation { voidmethod() { newThread_sub(); } classThread_subextendsThread { publicThread_sub() { start();//VIOLATION } } }
Shouldbewrittenas:
packagecom.rule; publicclassDo_not_start_Thread_in_constructor_correction { voidmethod() { newThread_sub().start();//CORRECTION:calltostart()movedhere } classThread_subextendsThread { publicThread_sub() { //CORRECTION:calltostart()ismovedtowhereobjectiscreated } } }
Reference:https://lists.xcf.berkeley.edu/lists/advanced-java/2001-April/016440.html
Rule130:Classes_or_interfaces_having_same_name_as_java_file_should_be_public
Severity:Low
Rule:Classesorinterfaceshavingsamenameasjavafileshouldbedeclaredaspublic.
Reason:Classesorinterfaceshavingsamenameasjavafileshouldbedeclaredaspublic.
UsageExample:
filename:MyFile.java classMyFile//VIOLATION {}
Shouldbewrittenas:
filename:MyFile.java publicclassMyFile//CORRECTION {}
Reference:Noreferencesavailable.
Rule131:Always_ensure_only_one_class_or_interface_has_same_name_as_java_file
Severity:Low
Rule:Atleastoneclassorinterfaceshouldhavethesamenameasthejavafileinwhichitisdeclared.
Reason:Atleastoneclassorinterfaceshouldhavethesamenameasthejavafileinwhichitisdeclared.
UsageExample:
filename:MyClass.java classMyClass_//VIOLATION { }
Shouldbewrittenas:
filename:MyClass.java classMyClass//CORRECTION { }
Reference:Norefrerencesavailable.
Rule132:Avoid_returning_this
Severity:Medium
Rule:Avoidreturningthisfromamethod.
Reason:Avoidreturningthisfromamethod.
UsageExample:
packagecom.rule; publicclassAvoid_returning_this_violation { publicAvoid_returning_this_violationmethod1() { returnthis;//VIOLATION } publicvoidmethod2() { //somethingsynchronized } publicstaticvoidmain(String[]args) { Avoid_returning_this_violationa=newAvoid_returning_this_violation(); a.method1().method2(); } }
Shouldbewrittenas:
packagecom.rule; publicclassAvoid_returning_this_correction { publicvoidmethod1() { return;//CORRECTION } publicvoidmethod2() { //somethingsynchronized } publicstaticvoidmain(String[]args) { Avoid_returning_this_correctiona=newAvoid_returning_this_correction(); a.method1(); a.method2(); } }
Reference:http://gee.cs.oswego.edu/dl/html/javaCodingStd.html#secRec
Rule133:Avoid_calling_getResource_on_getClass
Severity:Medium
Rule:CallinggetResource()ontheclassreturnedbygetClass()mightcauseunexpectedresults.
Reason:CallinggetResource()ontheclassreturnedbygetClass()mightcauseunexpectedresults.
UsageExample:
packagecom.rule; importjava.net.URL; publicclassAvoid_calling_getResource_on_getClass_violation { publicURLloadResource(Stringstr) { returnthis.getClass().getResource(str);//VIOLATION } }
Shouldbewrittenas:
packagecom.rule; importjava.net.URL; publicclassAvoid_calling_getResource_on_getClass_correction { publicURLloadResource(Stringstr) { returnAvoid_calling_getResource_on_getClass_correction.class.getResource(str);//CORRECTION } }
Reference:http://java.sun.com/j2se/1.4.2/docs/api/java/lang/Class.html#getResource(java.lang.String)
http://java.sun.com/j2se/1.4.2/docs/api/java/lang/Class.html#getResourceAsStream(java.lang.String)
Rule134:Non_instantiable_class_should_contain_non_private_static_method
Severity:Critical
Rule:Thereshouldbeatleastonenon-private,staticmethodintheclasshavingonlyprivateconstructors
Reason:Thereshouldbeatleastonenon-private,staticmethodintheclasshavingonlyprivateconstructors
UsageExample:
packagecom.rule; classNon_instantiable_class_should_contain_non_private_static_member_violation { privateNon_instantiable_class_should_contain_non_private_static_member_violation() { } privatestaticintgetValue()//VIOLATION { return1; } }
Shouldbewrittenas:
packagecom.rule; classNon_instantiable_class_should_contain_non_private_static_member_correction { privateNon_instantiable_class_should_contain_non_private_static_member_correction() { } staticintgetValue()//CORRECTION { return1; } }
Reference:ReferenceNotAvailable.
Rule135:Do_not_override_synchronized_method_with_unsynchronized_method
Severity:High
Rule:Donotoverridesynchronizedmethodwithunsynchronizedmethod.
Reason:Donotoverridesynchronizedmethodwithunsynchronizedmethod.
UsageExample:
packagecom.rule; publicclassDo_not_override_synchronized_method_with_unsynchronized_method_violation { publicsynchronizedvoidfoo() {} } classchild { publicvoidfoo(){}//Violation }
Shouldbewrittenas:
packagecom.rule; publicclassDo_not_override_synchronized_method_with_unsynchronized_method_correction { publicsynchronizedvoidfoo() {} } classchild { publicsynchronizedvoidfoo() {}//Correction }
Reference:Referencenotavailable.
相关推荐
Alibaba_Java_Coding_Guidelines-2.1.1 是阿里巴巴集团发布的Java编程规范的一个版本。这个规范旨在统一阿里巴巴集团内部Java开发者的编码习惯,提升代码的可读性、可维护性和性能。 该规范通常包含多个方面,如...
总的来说,《Alibaba Java Coding Guidelines》2.0.2版提供了一个全面且实用的Java编程标准,它不仅有助于提升代码质量,也有助于培养良好的编程习惯。开发者可以将其集成到IDEA中,进行实时的代码检查,以达到规范...
最新发布的《Alibaba Java Coding Guidelines 2.1.1》是对Java开发人员的一份重要指南,旨在提升代码质量,保证项目稳定性和可维护性。这份规范不仅涵盖了基础的编程习惯,还涉及到设计模式、异常处理、多线程等高级...
《Alibaba Java Coding Guidelines IDEA插件详解》 在软件开发领域,编码规范是提升代码质量、维护团队协作效率的重要工具。阿里巴巴作为全球领先的科技公司,其制定的Java Coding Guidelines已经成为了业界广泛...
现在网上很多是idea怎么安装Alibaba Java Coding Guidelines插件,myecplise的讲解少之又少而且还不好用,我找了半天终于找到了Alibaba Java Coding Guidelines插件的离线安装包,已经亲测没问题,就跟svn一样用link...
《阿里巴巴Java编码规范2.1.1》是阿里巴巴开源的一款针对Java编程的代码规范指南,旨在提高代码质量、提升开发效率、确保代码可读性和可维护性。此规范被广泛应用于阿里巴巴集团及其关联公司,同时也成为业界参考的...
《阿里巴巴Java编码规范2.1.1》是阿里巴巴集团针对Java开发制定的一套详细编码标准,旨在提升代码质量,提高团队协作效率,并确保代码的可读性和可维护性。这份规范不仅适用于IntelliJ IDEA这样的集成开发环境,也对...
1. **代码风格检查**:通过配置IDEA的Alibaba Java Coding Guidelines插件,可以实时检查代码风格,确保符合规范。 2. **代码审查**:提倡团队成员之间进行代码审查,发现潜在问题,提高代码质量。 总之,《阿里...
【标题】:“淘宝网java开发Coding Formatter” 【描述】:“NULL 博文链接:https://itjiehun.iteye.com/blog/1292545” 在Java开发过程中,代码规范和格式化是非常重要的一环,它有助于提高代码的可读性和团队间...
Alibaba Java Coding GuidelinesAlibaba Java Coding GuidelinesAlibaba Java Coding GuidelinesAlibaba Java Coding Guidelines
《阿里巴巴 Java 编码指南》是业界广泛采用的编码规范,旨在提高代码质量和开发效率,尤其对于使用 IntelliJ IDEA 的开发者来说,此指南的兼容性更新至 2023.3+ 版本,确保了最新的开发环境支持。这份指南在 2024 年...
本篇文章将深入解析阿里巴巴Java编码规范,并结合“Alibaba-Java-Coding-Guidelines-1.0.3.zip”插件的使用,探讨如何将这些规范应用到实际开发中。 首先,我们需要理解Java编码规范的重要性。良好的编码规范能够...
Java Coding Interview 英文mobi 本资源转载自网络,如有侵权,请联系上传者或csdn删除 本资源转载自网络,如有侵权,请联系上传者或csdn删除
《The Art Of Java_Coding》源码的分享无疑为我们提供了一次深入理解Java编程艺术的宝贵机会。在Java的世界里,编码艺术不仅关乎技术的掌握,更体现在代码的优雅、可读性和可维护性上。这里,我们将探讨几个重要的...
《阿里巴巴Java编码规约》是阿里巴巴集团为了提升代码质量和开发效率而制定的一套规范标准,它涵盖了Java编程语言的各个方面,旨在帮助开发者写出更清晰、更健壮、更易维护的代码。以下是对该规约的详细解读: 1. *...
《阿里巴巴Java编码规范》是Java开发者的一份重要指南,它为编写高质量、可维护的Java代码提供了详尽的规则和建议。这份规范不仅涵盖了基础的编程风格,还深入到设计模式、异常处理、多线程等多个核心领域。下面将...