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
下载前可以先看下教程 https://pan.quark.cn/s/a4b39357ea24 在网页构建过程中,表单(Form)扮演着用户与网站之间沟通的关键角色,其主要功能在于汇集用户的各类输入信息。 JavaScript作为网页开发的核心技术,提供了多样化的API和函数来操作表单组件,诸如input和select等元素。 本专题将详细研究如何借助原生JavaScript对form表单进行视觉优化,并对input输入框与select下拉框进行功能增强。 一、表单基础1. 表单组件:在HTML语言中,<form>标签用于构建一个表单,该标签内部可以容纳多种表单组件,包括<input>(输入框)、<select>(下拉框)、<textarea>(多行文本输入区域)等。 2. 表单参数:诸如action(表单提交的地址)、method(表单提交的协议,为GET或POST)等属性,它们决定了表单的行为特性。 3. 表单行为:诸如onsubmit(表单提交时触发的动作)、onchange(表单元素值变更时触发的动作)等事件,能够通过JavaScript进行响应式处理。 二、input元素视觉优化1. CSS定制:通过设定input元素的CSS属性,例如border(边框)、background-color(背景色)、padding(内边距)、font-size(字体大小)等,能够调整其视觉表现。 2. placeholder特性:提供预填的提示文字,以帮助用户明确输入框的预期用途。 3. 图标集成:借助:before和:after伪元素或者额外的HTML组件结合CSS定位技术,可以在输入框中嵌入图标,从而增强视觉吸引力。 三、select下拉框视觉优化1. 复选功能:通过设置multiple属性...
【EI复现】基于深度强化学习的微能源网能量管理与优化策略研究(Python代码实现)内容概要:本文围绕“基于深度强化学习的微能源网能量管理与优化策略”展开研究,重点探讨了如何利用深度强化学习技术对微能源系统进行高效的能量管理与优化调度。文中结合Python代码实现,复现了EI级别研究成果,涵盖了微电网中分布式能源、储能系统及负荷的协调优化问题,通过构建合理的奖励函数与状态空间模型,实现对复杂能源系统的智能决策支持。研究体现了深度强化学习在应对不确定性可再生能源出力、负荷波动等挑战中的优势,提升了系统运行的经济性与稳定性。; 适合人群:具备一定Python编程基础和机器学习背景,从事能源系统优化、智能电网、强化学习应用等相关领域的研究生、科研人员及工程技术人员。; 使用场景及目标:①应用于微能源网的能量调度与优化控制,提升系统能效与经济效益;②为深度强化学习在能源管理领域的落地提供可复现的技术路径与代码参考;③服务于学术研究与论文复现,特别是EI/SCI级别高水平论文的仿真实验部分。; 阅读建议:建议读者结合提供的Python代码进行实践操作,深入理解深度强化学习算法在能源系统建模中的具体应用,重点关注状态设计、动作空间定义与奖励函数构造等关键环节,并可进一步扩展至多智能体强化学习或与其他优化算法的融合研究。
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值