“Comments Do Not Make Up for Bad Code.” Good code is actually pretty readable without comments, but proper comments make code more readable and maintainable.

1. Comments don’t beautify bad code

1. Clean and expressive code with a few comments is much better than fragmented and complex code with lots of comments.

2. Instead of spending time writing comments that explain the crappy code you’ve created, spend time cleaning up the crappy code.

2. Explain in code

Explain most of your intentions in code, often as simple as creating a function that describes the same thing the comments say.

// check to see if the employee is eligible for full benefits if ((employee.flags & HOURLY_FLAG) && (employee.age > 65))  { // do something }Copy the code

Improvement:

if (employee.isEligibleForFullBenefits()) {
    // do something
}
Copy the code

3. Good comments

Of course, some comments are necessary and helpful.

1. Legal information: The company code specification requires the writing of legal notes, such as == copyright and work notices ==.


2. Notes that provide information

Pattern.compile(“\d*:\d*:\d* \w*, \w* \d*, \d*”); // Format matching kk.mm. Ss EEE, MMM dd, YYYY Pattern timeMatcher = pattern.compile (“\d*:\d*:\d* :\d* \w*, \d*, \d*”);


3. Interpretation of intent: Sometimes annotations provide useful information not only about the implementation, but also about the intent behind a decision.

/**
     * generate signature by params and secret, used for computing signature for http request.
     *
     * @param params request params
     * @param secret auth secret
     * @return secret sign
     * @throws Exception  exception
     */
    public static String generateSignature(Map<String, Object> params, String secret) throws Exception {
        final StringBuilder paramStr = new StringBuilder();
        final Map<String, Object> sortedMap = new TreeMap<>(params);
        for (Map.Entry<String, Object> entry : sortedMap.entrySet()) {
            paramStr.append(entry.getKey());
            paramStr.append(entry.getValue());
        }

        Mac hmac = Mac.getInstance("HmacSHA1");
        SecretKeySpec sec = new SecretKeySpec(secret.getBytes(), "HmacSHA1");
        hmac.init(sec);
        byte[] digest = hmac.doFinal(paramStr.toString().getBytes());

        return new String(new Hex().encode(digest), "UTF-8");
    }
Copy the code
  • Comments must express something other than code, == what code can contain, and must not include == in comments
  • If you need to comment, comment the intent (==why==), not the implementation (==how==), everyone will look at the code

4. Interpretation: Sometimes annotations translate the meaning of an obscure parameter or return value into a readable form.

==== especially if the argument or return value is part of a standard library ====, or if you can’t change the code, code that helps explain what it means is useful, for example:

assertTrue(bb.compareTo(ba)==1); //bb>aa assertTrue(a.compareTo(b)==-1); //a<bCopy the code

The method may not be clear when you look at it directly, but it is much clearer when you have comments.


5. Warnings: Warnings have consequences.

private BaseResult putReadyFlag(BillingDataContext context, Integer readyFlag) {
    // warn! oms data format require List<Map<String,String>> and the size of it must be one.
    List<Map<String, String>> dataList = Lists.newArrayListWithExpectedSize(1);
}
Copy the code

This method creates an array linked list == with a fixed size of 1 and type Map<String,String>.

The occasional hack of logic in your code and the risk of modification is high, you need to add comments to highlight it

The following comment explains why a particular test case should be closed:

// Don't run unless you have some time to kill
public void testWithReallyBigFile()
{
    writeLinesToFile(100000000);
    response.setBody(testFile);
    String responseString = output.toString();
    assertSubString("Content-Length: 10000000",responseString);
    assertTrue(bytesSent>100000000);
}
Copy the code

Of course, most of us now close test cases with the @ignore attribute that conforms to a properly interpreted string. Such as when

@ignore (" Takes too long to run ")Copy the code

6. TODO. Note that == clean ==

Sometimes it makes sense to place to-do lists in the source code in //TODO form.

TODO is something that programmers think they should do, but for some reason haven’t done yet. It might be a reminder to remove an unnecessary feature, or to call attention to a problem. It might be a plea for a good name, or a reminder of a change that relies on a plan. Whatever TODO’s purpose, it’s not an excuse to leave bad code in the system.


7. Zoom in: Some of the code may seem redundant, but the coders had their own reasons at the time and needed to comment on the importance of the code. Avoid being optimized out later.


8. Javadoc in public apis:

Writing a public API means writing a good standard Java Doc specification for it. However, just like any other annotation, Javadoc can be misleading, inapplicable, or provide incorrect information.

4. The bad comments

Most comments fall into the bad comment category. Often a bad comment is a prop or an excuse for bad code, or a correction for a bad decision, essentially a programmer talking to himself.

4.1 Mumbling

If you feel you should or need to add a comment because the process requires it, it’s pointless. Notes should be for the reader, not for yourself.

