WebCS/OpenSource

About Comment - Which is good or bad?

calendar

2022-12-10

4

Intro

When developing, opinions are divided on whether or not to leave a comment. Some of the developers say comments are forced to be written. Recently, however, more people have argued that comment isn't needed.

This post is based on the Book name "clean code" written by Robert C. Martin. And it is very personal. Just keep in mind that there are these opinions

What is comment?

‘Don't use comments’ - Write the code that can be understood without comments

  • Comments never compensate bad code
  • Express intentions with code itself rather than comments

Good Comments (Necessary Comments)

  1. Legal comments

    1. Indicate specific comments for legal reasons in line with implementation standards established by the company
    1// Copyright (C) 2003,2004,2005 by Object Mentor, Inc. All rights reserved. 2// GNU General Public License
  2. Comments providing information

    1. It's convenient to provide basic information in comments (if possible, it's better to put information in function name)
    1// Return Responder instance being tested 2Protected abstract Responder responderInstance();

    or

    1// kk:mm:ss EEE, MMM dd, yyyy formation 2Pattern timeMatcher = Pattern.compile( 3 "\\d*:\\d*:\\d* \\w*, \\w* \\d*, \\d*" 4);
  3. Comments describing intention

    1. Beyond the line to help you understand the codes, explain the intent behind the decision
    1public int compareTo(Object o) { 2 if(o instanceof WikiPagePath) { 3 WikiPagePath p = (WikiPagePath) o; 4 String compressedName = StringUtil.join(names, ""); 5 String compressedArgumentName = StringUtil.join(p.names, ""); 6 return compressedName.compareTo(compressedArgumentName); 7 } 8 return 1; // It's the right type, so the ranking is higher 9}

    or

    1// It attempts to create a competitive condition by generating threads in large quantities. 2for(int i = 0; i < 25000; i++) { 3 WidgetBuilderThread widgetBuilderThread = new WidgetBuilderThread(widgetBuilder, text, parent, failFlag); 4 Thread thread = new Thread(widgetBuilderThread); 5 thread.start(); 6}
  4. Comments informing the meaning clearly

    1. Ambiguous arguments or return values become easier to understand if the meaning is expressed in a readable way
    2. but, there is a significant risk of incorrect annotation
    3. In other words, use it when there is no better way
    1assertTrue(a.compareTo(a) == 0); // a == a 2assertTrue(a.compareTo(b) != 0); // a != a 3assertTrue(ab.compareTo(ab) == 0); // ab == ab 4assertTrue(a.compareTo(b) == -1); // a < b 5assertTrue(aa.compareTo(ab) == -1); // aa < ab 6assertTrue(ba.compareTo(bb) == -1); // ba < bb 7assertTrue(b.compareTo(a) == 1); // b > a 8assertTrue(ab.compareTo(aa) == 1); // ab > aa 9assertTrue(bb.compareTo(ba) == 1); // bb > ba
  5. Comments warning the result

    1. Of course, these days, we can turn off the test case using the @ignore property
    2. There may be better solutions, but warning comments are very reasonable
    1// If you don't have enough free time, don't run it 2public void _testWithReallyBigFile() { 3 writeLinesToFile(10000000); 4 ... 5}

    or

    1public static SimpleDateFormat makeStandardHttpDateFormat() { 2 // SimpleDateFormat() is not safe to threads 3 // Therefore, each instance must be created independently 4 SimpleDateFormat df = new SimpleDateFormat("EEE, dd MMM yyyy HH:mm:ss z"); 5 df.setTimeZone(TimeZone.getTimeZone("GMT")); 6 return df; 7}
  6. TODO comments

    1. It's good to leave a future event or something that needs to be modified
    2. However, there is a hassle of checking and erasing periodically without forgetting (If you forget and don't erase it, it's just a slap in the face…)
    1// TODO: MdM is not need now 2// If importing the checkout model, function is not needed
  7. Comments emphasizing the importance

    1. Not-emphasizing the importance of any code
    2. Useful when emphasizing the importance of something that might be considered insignificant
    1String listItemContent = match.group(3).trim(); 2// At this point, trim is very important. trim() erases the starting spaces from the string 3// This is because if there is a start space in the string, it is recognized as another string 4new ListItemWidget(this, listItemContent, this.level + 1); 5return buildList(text.substring(match.end()));

Bad Comments (Un-necessary Comments)

  1. Rambling comment

    1. Comments reluctantly written in a sense of duty for no particular reason
    2. The value of the comments' existance is diminished
    1try { 2 String propertiesPath = propertiesLocation + "/" + PROPERTISE_FILE; 3 FileInputStream propertiesStream = new FileInputStream(propertiesPath); 4 loadedProperties.load(propertiesStream); 5} catch (IOException) { 6 // If there is no properties file, it means that default value is read to memory 7}
  2. Comments that overlap the same story

    1. It's not effective to write overlapped comments on the codes because it takes a long time to read
    2. The overlapped comments tarnish the code
    1// This is the utility method when the this.closed is true 2// When it reaches timeout, exception is thrown 3public synchronized void waitForClose(final long timeoutMillis) { 4 throw Exception { 5 if (!closed) { 6 wait(timeoutMillis); 7 if (!closed) { 8 throw new Exception("MockResponseSender could not be closed"); 9 } 10 } 11 } 12}

    or

    1// delay value 2protected int backgroundProcessorDelay = -1; 3 4// lifecycle to support the component 5protected LifecycleSupport lifecycle = new LifecycleSupport(this); 6 7// Logger that is related to container 8protected Loader loader = null;
  3. Comments that can be misunderstood

    1. Because of the slightly incorrect (or misleading) information in the comments, other developers may make an error without knowing why
    1// This is the utility method when the this.closed is true 2// When it reaches timeout, exception is thrown 3public synchronized void waitForClose(final long timeoutMillis) { 4 throw Exception { 5 if (!closed) { 6 wait(timeoutMillis); 7 if (!closed) { 8 throw new Exception("MockResponseSender could not be closed"); 9 } 10 } 11 } 12}

    This is the same code of Comments that overlap the same story's example. In other words, the above code is both Comments that overlap the same story and Comments that can be misunderstood

  4. Mandatory comments

    1/** 2 * @param title CD title 3 * @param author CD autor 4 * @param tracks number of CD tracks 5 */ 6 7public void addCD(String title, String author, int tracks) { 8 CD cd = new CD(); 9 cd.title = title; 10 cd.author = author; 11 cd.tracks = tracks; 12 13 cdList.add(cd); 14}
  5. Comments to record history

    1. Very few these days
    1/** 2 * History ( since 11-Oct-2020 ) 3 * ----------------------------- 4 * 11-Oct-2020 : Create new Package 5 * 05-Nov-2020 : Add getDescription() method and remove NotableData class 6 * 12-Nov-2020 : Fix the bug from SpreadsheetDate class 7 * 13-Mar-2020 : Fix the bug from Checkstyle 8 */
  6. An Unremarkable Comment

    1. Comments that mentions obvious fact and fails to provide any new information
    1// day of month 2private int dayOffMonth; 3 4// return day of month 5// @return day of month 6public int getDayOfMonth() { 7 return dayOfMonth; 8}

    or

    1try { 2 doSending(); 3} catch (SocketException e) { 4 // Well, someone ceased the request 5} catch (Exception e) { 6 try { 7 response.add(ErrorResponder.makeExceptionString(e)); 8 response.closeAll(); 9 } catch (Exception e1) { 10 // What is that? 11 } 12}
  7. Comments that can be expressed as a function or variable

    1. If we are programmer, we should express our intention as a function or variable
    1// Does the module in the global list <smodule> depend on the subsystem we belong to? 2if (smodule.getDependSubsystems().contains(subSysMod.getSubSystem()));
  8. Location Comments

    1. It can be useful to use location comments during developing. But, it should be erased.
    2. If it's not removed, it's a trash
    1// Actions ///////////////////////////////////////
  9. Comments after ), }, ] (close brackets)

    1. If it is a superimposed and lengthy function, it may be meaningful
    2. But, like these days, these kinds of comments are useless because functions are small and encapsulated
    1try { 2 while ((line = in.readLine()) != null) { 3 ... 4 } // while 5 ... 6} // try
  10. Comments that credits or expresses the author

    1// Jay added
  11. Commented codes

    1. If other developers see commented codes, they'll hesitate to erase it even the useless.
    2. Delete obsolete codes, not commented
    1InputStreamResponse response = new InputStreamResponse(); 2response.setBody(formatter.getResultStream(), formatter.getByteCount()); 3// InputStream resultStream = formatter.getReultStream(); 4// StreamReader reader = new StreamReader(resultStream);
  12. HTML codes

    1. "In the source code, the Html annotation is abhorrent itself" from "clean code"
    1/** 2 * This is for the test 3 * This task returns the results from the test 4 * <pre> 5 * <p> 6 * ... 7 * </p> 8 * </pre>
  13. Global information

    1. If we need to comment, only write the code near it
    1/** 2 * Test Port: <b>8082</b> 3 * 4 * @param fitnessPort 5 */ 6public void setFitnessePort(int fitnessePort) { 7 this.fitnessePort = fitnessePort; 8}
  14. Too much information

    1. It's probably useless
    1/* 2 Too much information shared in the workplace. Irrelevant information exchanged 3 at work. A lack of alignment between all the discussions going on at the same 4 time in the workplace. Not enough time given to the employees to process the 5 information they receive. 6*/
  15. Ambiguous relationship

    1. If the relationship between codes and comments is not clear, it will make it harder for the reader to understand
    1/** 2 * Array is started with enough size to put every pixels in it. 3 * And, 200 bytes are added for header information. 4 */ 5this.pngBytes = new byte[((this.width + 1) * this.height * 3) + 200];
  16. Function header