B轮融资|代码注释的艺术,优秀代码真的不需要注释吗?( 五 )


不明所以的常量
/** * The bin count threshold for using a tree rather than list for a * bin. Bins are converted to trees when adding an element to a * bin with at least this many nodes. The value must be greater * than 2 and should be at least 8 to mesh with assumptions in * tree removal about conversion back to plain bins upon * shrinkage. */static final int TREEIFY_THRESHOLD = 8; 这是JDK中HashMap的一个常量因子 , 记录由链表转向红黑树的链表长度阈值 , 超过该长度则链表转为红黑树 。 这里记录了一个8 , 不仅记录了该常量的用途 , 也记录了为什么我们定义这个值 。 经常我们会发现我们代码中存在一个常量等于3、等于4 , 有时我们不知道这些3和4是干什么的 , 有时我们不知道为什么是3和4 。截取自java.util.HashMap#TREEIFY_THRESHOLD
意料之外的行为
for (int i = 0; i3; i++) { // if task running invoke only check result ready or not Result result = bigDataQueryService.queryBySQL(sql token); if (SUCCESS.equals(result.getStatus())) { return result.getValue();Thread.sleep(5000); 代码及注释所示为每5秒check一下是否有结果返回 , 远程服务将触发与获取放在了一个接口 。 没有注释我们可能认为这段代码有问题 , 代码表现的含义更像是每5秒调用一次 , 而非每5秒check一次 。 为意料之外的行为添加注释 , 可以减少对代码的误解读 , 并向读者说明必要的背景及逻辑信息 。
接口对外API
/** *pChecks if a CharSequence is empty (\"\") null or whitespace only./p*pWhitespace is defined by {@link Character#isWhitespace(char)./p* StringUtils.isBlank(null) = true * StringUtils.isBlank(\"\") = true * StringUtils.isBlank(\" \") = true * StringUtils.isBlank(\"bob\") = false * StringUtils.isBlank(\" bob \") = false * * @param cs the CharSequence to check may be null * @return {@code true if the CharSequence is null empty or whitespace only */public static boolean isBlank(final CharSequence cs) { final int strLen = length(cs); if (strLen == 0) { return true;for (int i = 0; istrLen; i++) { if (!Character.isWhitespace(cs.charAt(i))) { return false;return true; 我们经常使用的StringUtils工具类中的isBlank方法 , 写了非常详情的注释 , 不仅包括方法的逻辑 , 入参的含义 , 甚至还包括具体示例 。 我们平常定义的二方库中的HSF、HTTP接口定义 , 同样需要有清晰详尽的注释 , 这里的注释甚至经常会多过你的代码 。截取自org.apache.commons.lang3.StringUtils#isBlank
法律文件信息
/* * Licensed to the Apache Software Foundation (ASF) under one or more * contributor license agreements. See the NOTICE file distributed with * this work for additional information regarding copyright ownership. * The ASF licenses this file to You under the Apache License Version 2.0 * (the \"License\"); you may not use this file except in compliance with * the License. You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing software * distributed under the License is distributed on an \"AS IS\" BASIS * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ 与法律相关的注释 , 在开源软件库中较经常遇到 。 涉及到一些版权及著作声明时 , 我们需要在源文件顶部放置法律相关注释 。 当然 , 我们不需要将所有法律信息写到注释中 , 如例子中的跳链 , 引用一份标准的外部文档 , 会是一个更好的选择 。
写在最后 注释并不会妨碍你写出优雅简洁的代码 , 它只是程序固有的一部分而已 。 我们不用过分在意我们的代码是否可以脱离注释 , 也不需要强调因为我们的代码符合什么原则 , 满足什么约定 , 所以代码是优秀的注释是冗余的 。 代码是一门艺术 , 并不会因为满足三规九条它就一定完美 , 因为艺术 , 是不可衡量的 。