Java 编码规范

来源:互联网 发布:手机团购软件 编辑:程序博客网 时间:2024/05/16 00:42

问题

怎么规范项目组组员的java代码?

背景

大公司都有自己的编码规范,这里参考华为的编码规范,并加以适当的修改。

方案

一、编码格式规范

在Eclipse中导入如下两个文件,具体的导入方法可以参考:[http://blog.csdn.net/pengych_321/article/details/50659493]

  • codetemplates.xml
<?xml version="1.0" encoding="UTF-8"?><templates><template id="org.eclipse.jdt.ui.text.codetemplates.gettercomment" name="gettercomment" description="Comment for getter method" context="gettercomment_context" enabled="true" deleted="false">/** * @return Returns the ${bare_field_name}. */</template><template id="org.eclipse.jdt.ui.text.codetemplates.settercomment" name="settercomment" description="Comment for setter method" context="settercomment_context" enabled="true" deleted="false">/** * @param ${param} The ${bare_field_name} to set. */</template><template id="org.eclipse.jdt.ui.text.codetemplates.constructorcomment" name="constructorcomment" description="Comment for created constructors" context="constructorcomment_context" enabled="true" deleted="false">/** * ${tags} */</template><template id="org.eclipse.jdt.ui.text.codetemplates.typecomment" name="typecomment" description="Comment for created types" context="typecomment_context" enabled="true" deleted="false">/** * description: * * @author ${user} * @date ${date} * @since 1.0 */</template><template id="org.eclipse.jdt.ui.text.codetemplates.fieldcomment" name="fieldcomment" description="Comment for fields" context="fieldcomment_context" enabled="true" deleted="false">/** * 意义,目的和功能,以及被用到的地方&lt;br&gt; */</template><template id="org.eclipse.jdt.ui.text.codetemplates.methodcomment" name="methodcomment" description="Comment for non-overriding methods" context="methodcomment_context" enabled="true" deleted="false">/** * function: *  * ${tags}  */</template><template id="org.eclipse.jdt.ui.text.codetemplates.overridecomment" name="overridecomment" description="Comment for overriding methods" context="overridecomment_context" enabled="true" deleted="false">/* (non-Javadoc) * ${see_to_overridden} */</template><template id="org.eclipse.jdt.ui.text.codetemplates.newtype" name="newtype" description="Newly created files" context="newtype_context" enabled="true" deleted="false">/* * 文件名:${file_name} * 版权:Copyright by www.midea.com * 修改人:${user} * 修改时间:${date} */${package_declaration}${typecomment}${type_declaration}</template><template id="org.eclipse.jdt.ui.text.codetemplates.catchblock" name="catchblock" description="Code in new catch blocks" context="catchblock_context" enabled="true" deleted="false">// ${todo} Auto-generated catch block${exception_var}.printStackTrace();</template><template id="org.eclipse.jdt.ui.text.codetemplates.methodbody" name="methodbody" description="Code in created method stubs" context="methodbody_context" enabled="true" deleted="false">// ${todo} Auto-generated method stub${body_statement}</template><template id="org.eclipse.jdt.ui.text.codetemplates.constructorbody" name="constructorbody" description="Code in created constructor stubs" context="constructorbody_context" enabled="true" deleted="false">${body_statement}// ${todo} Auto-generated constructor stub</template><template id="org.eclipse.jdt.ui.text.codetemplates.getterbody" name="getterbody" description="Code in created getters" context="getterbody_context" enabled="true" deleted="false">return ${field};</template><template id="org.eclipse.jdt.ui.text.codetemplates.setterbody" name="setterbody" description="Code in created setters" context="setterbody_context" enabled="true" deleted="false">${field} = ${param};</template></templates>
  • codeformate.xml
<?xml version="1.0" encoding="UTF-8"?><profiles version="1"><profile name="mcity_codeformat" version="1"><setting id="org.eclipse.jdt.core.formatter.align_type_members_on_columns" value="false"/><setting id="org.eclipse.jdt.core.formatter.alignment_for_arguments_in_allocation_expression" value="16"/><setting id="org.eclipse.jdt.core.formatter.alignment_for_arguments_in_enum_constant" value="16"/><setting id="org.eclipse.jdt.core.formatter.alignment_for_arguments_in_explicit_constructor_call" value="18"/><setting id="org.eclipse.jdt.core.formatter.alignment_for_arguments_in_method_invocation" value="16"/><setting id="org.eclipse.jdt.core.formatter.alignment_for_arguments_in_qualified_allocation_expression" value="16"/><setting id="org.eclipse.jdt.core.formatter.alignment_for_binary_expression" value="18"/><setting id="org.eclipse.jdt.core.formatter.alignment_for_compact_if" value="16"/><setting id="org.eclipse.jdt.core.formatter.alignment_for_conditional_expression" value="0"/><setting id="org.eclipse.jdt.core.formatter.alignment_for_enum_constants" value="0"/><setting id="org.eclipse.jdt.core.formatter.alignment_for_expressions_in_array_initializer" value="16"/><setting id="org.eclipse.jdt.core.formatter.alignment_for_multiple_fields" value="16"/><setting id="org.eclipse.jdt.core.formatter.alignment_for_parameters_in_constructor_declaration" value="18"/><setting id="org.eclipse.jdt.core.formatter.alignment_for_parameters_in_method_declaration" value="18"/><setting id="org.eclipse.jdt.core.formatter.alignment_for_selector_in_method_invocation" value="4"/><setting id="org.eclipse.jdt.core.formatter.alignment_for_superclass_in_type_declaration" value="0"/><setting id="org.eclipse.jdt.core.formatter.alignment_for_superinterfaces_in_enum_declaration" value="16"/><setting id="org.eclipse.jdt.core.formatter.alignment_for_superinterfaces_in_type_declaration" value="0"/><setting id="org.eclipse.jdt.core.formatter.alignment_for_throws_clause_in_constructor_declaration" value="17"/><setting id="org.eclipse.jdt.core.formatter.alignment_for_throws_clause_in_method_declaration" value="17"/><setting id="org.eclipse.jdt.core.formatter.blank_lines_after_imports" value="2"/><setting id="org.eclipse.jdt.core.formatter.blank_lines_after_package" value="1"/><setting id="org.eclipse.jdt.core.formatter.blank_lines_before_field" value="1"/><setting id="org.eclipse.jdt.core.formatter.blank_lines_before_first_class_body_declaration" value="0"/><setting id="org.eclipse.jdt.core.formatter.blank_lines_before_imports" value="2"/><setting id="org.eclipse.jdt.core.formatter.blank_lines_before_member_type" value="1"/><setting id="org.eclipse.jdt.core.formatter.blank_lines_before_method" value="1"/><setting id="org.eclipse.jdt.core.formatter.blank_lines_before_new_chunk" value="1"/><setting id="org.eclipse.jdt.core.formatter.blank_lines_before_package" value="0"/><setting id="org.eclipse.jdt.core.formatter.blank_lines_between_type_declarations" value="2"/><setting id="org.eclipse.jdt.core.formatter.brace_position_for_annotation_type_declaration" value="end_of_line"/><setting id="org.eclipse.jdt.core.formatter.brace_position_for_anonymous_type_declaration" value="next_line"/><setting id="org.eclipse.jdt.core.formatter.brace_position_for_array_initializer" value="end_of_line"/><setting id="org.eclipse.jdt.core.formatter.brace_position_for_block" value="next_line"/><setting id="org.eclipse.jdt.core.formatter.brace_position_for_block_in_case" value="next_line"/><setting id="org.eclipse.jdt.core.formatter.brace_position_for_constructor_declaration" value="next_line"/><setting id="org.eclipse.jdt.core.formatter.brace_position_for_enum_constant" value="end_of_line"/><setting id="org.eclipse.jdt.core.formatter.brace_position_for_enum_declaration" value="end_of_line"/><setting id="org.eclipse.jdt.core.formatter.brace_position_for_method_declaration" value="next_line"/><setting id="org.eclipse.jdt.core.formatter.brace_position_for_switch" value="next_line"/><setting id="org.eclipse.jdt.core.formatter.brace_position_for_type_declaration" value="next_line"/><setting id="org.eclipse.jdt.core.formatter.comment.clear_blank_lines" value="true"/><setting id="org.eclipse.jdt.core.formatter.comment.format_comments" value="true"/><setting id="org.eclipse.jdt.core.formatter.comment.format_header" value="true"/><setting id="org.eclipse.jdt.core.formatter.comment.format_html" value="false"/><setting id="org.eclipse.jdt.core.formatter.comment.format_source_code" value="true"/><setting id="org.eclipse.jdt.core.formatter.comment.indent_parameter_description" value="true"/><setting id="org.eclipse.jdt.core.formatter.comment.indent_root_tags" value="true"/><setting id="org.eclipse.jdt.core.formatter.comment.insert_new_line_before_root_tags" value="insert"/><setting id="org.eclipse.jdt.core.formatter.comment.insert_new_line_for_parameter" value="insert"/><setting id="org.eclipse.jdt.core.formatter.comment.line_length" value="99"/><setting id="org.eclipse.jdt.core.formatter.compact_else_if" value="true"/><setting id="org.eclipse.jdt.core.formatter.continuation_indentation" value="1"/><setting id="org.eclipse.jdt.core.formatter.continuation_indentation_for_array_initializer" value="1"/><setting id="org.eclipse.jdt.core.formatter.format_guardian_clause_on_one_line" value="false"/><setting id="org.eclipse.jdt.core.formatter.indent_body_declarations_compare_to_enum_constant_header" value="true"/><setting id="org.eclipse.jdt.core.formatter.indent_body_declarations_compare_to_enum_declaration_header" value="true"/><setting id="org.eclipse.jdt.core.formatter.indent_body_declarations_compare_to_type_header" value="true"/><setting id="org.eclipse.jdt.core.formatter.indent_breaks_compare_to_cases" value="true"/><setting id="org.eclipse.jdt.core.formatter.indent_statements_compare_to_block" value="true"/><setting id="org.eclipse.jdt.core.formatter.indent_statements_compare_to_body" value="true"/><setting id="org.eclipse.jdt.core.formatter.indent_switchstatements_compare_to_cases" value="true"/><setting id="org.eclipse.jdt.core.formatter.indent_switchstatements_compare_to_switch" value="true"/><setting id="org.eclipse.jdt.core.formatter.indentation.size" value="4"/><setting id="org.eclipse.jdt.core.formatter.insert_new_line_after_annotation" value="insert"/><setting id="org.eclipse.jdt.core.formatter.insert_new_line_after_opening_brace_in_array_initializer" value="do not insert"/><setting id="org.eclipse.jdt.core.formatter.insert_new_line_at_end_of_file_if_missing" value="do not insert"/><setting id="org.eclipse.jdt.core.formatter.insert_new_line_before_catch_in_try_statement" value="insert"/><setting id="org.eclipse.jdt.core.formatter.insert_new_line_before_closing_brace_in_array_initializer" value="do not insert"/><setting id="org.eclipse.jdt.core.formatter.insert_new_line_before_else_in_if_statement" value="insert"/><setting id="org.eclipse.jdt.core.formatter.insert_new_line_before_finally_in_try_statement" value="insert"/><setting id="org.eclipse.jdt.core.formatter.insert_new_line_before_while_in_do_statement" value="insert"/><setting id="org.eclipse.jdt.core.formatter.insert_new_line_in_empty_anonymous_type_declaration" value="do not insert"/><setting id="org.eclipse.jdt.core.formatter.insert_new_line_in_empty_block" value="do not insert"/><setting id="org.eclipse.jdt.core.formatter.insert_new_line_in_empty_enum_constant" value="insert"/><setting id="org.eclipse.jdt.core.formatter.insert_new_line_in_empty_enum_declaration" value="insert"/><setting id="org.eclipse.jdt.core.formatter.insert_new_line_in_empty_method_body" value="do not insert"/><setting id="org.eclipse.jdt.core.formatter.insert_new_line_in_empty_type_declaration" value="do not insert"/><setting id="org.eclipse.jdt.core.formatter.insert_space_after_and_in_type_parameter" value="insert"/><setting id="org.eclipse.jdt.core.formatter.insert_space_after_assignment_operator" value="insert"/><setting id="org.eclipse.jdt.core.formatter.insert_space_after_at_in_annotation" value="do not insert"/><setting id="org.eclipse.jdt.core.formatter.insert_space_after_at_in_annotation_type_declaration" value="do not insert"/><setting id="org.eclipse.jdt.core.formatter.insert_space_after_binary_operator" value="insert"/><setting id="org.eclipse.jdt.core.formatter.insert_space_after_closing_angle_bracket_in_type_arguments" value="insert"/><setting id="org.eclipse.jdt.core.formatter.insert_space_after_closing_angle_bracket_in_type_parameters" value="insert"/><setting id="org.eclipse.jdt.core.formatter.insert_space_after_closing_brace_in_block" value="insert"/><setting id="org.eclipse.jdt.core.formatter.insert_space_after_closing_paren_in_cast" value="do not insert"/><setting id="org.eclipse.jdt.core.formatter.insert_space_after_colon_in_assert" value="insert"/><setting id="org.eclipse.jdt.core.formatter.insert_space_after_colon_in_case" value="insert"/><setting id="org.eclipse.jdt.core.formatter.insert_space_after_colon_in_conditional" value="insert"/><setting id="org.eclipse.jdt.core.formatter.insert_space_after_colon_in_for" value="insert"/><setting id="org.eclipse.jdt.core.formatter.insert_space_after_colon_in_labeled_statement" value="insert"/><setting id="org.eclipse.jdt.core.formatter.insert_space_after_comma_in_allocation_expression" value="insert"/><setting id="org.eclipse.jdt.core.formatter.insert_space_after_comma_in_annotation" value="insert"/><setting id="org.eclipse.jdt.core.formatter.insert_space_after_comma_in_array_initializer" value="insert"/><setting id="org.eclipse.jdt.core.formatter.insert_space_after_comma_in_constructor_declaration_parameters" value="insert"/><setting id="org.eclipse.jdt.core.formatter.insert_space_after_comma_in_constructor_declaration_throws" value="insert"/><setting id="org.eclipse.jdt.core.formatter.insert_space_after_comma_in_enum_constant_arguments" value="insert"/><setting id="org.eclipse.jdt.core.formatter.insert_space_after_comma_in_enum_declarations" value="insert"/><setting id="org.eclipse.jdt.core.formatter.insert_space_after_comma_in_explicitconstructorcall_arguments" value="insert"/><setting id="org.eclipse.jdt.core.formatter.insert_space_after_comma_in_for_increments" value="insert"/><setting id="org.eclipse.jdt.core.formatter.insert_space_after_comma_in_for_inits" value="insert"/><setting id="org.eclipse.jdt.core.formatter.insert_space_after_comma_in_method_declaration_parameters" value="insert"/><setting id="org.eclipse.jdt.core.formatter.insert_space_after_comma_in_method_declaration_throws" value="insert"/><setting id="org.eclipse.jdt.core.formatter.insert_space_after_comma_in_method_invocation_arguments" value="insert"/><setting id="org.eclipse.jdt.core.formatter.insert_space_after_comma_in_multiple_field_declarations" value="insert"/><setting id="org.eclipse.jdt.core.formatter.insert_space_after_comma_in_multiple_local_declarations" value="insert"/><setting id="org.eclipse.jdt.core.formatter.insert_space_after_comma_in_parameterized_type_reference" value="insert"/><setting id="org.eclipse.jdt.core.formatter.insert_space_after_comma_in_superinterfaces" value="insert"/><setting id="org.eclipse.jdt.core.formatter.insert_space_after_comma_in_type_arguments" value="insert"/><setting id="org.eclipse.jdt.core.formatter.insert_space_after_comma_in_type_parameters" value="insert"/><setting id="org.eclipse.jdt.core.formatter.insert_space_after_ellipsis" value="insert"/><setting id="org.eclipse.jdt.core.formatter.insert_space_after_opening_angle_bracket_in_parameterized_type_reference" value="do not insert"/><setting id="org.eclipse.jdt.core.formatter.insert_space_after_opening_angle_bracket_in_type_arguments" value="do not insert"/><setting id="org.eclipse.jdt.core.formatter.insert_space_after_opening_angle_bracket_in_type_parameters" value="do not insert"/><setting id="org.eclipse.jdt.core.formatter.insert_space_after_opening_brace_in_array_initializer" value="do not insert"/><setting id="org.eclipse.jdt.core.formatter.insert_space_after_opening_bracket_in_array_allocation_expression" value="do not insert"/><setting id="org.eclipse.jdt.core.formatter.insert_space_after_opening_bracket_in_array_reference" value="do not insert"/><setting id="org.eclipse.jdt.core.formatter.insert_space_after_opening_paren_in_annotation" value="do not insert"/><setting id="org.eclipse.jdt.core.formatter.insert_space_after_opening_paren_in_cast" value="do not insert"/><setting id="org.eclipse.jdt.core.formatter.insert_space_after_opening_paren_in_catch" value="do not insert"/><setting id="org.eclipse.jdt.core.formatter.insert_space_after_opening_paren_in_constructor_declaration" value="do not insert"/><setting id="org.eclipse.jdt.core.formatter.insert_space_after_opening_paren_in_enum_constant" value="do not insert"/><setting id="org.eclipse.jdt.core.formatter.insert_space_after_opening_paren_in_for" value="do not insert"/><setting id="org.eclipse.jdt.core.formatter.insert_space_after_opening_paren_in_if" value="do not insert"/><setting id="org.eclipse.jdt.core.formatter.insert_space_after_opening_paren_in_method_declaration" value="do not insert"/><setting id="org.eclipse.jdt.core.formatter.insert_space_after_opening_paren_in_method_invocation" value="do not insert"/><setting id="org.eclipse.jdt.core.formatter.insert_space_after_opening_paren_in_parenthesized_expression" value="do not insert"/><setting id="org.eclipse.jdt.core.formatter.insert_space_after_opening_paren_in_switch" value="do not insert"/><setting id="org.eclipse.jdt.core.formatter.insert_space_after_opening_paren_in_synchronized" value="do not insert"/><setting id="org.eclipse.jdt.core.formatter.insert_space_after_opening_paren_in_while" value="do not insert"/><setting id="org.eclipse.jdt.core.formatter.insert_space_after_postfix_operator" value="insert"/><setting id="org.eclipse.jdt.core.formatter.insert_space_after_prefix_operator" value="do not insert"/><setting id="org.eclipse.jdt.core.formatter.insert_space_after_question_in_conditional" value="insert"/><setting id="org.eclipse.jdt.core.formatter.insert_space_after_question_in_wildcard" value="do not insert"/><setting id="org.eclipse.jdt.core.formatter.insert_space_after_semicolon_in_for" value="insert"/><setting id="org.eclipse.jdt.core.formatter.insert_space_after_unary_operator" value="do not insert"/><setting id="org.eclipse.jdt.core.formatter.insert_space_before_and_in_type_parameter" value="insert"/><setting id="org.eclipse.jdt.core.formatter.insert_space_before_assignment_operator" value="insert"/><setting id="org.eclipse.jdt.core.formatter.insert_space_before_at_in_annotation_type_declaration" value="insert"/><setting id="org.eclipse.jdt.core.formatter.insert_space_before_binary_operator" value="insert"/><setting id="org.eclipse.jdt.core.formatter.insert_space_before_closing_angle_bracket_in_parameterized_type_reference" value="do not insert"/><setting id="org.eclipse.jdt.core.formatter.insert_space_before_closing_angle_bracket_in_type_arguments" value="do not insert"/><setting id="org.eclipse.jdt.core.formatter.insert_space_before_closing_angle_bracket_in_type_parameters" value="do not insert"/><setting id="org.eclipse.jdt.core.formatter.insert_space_before_closing_brace_in_array_initializer" value="do not insert"/><setting id="org.eclipse.jdt.core.formatter.insert_space_before_closing_bracket_in_array_allocation_expression" value="do not insert"/><setting id="org.eclipse.jdt.core.formatter.insert_space_before_closing_bracket_in_array_reference" value="do not insert"/><setting id="org.eclipse.jdt.core.formatter.insert_space_before_closing_paren_in_annotation" value="do not insert"/><setting id="org.eclipse.jdt.core.formatter.insert_space_before_closing_paren_in_cast" value="do not insert"/><setting id="org.eclipse.jdt.core.formatter.insert_space_before_closing_paren_in_catch" value="do not insert"/><setting id="org.eclipse.jdt.core.formatter.insert_space_before_closing_paren_in_constructor_declaration" value="do not insert"/><setting id="org.eclipse.jdt.core.formatter.insert_space_before_closing_paren_in_enum_constant" value="do not insert"/><setting id="org.eclipse.jdt.core.formatter.insert_space_before_closing_paren_in_for" value="do not insert"/><setting id="org.eclipse.jdt.core.formatter.insert_space_before_closing_paren_in_if" value="do not insert"/><setting id="org.eclipse.jdt.core.formatter.insert_space_before_closing_paren_in_method_declaration" value="do not insert"/><setting id="org.eclipse.jdt.core.formatter.insert_space_before_closing_paren_in_method_invocation" value="do not insert"/><setting id="org.eclipse.jdt.core.formatter.insert_space_before_closing_paren_in_parenthesized_expression" value="do not insert"/><setting id="org.eclipse.jdt.core.formatter.insert_space_before_closing_paren_in_switch" value="do not insert"/><setting id="org.eclipse.jdt.core.formatter.insert_space_before_closing_paren_in_synchronized" value="do not insert"/><setting id="org.eclipse.jdt.core.formatter.insert_space_before_closing_paren_in_while" value="do not insert"/><setting id="org.eclipse.jdt.core.formatter.insert_space_before_colon_in_assert" value="do not insert"/><setting id="org.eclipse.jdt.core.formatter.insert_space_before_colon_in_case" value="do not insert"/><setting id="org.eclipse.jdt.core.formatter.insert_space_before_colon_in_conditional" value="insert"/><setting id="org.eclipse.jdt.core.formatter.insert_space_before_colon_in_default" value="do not insert"/><setting id="org.eclipse.jdt.core.formatter.insert_space_before_colon_in_for" value="insert"/><setting id="org.eclipse.jdt.core.formatter.insert_space_before_colon_in_labeled_statement" value="do not insert"/><setting id="org.eclipse.jdt.core.formatter.insert_space_before_comma_in_allocation_expression" value="do not insert"/><setting id="org.eclipse.jdt.core.formatter.insert_space_before_comma_in_annotation" value="do not insert"/><setting id="org.eclipse.jdt.core.formatter.insert_space_before_comma_in_array_initializer" value="do not insert"/><setting id="org.eclipse.jdt.core.formatter.insert_space_before_comma_in_constructor_declaration_parameters" value="do not insert"/><setting id="org.eclipse.jdt.core.formatter.insert_space_before_comma_in_constructor_declaration_throws" value="do not insert"/><setting id="org.eclipse.jdt.core.formatter.insert_space_before_comma_in_enum_constant_arguments" value="do not insert"/><setting id="org.eclipse.jdt.core.formatter.insert_space_before_comma_in_enum_declarations" value="do not insert"/><setting id="org.eclipse.jdt.core.formatter.insert_space_before_comma_in_explicitconstructorcall_arguments" value="do not insert"/><setting id="org.eclipse.jdt.core.formatter.insert_space_before_comma_in_for_increments" value="do not insert"/><setting id="org.eclipse.jdt.core.formatter.insert_space_before_comma_in_for_inits" value="do not insert"/><setting id="org.eclipse.jdt.core.formatter.insert_space_before_comma_in_method_declaration_parameters" value="do not insert"/><setting id="org.eclipse.jdt.core.formatter.insert_space_before_comma_in_method_declaration_throws" value="do not insert"/><setting id="org.eclipse.jdt.core.formatter.insert_space_before_comma_in_method_invocation_arguments" value="do not insert"/><setting id="org.eclipse.jdt.core.formatter.insert_space_before_comma_in_multiple_field_declarations" value="do not insert"/><setting id="org.eclipse.jdt.core.formatter.insert_space_before_comma_in_multiple_local_declarations" value="do not insert"/><setting id="org.eclipse.jdt.core.formatter.insert_space_before_comma_in_parameterized_type_reference" value="do not insert"/><setting id="org.eclipse.jdt.core.formatter.insert_space_before_comma_in_superinterfaces" value="do not insert"/><setting id="org.eclipse.jdt.core.formatter.insert_space_before_comma_in_type_arguments" value="do not insert"/><setting id="org.eclipse.jdt.core.formatter.insert_space_before_comma_in_type_parameters" value="do not insert"/><setting id="org.eclipse.jdt.core.formatter.insert_space_before_ellipsis" value="do not insert"/><setting id="org.eclipse.jdt.core.formatter.insert_space_before_opening_angle_bracket_in_parameterized_type_reference" value="do not insert"/><setting id="org.eclipse.jdt.core.formatter.insert_space_before_opening_angle_bracket_in_type_arguments" value="do not insert"/><setting id="org.eclipse.jdt.core.formatter.insert_space_before_opening_angle_bracket_in_type_parameters" value="do not insert"/><setting id="org.eclipse.jdt.core.formatter.insert_space_before_opening_brace_in_annotation_type_declaration" value="insert"/><setting id="org.eclipse.jdt.core.formatter.insert_space_before_opening_brace_in_anonymous_type_declaration" value="insert"/><setting id="org.eclipse.jdt.core.formatter.insert_space_before_opening_brace_in_array_initializer" value="insert"/><setting id="org.eclipse.jdt.core.formatter.insert_space_before_opening_brace_in_block" value="insert"/><setting id="org.eclipse.jdt.core.formatter.insert_space_before_opening_brace_in_constructor_declaration" value="insert"/><setting id="org.eclipse.jdt.core.formatter.insert_space_before_opening_brace_in_enum_constant" value="insert"/><setting id="org.eclipse.jdt.core.formatter.insert_space_before_opening_brace_in_enum_declaration" value="insert"/><setting id="org.eclipse.jdt.core.formatter.insert_space_before_opening_brace_in_method_declaration" value="insert"/><setting id="org.eclipse.jdt.core.formatter.insert_space_before_opening_brace_in_switch" value="insert"/><setting id="org.eclipse.jdt.core.formatter.insert_space_before_opening_brace_in_type_declaration" value="insert"/><setting id="org.eclipse.jdt.core.formatter.insert_space_before_opening_bracket_in_array_allocation_expression" value="do not insert"/><setting id="org.eclipse.jdt.core.formatter.insert_space_before_opening_bracket_in_array_reference" value="do not insert"/><setting id="org.eclipse.jdt.core.formatter.insert_space_before_opening_bracket_in_array_type_reference" value="do not insert"/><setting id="org.eclipse.jdt.core.formatter.insert_space_before_opening_paren_in_annotation" value="do not insert"/><setting id="org.eclipse.jdt.core.formatter.insert_space_before_opening_paren_in_annotation_type_member_declaration" value="do not insert"/><setting id="org.eclipse.jdt.core.formatter.insert_space_before_opening_paren_in_catch" value="insert"/><setting id="org.eclipse.jdt.core.formatter.insert_space_before_opening_paren_in_constructor_declaration" value="do not insert"/><setting id="org.eclipse.jdt.core.formatter.insert_space_before_opening_paren_in_enum_constant" value="do not insert"/><setting id="org.eclipse.jdt.core.formatter.insert_space_before_opening_paren_in_for" value="insert"/><setting id="org.eclipse.jdt.core.formatter.insert_space_before_opening_paren_in_if" value="insert"/><setting id="org.eclipse.jdt.core.formatter.insert_space_before_opening_paren_in_method_declaration" value="do not insert"/><setting id="org.eclipse.jdt.core.formatter.insert_space_before_opening_paren_in_method_invocation" value="do not insert"/><setting id="org.eclipse.jdt.core.formatter.insert_space_before_opening_paren_in_parenthesized_expression" value="do not insert"/><setting id="org.eclipse.jdt.core.formatter.insert_space_before_opening_paren_in_switch" value="insert"/><setting id="org.eclipse.jdt.core.formatter.insert_space_before_opening_paren_in_synchronized" value="insert"/><setting id="org.eclipse.jdt.core.formatter.insert_space_before_opening_paren_in_while" value="insert"/><setting id="org.eclipse.jdt.core.formatter.insert_space_before_postfix_operator" value="do not insert"/><setting id="org.eclipse.jdt.core.formatter.insert_space_before_prefix_operator" value="do not insert"/><setting id="org.eclipse.jdt.core.formatter.insert_space_before_question_in_conditional" value="insert"/><setting id="org.eclipse.jdt.core.formatter.insert_space_before_question_in_wildcard" value="do not insert"/><setting id="org.eclipse.jdt.core.formatter.insert_space_before_semicolon" value="do not insert"/><setting id="org.eclipse.jdt.core.formatter.insert_space_before_semicolon_in_for" value="do not insert"/><setting id="org.eclipse.jdt.core.formatter.insert_space_before_unary_operator" value="do not insert"/><setting id="org.eclipse.jdt.core.formatter.insert_space_between_brackets_in_array_type_reference" value="do not insert"/><setting id="org.eclipse.jdt.core.formatter.insert_space_between_empty_braces_in_array_initializer" value="do not insert"/><setting id="org.eclipse.jdt.core.formatter.insert_space_between_empty_brackets_in_array_allocation_expression" value="do not insert"/><setting id="org.eclipse.jdt.core.formatter.insert_space_between_empty_parens_in_annotation_type_member_declaration" value="do not insert"/><setting id="org.eclipse.jdt.core.formatter.insert_space_between_empty_parens_in_constructor_declaration" value="do not insert"/><setting id="org.eclipse.jdt.core.formatter.insert_space_between_empty_parens_in_enum_constant" value="do not insert"/><setting id="org.eclipse.jdt.core.formatter.insert_space_between_empty_parens_in_method_declaration" value="do not insert"/><setting id="org.eclipse.jdt.core.formatter.insert_space_between_empty_parens_in_method_invocation" value="do not insert"/><setting id="org.eclipse.jdt.core.formatter.keep_else_statement_on_same_line" value="false"/><setting id="org.eclipse.jdt.core.formatter.keep_empty_array_initializer_on_one_line" value="true"/><setting id="org.eclipse.jdt.core.formatter.keep_imple_if_on_one_line" value="true"/><setting id="org.eclipse.jdt.core.formatter.keep_then_statement_on_same_line" value="false"/><setting id="org.eclipse.jdt.core.formatter.lineSplit" value="99"/><setting id="org.eclipse.jdt.core.formatter.number_of_blank_lines_at_beginning_of_method_body" value="0"/><setting id="org.eclipse.jdt.core.formatter.number_of_empty_lines_to_preserve" value="1"/><setting id="org.eclipse.jdt.core.formatter.put_empty_statement_on_new_line" value="false"/><setting id="org.eclipse.jdt.core.formatter.tabulation.char" value="space"/><setting id="org.eclipse.jdt.core.formatter.tabulation.size" value="4"/><setting id="org.eclipse.jdt.core.formatter.use_tabs_only_for_leading_indentations" value="false"/></profile></profiles>
  • checkstyle.xml
<?xml version="1.0" encoding="UTF-8"?><!DOCTYPE module PUBLIC "-//Puppy Crawl//DTD Check Configuration 1.2//EN" "http://www.puppycrawl.com/dtds/configuration_1_2.dtd"><!-- Generated by RHY @will_awoke --><module name="Checker">     <property name="charset" value="UTF-8"/>       <property name="severity" value="warning"/>    <!-- Checks for Size Violations.  -->     <!-- 检查文件的长度(行) default max=2000 -->     <module name="FileLength">              <property name="max" value="2500"/>          </module>    <!-- Checks that property files contain the same keys. -->   <!-- 检查**.properties配置文件 是否有相同的key  <module name="Translation">           </module>     -->   <module name="TreeWalker">    <!-- Checks for imports    -->                   <!-- 必须导入类的完整路径,即不能使用*导入所需的类 -->      <module name="AvoidStarImport"/>      <!-- 检查是否从非法的包中导入了类 illegalPkgs: 定义非法的包名称-->      <module name="IllegalImport"/> <!-- defaults to sun.* packages -->      <!-- 检查是否导入了不必显示导入的类-->      <module name="RedundantImport"/>      <!-- 检查是否导入的包没有使用-->      <module name="UnusedImports"/>    <!-- Checks for whitespace               <module name="EmptyForIteratorPad"/>    <module name="MethodParamPad"/>    <module name="NoWhitespaceAfter"/>    <module name="NoWhitespaceBefore"/>    <module name="OperatorWrap"/>    <module name="ParenPad"/>    <module name="TypecastParenPad"/>    <module name="WhitespaceAfter"/>    <module name="WhitespaceAround"/>    -->    <!-- 检查类和接口的javadoc 默认不检查author 和version tags             authorFormat: 检查author标签的格式            versionFormat: 检查version标签的格式            scope: 可以检查的类的范围,例如:public只能检查public修饰的类,private可以检查所有的类            excludeScope: 不能检查的类的范围,例如:public,public的类将不被检查,但访问权限小于public的类仍然会检查,其他的权限以此类推            tokens: 该属性适用的类型,例如:CLASS_DEF,INTERFACE_DEF -->    <module name="JavadocType">          <property name="authorFormat" value="\S"/>        <property name="scope" value="protected"/>              <property name="tokens" value="CLASS_DEF,INTERFACE_DEF"/>      </module>    <!-- 检查方法的javadoc的注释            scope: 可以检查的方法的范围,例如:public只能检查public修饰的方法,private可以检查所有的方法            allowMissingParamTags: 是否忽略对参数注释的检查            allowMissingThrowsTags: 是否忽略对throws注释的检查            allowMissingReturnTag: 是否忽略对return注释的检查 -->    <module name="JavadocMethod">          <property name="scope" value="private"/>        <property name="allowMissingParamTags" value="false"/>        <property name="allowMissingThrowsTags" value="false"/>        <property name="allowMissingReturnTag" value="false"/>        <property name="tokens" value="METHOD_DEF"/>        <property name="allowUndeclaredRTE" value="true"/>        <property name="allowThrowsTagsForSubclasses" value="true"/>        <!--允许get set 方法没有注释-->        <property name="allowMissingPropertyJavadoc" value="true"/>    </module>      <!-- 检查类变量的注释            scope: 检查变量的范围,例如:public只能检查public修饰的变量,private可以检查所有的变量 -->        <module name="JavadocVariable">        <property name="scope" value="private"/>      </module>      <!--option: 定义左大括号'{'显示位置,eol在同一行显示,nl在下一行显示        maxLineLength: 大括号'{'所在行行最多容纳的字符数        tokens: 该属性适用的类型,例:CLASS_DEF,INTERFACE_DEF,METHOD_DEF,CTOR_DEF -->      <module name="LeftCurly">         <property name="option" value="nl"/>    </module>    <!-- NeedBraces 检查是否应该使用括号的地方没有加括号        tokens: 定义检查的类型 -->      <module name="NeedBraces"/>      <!-- Checks the placement of right curly braces ('}') for  else, try, and catch tokens. The policy to verify is specified using property  option.         option: 右大括号是否单独一行显示        tokens: 定义检查的类型  -->      <module name="RightCurly">            <property name="option" value="alone"/>         </module>    <!-- 检查在重写了equals方法后是否重写了hashCode方法 -->     <module name="EqualsHashCode"/>    <!--  Checks for illegal instantiations where a factory method is preferred.        Rationale: Depending on the project, for some classes it might be preferable to create instances through factory methods rather than calling the constructor.        A simple example is the java.lang.Boolean class. In order to save memory and CPU cycles, it is preferable to use the predefined constants TRUE and FALSE. Constructor invocations should be replaced by calls to Boolean.valueOf().        Some extremely performance sensitive projects may require the use of factory methods for other classes as well, to enforce the usage of number caches or object pools. -->      <module name="IllegalInstantiation">          <property name="classes" value="java.lang.Boolean"/>      </module>    <!-- Checks for Naming Conventions.   命名规范   -->    <!-- local, final variables, including catch parameters -->    <module name="LocalFinalVariableName"/>    <!-- local, non-final variables, including catch parameters-->     <module name="LocalVariableName"/>    <!-- static, non-final fields -->    <module name="StaticVariableName">        <property name="format" value="(^[A-Z0-9_]{0,19}$)"/>        </module>      <!-- packages -->    <module name="PackageName" >        <property name="format" value="^[a-z]+(\.[a-z][a-z0-9]*)*$"/>    </module>     <!-- classes and interfaces -->    <module name="TypeName">          <property name="format" value="(^[A-Z][a-zA-Z0-9]{0,19}$)"/>       </module>    <!-- methods -->      <module name="MethodName">                <property name="format" value="(^[a-z][a-zA-Z0-9]{0,19}$)"/>             </module>     <!-- non-static fields -->    <module name="MemberName">          <property name="format" value="(^[a-z][a-z0-9][a-zA-Z0-9]{0,19}$)"/>             </module>    <!-- parameters -->    <module name="ParameterName">        <property name="format" value="(^[a-z][a-zA-Z0-9_]{0,19}$)"/>             </module>    <!-- constants (static,  final fields) -->    <module name="ConstantName">         <property name="format" value="(^[A-Z0-9_]{0,19}$)"/>          </module>    <!-- 代码缩进   -->    <module name="Indentation">            </module>    <!-- Checks for redundant exceptions declared in throws clause such as duplicates, unchecked exceptions or subclasses of another declared exception.       检查是否抛出了多余的异常      <module name="RedundantThrows">        <property name="logLoadErrors" value="true"/>        <property name="suppressLoadErrors" value="true"/>     </module>    -->      <!--  Checks for overly complicated boolean expressions. Currently finds code like  if (b == true), b || true, !false, etc.          检查boolean值是否冗余的地方         Rationale: Complex boolean logic makes code hard to understand and maintain. -->      <module name="SimplifyBooleanExpression"/>    <!--  Checks for overly complicated boolean return statements. For example the following code         检查是否存在过度复杂的boolean返回值         if (valid())            return false;         else            return true;         could be written as            return !valid();         The Idea for this Check has been shamelessly stolen from the equivalent PMD rule. -->      <module name="SimplifyBooleanReturn"/>      <!-- Checks that a class which has only private constructors is declared as final.只有私有构造器的类必须声明为final-->      <module name="FinalClass"/>     <!--  Make sure that utility classes (classes that contain only static methods or fields in their API) do not have a public constructor.         确保Utils类(只提供static方法和属性的类)没有public构造器。         Rationale: Instantiating utility classes does not make sense. Hence the constructors should either be private or (if you want to allow subclassing) protected. A common mistake is forgetting to hide the default constructor.         If you make the constructor protected you may want to consider the following constructor implementation technique to disallow instantiating subclasses:         public class StringUtils // not final to allow subclassing         {             protected StringUtils() {                 throw new UnsupportedOperationException(); // prevents calls from subclass             }             public static int count(char c, String s) {                 // ...             }         }     <module name="HideUtilityClassConstructor"/>     -->     <!--  Checks visibility of class members. Only static final members may be public; other class members must be private unless property protectedAllowed or packageAllowed is set.        检查class成员属性可见性。只有static final 修饰的成员是可以public的。其他的成员属性必需是private的,除非属性protectedAllowed或者packageAllowed设置了true.         Public members are not flagged if the name matches the public member regular expression (contains "^serialVersionUID$" by default). Note: Checkstyle 2 used to include "^f[A-Z][a-zA-Z0-9]*$" in the default pattern to allow CMP for EJB 1.1 with the default settings. With EJB 2.0 it is not longer necessary to have public access for persistent fields, hence the default has been changed.         Rationale: Enforce encapsulation. 强制封装 -->      <module name="VisibilityModifier"/>     <!-- 每一行只能定义一个变量 -->    <module name="MultipleVariableDeclarations">           </module>     <!-- Checks the style of array type definitions. Some like Java-style: public static void main(String[] args) and some like C-style: public static void main(String args[])          检查再定义数组时,采用java风格还是c风格,例如:int[] num是java风格,int num[]是c风格。默认是java风格-->      <module name="ArrayTypeStyle">     </module>    <!-- Checks that there are no "magic numbers", where a magic number is a numeric literal that is not defined as a constant. By default, -1, 0, 1, and 2 are not considered to be magic numbers.     <module name="MagicNumber">       </module>    -->      <!-- A check for TODO: comments. Actually it is a generic regular expression matcher on Java comments. To check for other patterns in Java comments, set property format.          检查是否存在TODO(待处理) TODO是javaIDE自动生成的。一般代码写完后要去掉。       -->      <module name="TodoComment"/>      <!--  Checks that long constants are defined with an upper ell. That is ' L' and not 'l'. This is in accordance to the Java Language Specification,  Section 3.10.1.        检查是否在long类型是否定义了大写的L.字母小写l和数字1(一)很相似。        looks a lot like 1. -->      <module name="UpperEll"/>    <!--  Checks that switch statement has "default" clause. 检查switch语句是否有‘default’从句         Rationale: It's usually a good idea to introduce a default case in every switch statement.        Even if the developer is sure that all currently possible cases are covered, this should be expressed in the default branch,        e.g. by using an assertion. This way the code is protected aginst later changes, e.g. introduction of new types in an enumeration type. -->     <module name="MissingSwitchDefault"/>     <!--检查switch中case后是否加入了跳出语句,例如:return、break、throw、continue -->    <module name="FallThrough"/>      <!-- Checks the number of parameters of a method or constructor. max default 7个. -->        <module name="ParameterNumber">            <property name="max" value="5"/>                  </module>    <!-- 每行字符数 -->        <module name="LineLength">        <property name="max" value="200"/>           </module>      <!-- Checks for long methods and constructors. max default 150行. max=300 设置长度300 -->     <module name="MethodLength">        <property name="max" value="300"/>                     </module>            <!-- ModifierOrder 检查修饰符的顺序,默认是 public,protected,private,abstract,static,final,transient,volatile,synchronized,native -->      <module name="ModifierOrder">              </module>          <!-- 检查是否有多余的修饰符,例如:接口中的方法不必使用public、abstract修饰  -->    <module name="RedundantModifier">           </module>    <!--- 字符串比较必须使用 equals() -->       <module name="StringLiteralEquality">              </module>     <!-- if-else嵌套语句个数 最多4层 -->    <module name="NestedIfDepth">              <property name="max" value="3"/>             </module>      <!-- try-catch 嵌套语句个数 最多2层 -->    <module name="NestedTryDepth">        <property name="max" value="2"/>             </module>      <!-- 返回个数 -->       <module name="ReturnCount">              <property name="max" value="5"/>        <property name="format" value="^$"/>              </module>                    </module></module>

二、java代码规范

传说中的华为编码军规 …

转至元数据起始1.1      排版1.1.1      规则规则1      程序块要采用缩进风格编写,缩进的空格数为4个,不允许使用TAB缩进。(1.42+)说明:缩进使程序更易阅读,使用空格缩进可以适应不同操作系统与不同开发工具。规则2      分界符(如大括号‘{’和‘}’)应各独占一行,同时与引用它们的语句左对齐。在函数体的开始、类和接口的定义、以及iffordowhileswitchcase语句中的程序或者static、,synchronized等语句块中都要采用如上的缩进方式。(1.42+)       示例:       if (a>b)   {       doStart();   }规则3      较长的语句、表达式或参数(>80字符)要分成多行书写,长表达式要在低优先级操作符处划分新行,操作符放在新行之首,划分出的新行要进行适当的缩进,使排版整齐,语句可读。(1.42+)示例:        if (logger.isDebugEnabled())        {            logger.debug("Session destroyed,call-id"                    + event.getSession().getCallId());        }规则4      不允许把多个短语句写在一行中,即一行只写一条语句(1.42+)       说明:阅读代码更加清晰       示例:如下例子不符合规范。       Object o = new Object(); Object b = null;规则5      if, for, do, while, case, switch, default 等语句自占一行,且if, for, do, while,switch等语句的执行语句无论多少都要加括号{},case 的执行语句中如果定义变量必须加括号{}。(1.42+)       说明:阅读代码更加清晰,减少错误产生       示例:       if (a>b){doStart();}   case x:{int i = 9;}规则6      相对独立的程序块之间、变量说明之后必须加空行。 (1.42+)说明:阅读代码更加清晰示例:if(a > b){doStart();}//此处是空行return;规则7      在两个以上的关键字、变量、常量进行对等操作时,它们之间的操作符之前、之后或者前后要加空格;进行非对等操作时,如果是关系密切的立即操作符(如.),后不应加空格。(1.42+)说明:阅读代码更加清晰示例:if (a == b){objectA.doStart();}a *= 2;1.1.2      建议建议1     类属性和类方法不要交叉放置,不同存取范围的属性或者方法也尽量不要交叉放置。(1.42+)格式:类定义{    类的公有属性定义    类的保护属性定义    类的私有属性定义    类的公有方法定义    类的保护方法定义    类的私有方法定义}建议2     修饰词按照指定顺序书写:[访问权限][static][final] 。(1.42+)       示例:       public static final String str = “abc”;1.2      注释1.2.1      规则规则1      源程序注释量必须在30%以上。(1.42+)说明:由于每个文件的代码注释不一定都可以达到30%,建议以一个系统内部模块作为单位进行检查规则2      包的注释:写入一个名为 package.html 的HTML格式的说明文件放入包所在路径。包的注释内容:简述本包的作用、详细描述本包的内容、产品模块名称和版本、公司版权。(1.42+)说明:方便JavaDoc收集,方便对包的了解示例:com/huawei/iin/websmap/comm/package.html<html><body><p>一句话简述。<p>详细描述。<p>产品模块名称和版本<br>公司版权信息</body></html>示例:<html><body><P>为 WEBSMAP 提供通信类,上层业务使用本包的通信类与 SMP-B 进行通信。<p>详细描述。。。。。。。。<p>IIN V100R001 WEBSMAP<br>(C) 版权所有 2000-2001 华为技术有限公司</body></html>规则3      类和接口的注释放在class 或者 interface 关键字之前,import 关键字之后。注释主要是一句话功能简述与功能详细描述。类注释使用“/**  */”注释方式(1.42+)说明:方便JavaDoc收集,没有import可放在package之后。注释可根据需要列出:作者、内容、功能、与其它类的关系等。功能详细描述部分说明该类或者接口的功能、作用、使用方法和注意事项,每次修改后增加作者和更新版本号和日期,@since 表示从那个版本开始就有这个类或者接口,@deprecated 表示不建议使用该类或者接口。/** * 〈一句话功能简述〉 * 〈功能详细描述〉 * @author     [作者](必须)* @see         [相关类/方法](可选) * @since      [产品/模块版本] (必须) * @deprecated  (可选) */示例:package com.huawei.iin.logwebsmap.comm;import java.util.*;/** * LogManager 类集中控制对日志读写的操作。 * 全部为静态变量和静态方法,对外提供统一接口。分配对应日志类型的读写器, * 读取或写入符合条件的日志纪录。 * @author      张三,李四,王五* @see          LogIteraotor * @see          BasicLog * @since       CommonLog1.0 */public class LogManager规则4      类属性(成员变量)、公有和保护方法注释:写在类属性、公有和保护方法上面,注释方式为“/**  */”.(1.42+)示例:/** * 注释内容 */private String logType;/** * 注释内容 */public void write()规则5      公有和保护方法注释内容:列出方法的一句话功能简述、功能详细描述、输入参数、输出参数、返回值、异常等。(1.42+)格式:/** * 〈一句话功能简述〉 * 〈功能详细描述〉 * @param [参数1]     [参数1说明] * @param [参数2]     [参数2说明] * @return  [返回类型说明] * @exception/throws [异常类型] [异常说明] * @see   [类、类#方法、类#成员]* @since [起始版本] * @deprecated */说明:@since 表示从那个版本开始就有这个方法,如果是最初版本就存在的方法无需说明;@exception或throws 列出可能仍出的异常;@deprecated 表示不建议使用该方法。示例:    /**     * 根据日志类型和时间读取日志。     * 分配对应日志类型的LogReader, 指定类型、查询时间段、条件和反复器缓冲数,     * 读取日志记录。查询条件为null或0的表示没有限制,反复器缓冲数为0读不到日志。     * 查询时间为左包含原则,即 [startTime, endTime) 。     * @param logTypeName  日志类型名(在配置文件中定义的)     * @param startTime     查询日志的开始时间     * @param endTime      查询日志的结束时间     * @param logLevel      查询日志的级别     * @param userName     查询该用户的日志     * @param bufferNum    日志反复器缓冲记录数     * @return  结果集,日志反复器     * @since  1.2     */    public static LogIterator read(String logType, Date startTime, Date endTime, int logLevel, String userName, int bufferNum)规则6      对于方法内部用throw语句抛出的异常,必须在方法的注释中标明,对于所调用的其他方法所抛出的异常,选择主要的在注释中说明。 对于非RuntimeException,即throws子句声明会抛出的异常,必须在方法的注释中标明。(1.42+)说明:异常注释用@exception或@throws表示,在JavaDoc中两者等价,但推荐用@exception标注Runtime异常,@throws标注非Runtime异常。异常的注释必须说明该异常的含义及什么条件下抛出该异常。规则7      注释应与其描述的代码相近,对代码的注释应放在其上方,并与其上面的代码用空行隔开,注释与所描述内容进行同样的缩排。(1.42+)说明:可使程序排版整齐,并方便注释的阅读与理解。示例:/* * 注释*/public void example2( ){    // 注释    CodeBlock One    // 注释    CodeBlock Two}/* * 注释*/public void example( ){    // 注释    CodeBlock One    // 注释    CodeBlock Two}规则8      对于switch语句下的case语句,必须在每个case分支结束前加上break语句。(1.42+)说明:break才能真正表示该switch执行结束,不然可能会进入该case以后的分支。至于语法上合法的场景“一个case后进入下一个case处理”,应该在编码设计上就避免。规则9      修改代码同时修改相应的注释,以保证注释与代码的一致性。不再有用的注释要删除。(1.42+)规则10   注释的内容要清楚、明了,含义准确,防止注释二义性。(1.42+)说明:错误的注释不但无益反而有害。规则11   避免在注释中使用缩写,特别是不常用缩写。(1.42+)说明:在使用缩写时或之前,应对缩写进行必要的说明。规则12   对重载父类的方法必须进行@Override声明(5.0+)说明:可清楚说明此方法是重载父类的方法,保证重载父类的方法时不会因为单词写错而造成错误(写错方法名或者参数个数,类型都会编译无法通过)示例:   @Override   public void doRequest(SipServletRequest req) throws ServletException,          IOException1.2.2      建议建议1     避免在一行代码或表达式的中间插入注释。(1.42+)说明:除非必要,不应在代码或表达中间插入注释,否则容易使代码可理解性变差。建议2     在代码的功能、意图层次上进行注释,提供有用、额外的信息。(1.42+)说明:注释的目的是解释代码的目的、功能和采用的方法,提供代码以外的信息,帮助读者理解代码,防止没必要的重复注释信息。示例:如下注释意义不大。// 如果 receiveFlag 为真if (receiveFlag)而如下的注释则给出了额外有用的信息。// 如果从连结收到消息if (receiveFlag)建议3     对关键变量的定义和分支语句(条件分支、循环语句等)必须编写注释。(1.42+)说明:这些语句往往是程序实现某一特定功能的关键,对于维护人员来说,良好的注释帮助更好的理解程序,有时甚至优于看设计文档。建议4     注释应考虑程序易读及外观排版的因素,使用的语言若是中、英兼有的,建议多使用中文,除非能用非常流利准确的英文表达。中文注释中需使用中文标点。方法和类描述的第一句话尽量使用简洁明了的话概括一下功能,然后加以句号。接下来的部分可以详细描述。(1.42+)说明:注释语言不统一,影响程序易读性和外观排版,出于对维护人员的考虑,建议使用中文。JavaDoc工具收集简介的时候使用选取第一句话。建议5     方法内的单行注释使用 //。(1.42+)说明:调试程序的时候可以方便的使用 /* 。。。*/ 注释掉一长段程序。建议6     一些复杂的代码需要说明。(1.42+)示例:这里主要是对闰年算法的说明。      //1. 如果能被4整除,是闰年;      //2. 如果能被100整除,不是闰年;      //3. 如果能被400整除,是闰年。建议7     使用Html标签使JavaDoc生成更加美观。(1.42+)示例:/**     * Returns a hash code for this string. The hash code for a     * <code>String</code> object is computed as     * <blockquote><pre>     * s[0]*31^(n-1) + s[1]*31^(n-2) + ... + s[n-1]     * </pre></blockquote>     * using <code>int</code> arithmetic, where <code>s[i]</code> is the     * <i>i</i>th character of the string, <code>n</code> is the length * of     * the string, and <code>^</code> indicates exponentiation.     * (The hash value of the empty string is zero.)     *     * @return  a hash code value for this object.     */public int hashCode()       生成后的JavaDoc图1  生成后的JavaDoc1.3      命名1.3.1      规则规则1      类名和接口使用类意义完整的英文描述,每个英文单词的首字母使用大写、其余字母使用小写的大小写混合法。(1.42+)示例:OrderInformation, CustomerList, LogManager, LogConfig, SmpTransaction规则2      方法名使用类意义完整的英文描述:第一个单词的字母使用小写、剩余单词首字母大写其余字母小写的大小写混合法。(1.42+)示例:private void calculateRate();public void addNewOrder();规则3      方法中,存取属性的方法采用setter 和 getter方法,动作方法采用动词和动宾结构。(1.42+)格式:get + 非布尔属性名()is + 布尔属性名()set + 属性名()动词()动词 + 宾语()示例:public String getType();public boolean isFinished();public void setVisible(boolean);public void show();public void addKeyListener(Listener);规则4      属性名使用意义完整的英文描述,第一个单词的字母使用小写,剩余单词首字母大写其余字母小写的大小写混合法。属性名不能与方法名相同。(1.42+)示例:private customerName;private orderNumber;private smpSession;规则5      常量名使用全大写的英文描述,英文单词之间用下划线分隔开,并且使用 static final修饰。(1.42+)示例:public static final int MAX_VALUE = 1000;public static final String DEFAULT_START_DATE = "2001-12-08";1.3.2      建议建议1     包名采用域后缀倒置的加上自定义的包名,采用小写字母,都应该以com.huawei开头(不包括一些特殊原因)。在部门内部应该规划好包名的范围,防止产生冲突。部门内部产品使用部门的名称加上模块名称。产品线的产品使用产品的名称加上模块的名称。(1.42+)说明:除特殊原因包结构都必须以com.huawei开头,如果因为OEM合作等关系,可以不做要求。格式:com.huawei.产品名.模块名称示例:融合WEBSMAP包名  com.huawei.iin.websmap建议2     通过对函数或过程、变量、结构等正确的命名以及合理地组织代码的结构,使代码成为自注释的。(1.42+)说明:清晰准确的函数、变量等的命名,可增加代码可读性,并减少不必要的注释。建议3     常用组件类的命名以组件名加上组件类型名结尾。(1.42+)示例:Application 类型的,命名以App 结尾——MainAppFrame 类型的,命名以Frame 结尾——TopoFramePanel 类型的,建议命名以Panel 结尾——CreateCircuitPanelBean 类型的,建议命名以Bean 结尾——DataAccessBeanEJB 类型的,建议命名以EJB 结尾——DBProxyEJBApplet 类型的,建议命名以Applet 结尾——PictureShowApplet建议4     如果函数名超过15 个字母,可采用以去掉元音字母的方法或者以行业内约定俗成的缩写方式缩写函数名。(1.42+)示例:getCustomerInformation()  改为  getCustomerInfo()建议5     准确地确定成员函数的存取控制符号:只是该类内部调用的函数使用 private 属性,继承类可以使用的使用protected属性,同包类可以调用的使用默认属性(不加属性控制符号),对外公开的函数使用public属性(1.42+)示例:protected void getUserName(){。。。。。。}private void calculateRate(){。。。。。。}建议6     含有集合意义的属性命名,尽量包含其复数的意义。(1.42+)示例:customers,  orderItems1.4      编码1.4.1      规则规则1      数据库操作、IO操作等需要使用结束close()的对象必须在try -catch-finallyfinally中close(),如果有多个IO对象需要close(),需要分别对每个对象的close()方法进行try-catch,防止一个IO对象关闭失败其他IO对象都未关闭。(1.42+)示例:try{    // ... ...}catch(IOException ioe){     //... ...}finally{    try    {          out.close();    }    catch (IOException ioe)    {         //... ...}try    {          in.close();    }    catch (IOException ioe)    {         //... ...    }}规则2      系统非正常运行产生的异常捕获后,如果不对该异常进行处理,则应该记录日志。 (1.42+)说明:此规则指通常的系统非正常运行产生的异常,不包括一些基于异常的设计。若有特殊原因必须用注释加以说明。示例:try{    //.... ...}catch (IOException ioe){    logger.error(ioe);}规则3      自己抛出的异常必须要填写详细的描述信息。(1.42+)说明:便于问题定位。示例:throw new  IOException("Writing data error! Data: " + data.toString());规则4      运行时异常使用RuntimeException的子类来表示,不用在可能抛出异常的方法声明上加throws子句。非运行期异常是从Exception继承而来的,必须在方法声明上加throws子句。(1.42+)说明:非运行期异常是由外界运行环境决定异常抛出条件的异常,例如文件操作,可能受权限、磁盘空间大小的影响而失败,这种异常是程序本身无法避免的,需要调用者明确考虑该异常出现时该如何处理方法,因此非运行期异常必须有throws子句标出,不标出或者调用者不捕获该类型异常都会导致编译失败,从而防止程序员本身疏忽。运行期异常是程序在运行过程中本身考虑不周导致的异常,例如传入错误的参数等。抛出运行期异常的目的是防止异常扩散,导致定位困难。因此在做异常体系设计时要根据错误的性质合理选择自定义异常的继承关系。还有一种异常是Error 继承而来的,这种异常由虚拟机自己维护,表示发生了致命错误,程序无法继续运行例如内存不足。我们自己的程序不应该捕获这种异常,并且也不应该创建该种类型的异常。规则5      在程序中使用异常处理还是使用错误返回码处理,根据是否有利于程序结构来确定,并且异常和错误码不应该混合使用,推荐使用异常。(1.42+)说明:一个系统或者模块应该统一规划异常类型和返回码的含义。但是不能用异常来做一般流程处理的方式,不要过多地使用异常,异常的处理效率比条件分支低,而且异常的跳转流程难以预测。注意:Java 5.0 程序内部的错误码可以使用枚举来表示。规则6      注意运算符的优先级,并用括号明确表达式的操作顺序,避免使用默认优先级。(1.42+)说明:防止阅读程序时产生误解,防止因默认的优先级与设计思想不符而导致程序出错。示例:下列语句中的表达式word = (high << 8) | low     (1)if ((a | b) && (a & c))      (2)if ((a | b) < (c & d))       (3)如果书写为high << 8 | lowa | b && a & ca | b < c & d(1)(2)虽然不会出错,但语句不易理解;(3)造成了判断条件出错。规则7      避免使用不易理解的数字,用有意义的标识来替代。涉及物理状态或者含有物理意义的常量,不应直接使用数字,必须用有意义的静态变量或者枚举来代替。使用异常来表示方法执行错误,而不是使用C++的错误返回码方式。(1.42+)示例:如下的程序可读性差。if (state == 0){    state = 1;    ...  // program code}应改为如下形式:private final static int TRUNK_IDLE = 0;private final static int TRUNK_BUSY = 1;private final static int TRUNK_UNKNOWN = -1;if (state == TRUNK_IDLE){    state = TRUNK_BUSY;    ...  // program code}注意:Java 5.0 下建议使用枚举来表示。异常:public void function(){... throw new RuntimeException(“。。。”);}规则8      数组声明的时候使用 int[] index ,而不要使用 int index[] 。(1.42+)说明:使用int index[] 格式使程序的可读性较差,int [] index 表示声明了一个int数组(int [])叫做index示例:如下程序可读性差:public int getIndex()[]{    ....}如下程序可读性好:public int[] getIndex(){    ....}规则9      不要使用 System.out 与 System.err 进行控制台打印,应该使用工具类(如:日志工具)进行统一记录或者打印。(1.42+)说明:代码发布的时候可以统一关闭控制台打印,代码调试的时候又可以打开控制台打印,方便调试。规则10   用调测开关来切换软件的DEBUG版和正式版,而不要同时存在正式版本和DEBUG版本的不同源文件,以减少维护的难度。     (1.42+)规则11   集合必须指定模板类型(5.0+)说明:方便程序阅读,除去强制转换代码示例:Map<String,MyObject> map = new HashMap<String,MyObject>();规则12   一个文件不要定义两个类(并非指内部类)。(1.42+)说明:方便程序的阅读与代码的维护规则13   所有的数据类必须覆写toString()、hashCode()、equals() 方法,toString()方法返回该类有意义的内容。(1.42+)说明:方便数据类的比较,父类如果实现了比较合理的toString() ,子类可以继承不必再重写。hashCode与equals可以使用eclipse自动生成。示例:public TopoNode{      private String nodeName;      public String toString()      {               return "NodeName : " + nodeName;      }}规则14   判断语句不要使用”* == true”来判断为真说明:方便阅读,减少没有必要的计算以下错误:if (ok == true){……}以下正确:if (ok){……}规则15   不要写没有必要的向上强制转型。(1.42+)说明:没必要写的向上强制转型会浪费性能,增加代码阅读难度示例:以下错误:FileInputStream fis = new FileInputStream(f);InputStream is = (InputStream)fis;1.4.2      建议建议1     记录异常不要保存exception.getMessage(),而要记录exception.toString(),一般可通过日志工具记录完整的异常堆栈信息。(1.42+)说明:NullPointException抛出时常常描述为空,这样往往看不出是出了什么错。示例:try       {           ...       }       catch (FileNotFoundException e)       {            logger.error(e);    }建议2     一个方法不应抛出太多类型的异常。(1.42+)说明: 如果程序中需要分类处理,则将异常根据分类组织成继承关系。如果确实有很多异常类型首先考虑用异常描述来区别,throws/exception子句标明的异常最好不要超过三个。建议3     异常捕获尽量不要直接 catch (Exception ex),应该把异常细分处理。(1.42+)说明:可以设计更合理异常处理分支建议4     如果多段代码重复做同一件事情,那么在方法的划分上可能存在问题。(1.42+)说明:若此段代码各语句之间有实质性关联并且是完成同一件功能的,那么可考虑把此段代码构造成一个新的方法。建议5     集合中的数据如果不使用了应该及时释放,尤其是可重复使用的集合。(1.42+)说明:由于集合保存了对象的引用,虚拟机的垃圾收集器就不会回收。建议6  源程序中关系较为紧密的代码应尽可能相邻。(1.42+)说明:便于程序阅读和查找。示例:矩形的长与宽关系较密切,放在一起。rect.length = 10;rect.width = 5;建议7  不要使用难懂的技巧性很高的语句,除非很有必要时。(1.42+)说明:高技巧语句不等于高效率的程序,实际上程序的效率关键在于设计与算法。建议8     明确方法功能,精确(而不是近似)地实现方法设计。一个函数仅完成一件功能,即使简单功能也编写方法实现。 (1.42+)说明:虽然为仅用一两行就可完成的功能去编方法好象没有必要,但用方法可使功能明确化,增加程序可读性,亦可方便维护、测试。建议9     应明确规定对接口方法参数的合法性检查应由方法的调用者负责还是由接口方法本身负责,缺省是由方法调用者负责。(1.42+)说明:对于模块间接口方法的参数的合法性检查这一问题,往往有两个极端现象,即:要么是调用者和被调用者对参数均不作合法性检查,结果就遗漏了合法性检查这一必要的处理过程,造成问题隐患;要么就是调用者和被调用者均对参数进行合法性检查,这种情况虽不会造成问题,但产生了冗余代码,降低了效率。建议10  尽量使用Java 5.0新循环写法。(5.0+)说明:代码更加简洁示例:ArrayList<String> list = new ArrayList<String>();list.add...for(String str:list){System.out.println(str);}建议11  使用Java 5.0枚举来替代以前用数字与字符串的同等目的的操作。(5.0+)说明:Java 5.0以前没有枚举,大家都用数字或者字符串做枚举同样功能的事情示例:public enum EnumDemo{    ERROR,INFO,DEBUG}In other function:EnumDemo t = EnumDemo.DEBUG;if (t == EnumDemo.ERROR){  。。。。。。          }建议12  interface 中定义的常量不要写publicstatic、final的修饰词,方法不要写public修饰词。(1.42+)说明:更加简洁示例:public interface InterfaceT{    String TT = "abcl";    void doStart();}建议13  新起一个线程,都要使用Thread.setName(“…”)设置线程名。说明:性能测试时可对线程状态进行监控,异常时也可以知道异常发生在哪个线程中1.5      性能与可靠性1.5.1      规则规则1      对Debug,Info级别日志输出前必须对当前的调试等级先进行判断。(1.42+)说明:日志一般都会有不少字符串的处理,如果不是Debug级别就没有必要进行处理示例:if (logger.debugEnable()){logger.debug(“request : ” + request.getMethod());}规则2      数组复制使用System.arraycopy(*) 。(1.42+)说明:更好的性能规则3      不要使用循环将集合转为数组,可以使用集合的toArray()方法。(1.42+)说明:更好的性能,代码更加简洁示例:ArrayList list = new ArrayList();        list.add....        String [] array = new String[list.size()]; list.toArray(array);规则4      大量字符串的相加等于处理应该使用StringBuffer。(1.42+)说明:大量的String相加等于处理性能消耗较多。“大量”一般指5次“+=”以上或者在循环中进行字符串+=操作。示例:不推荐:String str = “”;str += ”a”;str += ”b”;推荐:StringBuffer sb = new StringBuffer();sb.append(“aa”);sb.append(“bb”);sb.append(“cc”);规则5      对类中日志工具对象logger应声明为static. (1.42+)说明:防止重复new 出logger对象(logger指各种日志工具类,可以是log4j,common log,jdk logger,内部API等,尽管一些logger对LogFactory工厂有一些优化,但是我们也必须防止代码没有必要的运行)。1.5.2      建议建议1     public类型的底层函数需对输入参数进行判断,参数不合法应该主动抛出RuntimeException。(1.42+)说明:底层函数必须保证输入参数正确性再进行其他处理(防止后面的代码抛出错误,减少没有必要的后续代码运行)。使用RuntimeException 减少了try catch满天飞,并有利于快速定于异常代码。示例:public void doDivide(int a,int b){if (b == 0){throw new IllegalArgumentException(“denominator can’t be zero”);}...}建议2     尽量使用JDK自带的API函数,不要自己写类似功能的函数. (1.42+)说明:JDK自身的函数在可靠性,性能方面一般有更好的表现,大家必须熟练掌握,特别是算法方面的。建议3     IO操作流使用有Buffer功能的class. (1.42+)说明:更好的性能,没有Buffer的输出流频繁IO操作,效率反倒低。示例:       FileOutputStream file= new FileOutputStream("test.txt");   BufferedOutputStream out =  new BufferedOutputStream(file);  for (int i = 0; i < bytes.length; i++ ){          out.write(…);}   out.flush();

总结

从头开始,调整好心态,现存的就是合理的。

0 0
原创粉丝点击