4.2 Redundant comments

counter-examples

/** * ecsOperatelogdo.java * * @author XXX public class DemoDO implements Serializable {private static final long serialVersionUID = -3517141301031994021L; /** * private Long id; /** * private Long aliUid; /** * @return the id */ public Long getId() { return id; } /** * @param id the id to set */ public void setId(Long id) { this.id = id; } /** * @return the aliUid */ public Long getAliUid() { return aliUid; } /** * @param aliUid the aliUid to set */ public void setAliUid(Long aliUid) { this.aliUid = aliUid; }}Copy the code

Analysis of the above code reveals two very awkward and redundant comments:

  • Class comments use the default template and are filled with invalid information
  • The IDE generates a lot of invalid comments for Getter and Setter methods

Is case

/** * public DemoDO implements Serializable {private static DemoDO implements Serializable final long serialVersionUID = -3517141301031994021L; /** * private Long id; /** * private Long aliUid; public Long getId() { return id; } public void setId(Long id) { this.id = id; } public Long getAliUid() { return aliUid; } public void setAliUid(Long aliUid) { this.aliUid = aliUid; }}Copy the code
  • Do not keep any conventional comments, such as the redundant comments automatically generated by the IDE

  • Do not generate any comments for this class. You can configure the IDE to achieve this effect. The Ling Fox plug-in is recommended

4.3 Misleading Notes

The code returns false, and comments always return true.

/***
 * Always returns true.
 */
public boolean isAvailable() {
    return false;
}
Copy the code

4.4 Conventional annotations

For example, if you ask every function to write Javadoc, you’ll get a lot of comments that you wouldn’t need to write otherwise.

4.5 Log Comments

== It is no longer necessary to add an annotated log of each change at the beginning of each module, and many code maintenance tools now provide better logging of changes;

/** * @author * @date 2020-09-10 * @param cardType ** 2020-09-11 add by Zhangwei * 2020-09-12 add by Zhangwei * 2020-09-12  add by zhangwei2 */ public void membershipConsume(CardType cardType){ }Copy the code

4.6 Nonsense Notes

Private int dayofMonth; The day of the month;

4.7 Horrible nonsense

Javadoc can also be crap,

4.8 Do not use comments when functions or variables are available

The == comment itself is meant to explain code that doesn’t explain itself, and if the comment itself also needs to explain ==, it’s useless.

4.9 Location Marking:

Don’t use such unreasonable, trivial comments. // Actions ///////////////////////////

4.10 Comments following parentheses

While this might make sense for long functions with deeply nested structures,But it would just confuse the shorter, encapsulated functions we’d rather writeIf you find yourself wanting to mark the closing parenthesis, instead you should shorten the function.

4.11 Attribution and signature

Source control systems are very good at remembering who added what evil and when. There’s no need to mess up the code with those little signatures. You might think that this kind of comment might help others know who to talk to about the code. The fact is, however, that the notes sit there year after year, getting less accurate and less relevant to the original author.

Code commented out in 4.12

Some programs that are no longer in use are still commented out there, and some people might recall where the code was left that might be useful. But now that we have source control, we don’t have to comment it out, we just delete it.

