Fundamentals 12 min read

Elegant Java Programming Practices: Code Style, Guard Clauses, Streams, and More

This article shares practical Java coding guidelines—including guard clauses, effective use of Stream API, avoiding nested loops, designing APIs with @see/@link, refined logging, exception handling, custom Spring Boot banners, syntax sugar, chain programming, thread pausing, and tuple usage—to help developers write cleaner, more maintainable code.

JD Tech
JD Tech
JD Tech
Elegant Java Programming Practices: Code Style, Guard Clauses, Streams, and More

Programming is not only a skill but also a creative activity; adopting a consistent coding style reduces communication costs and makes code more enjoyable and elegant. The article presents a series of strategies for writing elegant Java code.

1. Guard Clauses (Elegant Prevention)

When business conditions meet certain criteria (low duplicate call probability and clear primary keys), use optimistic duplicate‑prevention by catching DuplicateKeyException after the database insertion:

public int createContent(ContentOverviewEntity contentEntity) {
  try {
    return contentOverviewRepository.createContent(contentEntity);
  } catch (DuplicateKeyException dke) {
    log.warn("repeat content:{}", contentEntity.toString());
  }
  return 0;
}

2. Effective Use of Stream

Group a list of objects by a key in a single line:

List
actAggs = ...;
Map
> collect =
    actAggs.stream()
        .collect(Collectors.groupingBy(ActionAggregation::containWoNosStr, LinkedHashMap::new, Collectors.toList()));

3. Guard Statements (Early Returns)

Replace deep nested if blocks with early returns to improve readability:

if (!title.equals(newTitle)) {
  return xxx;
}
if (...) {
  return xxx;
} else {
  return yyy;
}
if (...) {
  return zzz;
}

4. Avoid Double Loops

Transform nested loops into a map‑lookup approach:

List
allPre = ...;
List
chains = ...;
Map
preMap = allPre.stream()
    .collect(Collectors.toMap(WorkOrderChain::getWoNext, item -> item, (v1, v2) -> v1));
chains.forEach(item -> {
  WorkOrderChain preWo = preMap.get(item.getWoNo());
  if (preWo != null) {
    item.setIsHead(1);
  } else {
    item.setIsHead(0);
  }
});

5. API Design with @see/@link

Use Javadoc tags to link fields to enumeration types, making the API self‑documenting:

@Data
@Builder
@NoArgsConstructor
@AllArgsConstructor
public class ContentProcessDto implements Serializable {
    /** 内容ID */
    private String contentId;
    /** @see com.jd.jr.community.common.enums.ContentTypeEnum */
    private Integer contentType;
    /** @see com.jd.jr.community.common.enums.ContentQualityGradeEnum */
    private Integer qualityGrade;
}

6. Logging Best Practices

Log only the necessary business key instead of the whole request object to simplify log searching:

log.info("operateRelationParam, id:{}, req:{}", request.getId(), JSONObject.toJSONString(request));

7. Exception‑Based Flow Control

Replace return‑code checks with specific exceptions, allowing callers to handle different error scenarios cleanly:

public RpcResult
deleteContent(ContentOptDto contentOptDto) {
  log.info("deleteContentParam:{}", contentOptDto);
  try {
    this.paramCheck(contentOptDto);
    ContentOverviewEntity contentEntity = DozerMapperUtil.map(contentOptDto, ContentOverviewEntity.class);
    contentEventHandleAbility.deleteContent(contentEntity);
  } catch (IllegalStateException pe) {
    log.error("deleteContentParam error:" + pe.getMessage(), pe);
    return RpcResult.getSgmFail("非法参数:" + pe.getMessage());
  } catch (BusinessException be) {
    log.error("deleteContentBusiness error:" + be.getMessage(), be);
    return RpcResult.getSgmFail("业务处理异常:" + be.getMessage());
  } catch (Exception e) {
    log.error("deleteContent exception:", e);
    return RpcResult.getSgmFail("内部处理错误");
  }
  return RpcResult.getSgmSuccess();
}

8. Custom Spring Boot Banner

Customize the startup banner for fun; the article links to the official documentation and an ASCII‑art generator.

9. Java Syntax Sugar

Use language features such as try‑with‑resources to reduce boilerplate:

try (FileInputStream inputStream = new FileInputStream(new File("test"))) {
  System.out.println(inputStream.read());
} catch (IOException e) {
  throw new RuntimeException(e.getMessage(), e);
}

10. Chain Programming

Implement fluent APIs that return this to enable method chaining:

public class ChainMap
{
  private Map
innerMap = new HashMap<>();
  public V get(K key) { return innerMap.get(key); }
  public ChainMap
chainPut(K key, V value) { innerMap.put(key, value); return this; }
  public static void main(String[] args) {
    ChainMap
chainMap = new ChainMap<>();
    chainMap.chainPut("a","1").chainPut("b","2").chainPut("c","3");
  }
}

11. Graceful Thread Pausing

Use Guava's Uninterruptibles.sleepUninterruptibly to pause a thread without worrying about InterruptedException and with compensation for interruptions.

12. Tuple Usage

When a method needs to return multiple related values, prefer Apache Commons Lang3's Pair or Triple instead of custom maps or objects.

In summary, by applying these techniques—guard clauses, Stream API, guard statements, avoiding double loops, API annotation, refined logging, exception‑driven flow, custom banners, syntax sugar, chain programming, uninterruptible sleep, and tuple objects—developers can produce Java code that is more elegant, maintainable, and easier to understand.

JavaException HandlingBest PracticesSpring Bootguard clausesStream APIcoding style
JD Tech
Written by

JD Tech

Official JD technology sharing platform. All the cutting‑edge JD tech, innovative insights, and open‑source solutions you’re looking for, all in one place.

0 followers
Reader feedback

How this landed with the community

login 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.