Common code violations in Java

本文总结了在Java项目中常见的代码违规问题,包括代码格式、返回语句管理、简化if-else语句、避免创建不必要的对象实例等,并提供了解决这些问题的方法。

Statement

This article comes from the network,the source is http://veerasundar.com/blog/2012/09/common-code-violations-in-java/

At work, recently I did a code cleanup of an existing Java project. After that exercise, I could see a common set of code violations that occur again and again in the code. So, I came up with a list of such common violations and shared it with my peers so that an awareness would help to improve the code quality and maintainability. I’m sharing the list here to a bigger audience.

The list is not in any particular order and all derived from the rules enforced by code quality tools such as CheckStyleFindBugs and PMD.

Here we go!

Format source code and Organize imports in Eclipse


Eclipse provides the option to auto-format the source code and organize the imports (thereby removing unused ones). You can use the following shortcut keys to invoke these functions.

  • Ctrl + Shift + F – Formats the source code.
  • Ctrl + Shift + O – Organizes the imports and removes the unused ones.

Instead of you manually invoking these two functions, you can tell Eclipse to auto-format and auto-organize whenever you save a file. To do this, in Eclipse, go to Window -> Preferences -> Java -> Editor -> Save Actions and then enable Perform the selected actions on save and checkFormat source code + Organize imports.

Avoid multiple returns (exit points) in methods


In your methods, make sure that you have only one exit point. Do not use returns in more than one places in a method body.

For example, the below code is NOT RECOMMENDED because it has more then one exit points (return statements).

private boolean isEligible(int age){
  if(age > 18){
    return true;
  }else{
    return false;
  }
}

The above code can be rewritten like this (of course, the below code can be still improved, but that’ll be later).

private boolean isEligible(int age){
  boolean result;
  if(age > 18){
    result = true;
  }else{
    result = false;
  }
  return result;
}

Simplify if-else methods


We write several utility methods that takes a parameter, checks for some conditions and returns a value based on the condition. For example, consider the isEligible method that you just saw in the previous point.

private boolean isEligible(int age){
  boolean result;
  if(age > 18){
    result = true;
  }else{
    result = false;
  }
  return result;
}

The entire method can be re-written as a single return statement as below.

private boolean isEligible(int age){
  return age > 18;
}

Do not create new instances of Boolean, Integer or String


Avoid creating new instances of Boolean, Integer, String etc. For example, instead of using new Boolean(true), use Boolean.valueOf(true). The later statement has the same effect of the former one but it has improved performance.

Use curly braces around block statements


Never forget to use curly braces around block level statements such as ifforwhile. This reduces the ambiguity of your code and avoids the chances of introducing a new bug when you modify the block level statement.

NOT RECOMMENDED

if(age > 18)
  result = true;
else
  result = false;

RECOMMENDED

if(age > 18){
  result = true;
}else{
  result = false;
}

Mark method parameters as final, wherever applicable


Always mark the method parameters as final wherever applicable. If you do so, when you accidentally modify the value of the parameter, you’ll get a compiler warning. Also, it makes the compiler to optimize the byte code in a better way.

RECOMMENDED

private boolean isEligible(final int age){ ... }

Name public static final fields in UPPERCASE


Always name the public static final fields (also known as Constants) in UPPERCASE. This lets you to easily differentiate constant fields from the local variables.

NOT RECOMMENDED

public static final String testAccountNo = "12345678";

RECOMMENDED

public static final String TEST_ACCOUNT_NO = "12345678";

Combine multiple if statements into one


Wherever possible, try to combine multiple if statements into single one.

For example, the below code;

if(age > 18){
  if( voted == false){
    // eligible to vote.
  }
}

can be combined into single if statements, as:

if(age > 18 && !voted){
  // eligible to vote
}

switch should have default


Always add a default case for the switch statements.

Avoid duplicate string literals, instead create a constant


If you have to use a string in several places, avoid using it as a literal. Instead create a String constant and use it.

For example, from the below code,

private void someMethod(){
  logger.log("My Application" + e);
  ....
  ....
  logger.log("My Application" + f);
}

The string literal “My Application” can be made as an Constant and used in the code.

public static final String MY_APP = "My Application";