private Object buildParamMap(Object request) throws Exception { if (List.class.isAssignableFrom(request.getClass())) { List<Object> input = (List<Object>)request; List<Object> result = new ArrayList<Object>(); for (Object obj : input) { result.add(buildParamMap(obj)); } return result; } Map<String, Object> result = new LinkedHashMap<String, Object>(); Field[] fields = FieldUtils.getAllFields(request.getClass()); for (Field field : fields) { if (IGNORE_FIELD_LIST.contains(field.getName())) { continue; } String fieldAnnotationName = field.getAnnotation(ProxyParam.class) ! = null ? field.getAnnotation( ProxyParam.class).paramName() : HttpParamUtil.convertParamName(field.getName()); //Object paramValue = FieldUtils.readField(field, request, true); //if (paramValue == null) { // continue; //} // //if (BASIC_TYPE_LIST.contains(field.getGenericType().getTypeName())) { // result.put(fieldAnnotationName, String.valueOf(paramValue)); //} else { // result.put(fieldAnnotationName, this.buildParamMap(paramValue)); //} } return result; }Copy the code

4.13 HTML comments

HTML tags in source code comments are a nuisance; if the comments are going to be extracted by a tool and rendered to a web page, it is the tool’s responsibility, not the programmer’s, to tag the comments with the appropriate HTML.

/** * used for indicate the field will be used as a http param, the http request methods include as follows: * <li>Get</li> * <li>Post</li> * <li>Connect</li> * * the proxy param will be parsed, see {@link ProxyParamBuilder}. * * @date 2017/12/08 */ @Target(ElementType.FIELD) @Retention(RetentionPolicy.RUNTIME) @Documented public @interface ProxyParam { /** * the value indicate the proxy app name, such as houyi. * * @return proxy app name */ String proxyApp() default "houyi"; /** * proxy request mapping http param. * * @return http param */ String paramName(); /** * the value indicate if the param is required. * * @return if this param is required */ boolean isRequired() default  true; }Copy the code

Is case

/** * used for indicate the field will be used as a http param. * * * @date 2017/12/08 */@Target(ElementType.FIELD)@Retention(RetentionPolicy.RUNTIME)@Documentedpublic @interface ProxyParam { /** * the value  indicate the proxy app name, such as houyi. * * @return proxy app name */ String proxyApp() default "houyi"; /** * proxy request mapping http param. * * @return http param */ String paramName(); /** * the value indicate if the param is required. * * @return if this param is required */ boolean isRequired() default  true; }Copy the code

4.14 Non-local Information

The == comment must describe the nearest code == counter example

// This method has a line of code that removes a data from the map and puts the comment before the put call. Private Map<String, String> buildInstanceDocumentMap(String version, String instanceId) {Map<String, String> instanceDocumentMap = Maps.newLinkedHashMap(); Map<String, String> instanceDocumentMapMetadataPart = metaDataService.getInstanceDocument(instanceId, version, instanceDocumentMetaKeys); instanceDocumentMap.putAll(instanceDocumentMapMetadataPart); //the map must remove the old key for instance type instanceDocumentMap.put("instance-type", instanceDocumentMap.get("instance/instance-type")); instanceDocumentMap.remove("instance/instance-type"); return instanceDocumentMap; }Copy the code

Is case

private Map<String, String> buildInstanceDocumentMap(String version, String instanceId) {
        Map<String, String> instanceDocumentMap = Maps.newLinkedHashMap();

        Map<String, String> instanceDocumentMapMetadataPart = metaDataService.getInstanceDocument(instanceId, version,
            instanceDocumentMetaKeys);
        instanceDocumentMap.putAll(instanceDocumentMapMetadataPart);
        instanceDocumentMap.put("instance-type", instanceDocumentMap.get("instance/instance-type"));
        //the map must remove the old key for instance type
        instanceDocumentMap.remove("instance/instance-type");

        return instanceDocumentMap;
    }
Copy the code

4.15 Too much information

4.16 No obvious connection

The connection between comments and the code they describe should be == obvious ==. If you go to the trouble of writing comments, at least let the reader look at the comments and the code, and understand what the comments are about

4.17 the function head

Short functions don’t need much description. Choosing a good name for a short function that does only one thing is usually better than writing a function header comment ==

Javadoc in 4.18 non-public code

While Javadoc is useful for public apis, it is a nuisance for code that is not intended for public use. Generating Javadoc pages for classes and functions in the system is not always useful, and the extra form of Javadoc comments requires opportunities equal to == eight articles ==.

4.19 sample

4.20 supplement

The IDE file Templates will be automatically configured as follows:

File/class annotation specification

/**
 * @author ${USER}
 * @date ${YEAR}/${MONTH}/${DAY}
 */
Copy the code

__ You are strongly advised to use the preceding configuration.

Methods the annotation

/**  
  * xxx
  * 
  * @param 
  * @param 
  * @return 
  * @throws 
  */
Copy the code

Here’s an example:

/** * Converts a <code>byte[]</code> to a String using the specified character encoding. * * @param bytes * the byte array to read from * @param charsetName * the encoding to use, if null then use the platform default * @return a new String * @throws UnsupportedEncodingException * If the named charset is not supported * @throws NullPointerException * if the input is null * @deprecated use {@link StringUtils#toEncodedString(byte[], Charset)} Instead of String constants in your code * @since 3.1 */ @deprecated public static String toString(final) byte[] bytes, final String charsetName) throws UnsupportedEncodingException { return charsetName ! = null ? new String(bytes, charsetName) : new String(bytes, Charset.defaultCharset()); }Copy the code

Block and Line comments Single-line code comments use line comments // multi-line code comments use block comments /* */

4.21 References

The Code Clean Way

Developer.aliyun.com/article/603…

zhuanlan.zhihu.com/p/267001652

www.jianshu.com/p/c44eca6ad…

Blog.csdn.net/c_lanxiaofa…

Pay attention to the public account “Programmer interview”

Reply to “interview” to get interview package!!

This public account to share their own from programmer xiao Bai to experience spring recruitment autumn recruitment cut more than 10 offer interview written test experience, including [Java], [operating system], [computer network], [design mode], [data structure and algorithm], [Dacheng face by], [database] look forward to you join!!

1. Computer network —- Three times shake hands four times wave hands

2. Dream come true —– Project self-introduction

Here are the design patterns you asked for

4. Shocked! Check out this programmer interview manual!!

5. Teach you the interview “Profile” word for word

6. Nearly 30 interviews shared