Fundamentals 21 min read

Why Code Comments Matter: Balancing Documentation and Clean Code

The article explores the purpose, controversy, and best practices of code comments, arguing that while excellent code can be self‑explanatory, thoughtful comments are essential for readability, maintenance, and conveying intent, especially in complex or ambiguous scenarios.

Alibaba Terminal Technology
Alibaba Terminal Technology
Alibaba Terminal Technology
Why Code Comments Matter: Balancing Documentation and Clean Code

The Purpose of Comments

A bad piece of code often forces developers to write comments, but the proper approach is to improve the code itself; when code is truly excellent, comments may become unnecessary. Comments are explanations that enhance readability and are stripped away by the compiler.

Controversy and Disagreement

Since the early days of programming, every language supports comments, yet their use remains debated. Some developers claim that perfect code needs no comments, while others argue that comments are indispensable for conveying intent that code alone cannot express.

"The proper use of comments is to compensate for our failure to express ourselves in code." – Robert C. Martin, Clean Code

Bad Code’s Lifeline

Robert C. Martin views comments as a sign of failure to write clear code; they should only appear when the code cannot express the intent. Peter Vogel similarly argues that comments often add little value.

Comment Negation Theory

"If our programming languages were expressive enough, or if we had the talent to subtly wield those languages to express our intent, we would not need comments very much—perhaps not at all." – Robert C. Martin

Utopian Views of Software Design

John Ousterhout famously called the belief that "good code is self‑documenting" a beautiful myth, emphasizing that well‑named variables and clear structure are necessary but not sufficient.

Comments as the Best Assistant to Good Code

Dustin Boswell argues that comments help readers know as much as the author, especially for details that code cannot convey.

Precise Expression and Naming

Phil Karlton famously said the only hard problems in computer science are cache invalidation and naming. Clear naming reduces the need for comments, but sometimes brief annotations are still required.

Code Examples

Typical redundant comment:

/**
 * returns the last day of the month
 * @return the last day of the month
 */
public Date getLastDayOfMonth(Date date) {
    Calendar calendar = new GregorianCalendar();
    calendar.setTime(date);
    calendar.set(Calendar.DAY_OF_MONTH, calendar.getActualMaximum(Calendar.DAY_OF_MONTH));
    return calendar.getTime();
}

Meaningful comment for a complex method:

/**
 * Query customer list with preparation, validation, and enrichment steps.
 */
public List queryCustomerList() {
    // Prepare parameters
    UserInfo userInfo = context.getLoginContext().getUserInfo();
    if (userInfo == null || StringUtils.isBlank(userInfo.getUserId())) {
        return Collections.emptyList();
    }
    // Convert and query
    LoginDTO loginDTO = userInfoConvertor.convertUserInfo2LoginDTO(userInfo);
    List<CustomerSearchVO> list = customerRemoteQueryService.query(loginDTO);
    // Filter and enrich
    for (Iterator<CustomerSearchVO> it = list.iterator(); it.hasNext(); ) {
        CustomerSearchVO cs = it.next();
        if (isInBlackList(cs) || isLowQuality(cs)) {
            it.remove();
        }
    }
    batchFillCustomerPositionInfo(list);
    batchFillCustomerAddressInfo(list);
    return list;
}

Spring bean retrieval snippet with explanatory comments:

// Fail if we're already creating this bean instance (circular reference)
if (isPrototypeCurrentlyInCreation(beanName)) {
    throw new BeanCurrentlyInCreationException(beanName);
}
// Check parent factory if bean not found locally
BeanFactory parent = getParentBeanFactory();
if (parent != null && !containsBeanDefinition(beanName)) {
    String nameToLookup = originalBeanName(name);
    return (args != null) ? parent.getBean(nameToLookup, args) : parent.getBean(nameToLookup, requiredType);
}

JDK Long.reverse method with detailed comment:

/**
 * Returns the value obtained by reversing the order of the bits in the
 * two's complement binary representation of the specified {@code long} value.
 */
public static long reverse(long i) {
    i = (i & 0x5555555555555555L) << 1 | (i >>> 1) & 0x5555555555555555L;
    i = (i & 0x3333333333333333L) << 2 | (i >>> 2) & 0x3333333333333333L;
    i = (i & 0x0f0f0f0f0f0f0f0fL) << 4 | (i >>> 4) & 0x0f0f0f0f0f0f0f0fL;
    i = (i & 0x00ff00ff00ff00ffL) << 8 | (i >>> 8) & 0x00ff00ff00ff00ffL;
    i = (i << 48) | ((i & 0xffff0000L) << 16) |
        ((i >>> 16) & 0xffff0000L) | (i >>> 48);
    return i;
}

HashMap TREEIFY_THRESHOLD constant with explanatory comment:

/**
 * The bin count threshold for using a tree rather than a 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.
 */
static final int TREEIFY_THRESHOLD = 8;

Unexpected Behaviors

Loop that checks a remote service every five seconds; a comment clarifies the intention.

// Check result every 5 seconds
for (int i = 0; i < 3; i++) {
    Result result = bigDataQueryService.queryBySQL(sql, token);
    if (SUCCESS.equals(result.getStatus())) {
        return result.getValue();
    }
    Thread.sleep(5000);
}

Public API Example

/**
 * Checks if a CharSequence is empty (""), null or whitespace only.
 * @param cs the CharSequence to check, may be null
 * @return true if the CharSequence is null, empty or whitespace only
 */
public static boolean isBlank(final CharSequence cs) {
    final int len = length(cs);
    if (len == 0) return true;
    for (int i = 0; i < len; i++) {
        if (!Character.isWhitespace(cs.charAt(i))) return false;
    }
    return true;
}

Legal Boilerplate

/*
 * 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.
 */

Conclusion

Comments do not hinder elegant code; they are an integral part of software development. While striving for self‑documenting code is valuable, well‑crafted comments remain essential for clarity, maintenance, and conveying nuances that code alone cannot express.

Javabest practicessoftware designcode commentsclean code
Alibaba Terminal Technology
Written by

Alibaba Terminal Technology

Official public account of Alibaba Terminal

0 followers
Reader feedback

How this landed with the community

Sign in to like

Rate this article

Was this worth your time?

Sign in to rate
Discussion

0 Comments

Thoughtful readers leave field notes, pushback, and hard-won operational detail here.