private void someMethod(){
  logger.log(MY_APP + e);
  ....
  ....
  logger.log(MY_APP + f);
}

out/soong/.intermediates/frameworks/base/api-stubs-docs/android_common/srcjars/frameworks/base/core/java/android/os/IUuidService.java:126: error: Methods calling system APIs should rethrow `RemoteException` as `RuntimeException` (but do not list it in the throws clause) [RethrowRemoteException] out/soong/.intermediates/frameworks/base/api-stubs-docs/android_common/srcjars/frameworks/base/core/java/android/os/IUuidService.java:126: error: Missing nullability on method `getOrCreatePersistentUuid` return [MissingNullability] out/soong/.intermediates/frameworks/base/api-stubs-docs/android_common/srcjars/frameworks/base/core/java/android/os/IUuidService.java:10: error: Methods calling system APIs should rethrow `RemoteException` as `RuntimeException` (but do not list it in the throws clause) [RethrowRemoteException] out/soong/.intermediates/frameworks/base/api-stubs-docs/android_common/srcjars/frameworks/base/core/java/android/os/IUuidService.java:10: error: Missing nullability on method `getOrCreatePersistentUuid` return [MissingNullability] out/soong/.intermediates/frameworks/base/api-stubs-docs/android_common/srcjars/frameworks/base/core/java/android/os/IUuidService.java:14: error: Missing nullability on method `asBinder` return [MissingNullability] out/soong/.intermediates/frameworks/base/api-stubs-docs/android_common/srcjars/frameworks/base/core/java/android/os/IUuidService.java:19: error: Raw AIDL interfaces must not be exposed: Stub extends Binder [RawAidl] out/soong/.intermediates/frameworks/base/api-stubs-docs/android_common/srcjars/frameworks/base/core/java/android/os/IUuidService.java:28: error: Missing nullability on method `asInterface` return [MissingNullability] out/soong/.intermediates/frameworks/base/api-stubs-docs/android_common/srcjars/frameworks/base/core/java/android/os/IUuidService.java:32: error: Missing nullability on parameter `obj` in method `asInterface` [MissingNullability] out/soong/.intermediates/frameworks/base/api-stubs-docs/android_common/srcjars/frameworks/base/core/java/android/os/IUuidService.java:43: error: Missing nullability on method `asBinder` return [MissingNullability] out/soong/.intermediates/frameworks/base/api-stubs-docs/android_common/srcjars/frameworks/base/core/java/android/os/IUuidService.java:47: error: Methods calling system APIs should rethrow `RemoteException` as `RuntimeException` (but do not list it in the throws clause) [RethrowRemoteException] out/soong/.intermediates/frameworks/base/api-stubs-docs/android_common/srcjars/frameworks/base/core/java/android/os/IUuidService.java:47: error: Missing nullability on parameter `data` in method `onTransact` [MissingNullability] out/soong/.intermediates/frameworks/base/api-stubs-docs/android_common/srcjars/frameworks/base/core/java/android/os/IUuidService.java:47: error: Missing nullability on parameter `reply` in method `onTransact` [MissingNullability] out/soong/.intermediates/frameworks/base/api-stubs-docs/android_common/srcjars/frameworks/base/core/java/android/os/IUuidService.java:109: error: Missing nullability on parameter `impl` in method `setDefaultImpl` [MissingNullability] out/soong/.intermediates/frameworks/base/api-stubs-docs/android_common/srcjars/frameworks/base/core/java/android/os/IUuidService.java:122: error: Missing nullability on method `getDefaultImpl` return [MissingNullability] 14 new API lint issues were found. See tools/metalava/API-LINT.md for how to handle these. metalava detected access to files that are not explicitly specified. See /mnt/sde/caiwenlu/JFC-001_1103/SW5100/LINUX/android/out/soong/.intermediates/frameworks/base/api-stubs-docs/android_common/api-stubs-docs-violations.txt for details. ************************************************************ Your API changes are triggering API Lint warnings or errors. To make these errors go away, fix the code according to the error and/or warning messages above. If it is not possible to do so, there are workarounds:
11-25
评论
成就一亿技术人!
拼手气红包6.0元
还能输入1000个字符
 
红包 添加红包
表情包 插入表情
 条评论被折叠 查看
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值