What Makes Java Code Terrible? 7 Jaw‑Dropping Bad Code Examples Revealed

An eye‑opening roundup of seven notoriously awful Java snippets—from misused StringBuffer and endless nested loops to convoluted Stream pipelines and absurd exception definitions—showcasing why such code is a nightmare, how it hampers readability, and what refactoring strategies can rescue it.

Java Backend Technology
Java Backend Technology
Java Backend Technology
What Makes Java Code Terrible? 7 Jaw‑Dropping Bad Code Examples Revealed

1. Misusing StringBuffer

The first example demonstrates a chaotic use of StringBuffer to build an XML string, mixing raw XML fragments with string concatenation inside a loop, making the code hard to read and maintain.

/**
 * Create Time 2019/5/24
 * StringBuffer追加 如痴如醉的写法
 * @author cailong
 */
public class Append {
    public static void main(String[] ares){
        StringBuffer sb = new StringBuffer();
        //这里都能理解
        sb.append("<?xml version=\"1.0\" encoding=\"UTF-8\"?><ROOT>");
        for (int i = 0; i < 10; i++) {
            //为什么到这里就要这样写???既然都用StringBuffer了
            sb.append("<NSRXX>" +
                    "<NSRSBH>"+i+"</NSRSBH>" +
                    "<NSRMC>"+i+"</NSRMC>" +
                    "<DJXH>"+i+"</DJXH>" +
                    "<ZGSWJ_DM>"+i+"</ZGSWJ_DM>" +
                    "<ZGSWJ_MC>"+i+"</ZGSWJ_MC>" +
                    "<SJLY>sjzs</SJLY>" +
                    "<YWSX_DM>"+i+"</YWSX_DM>" +
                    "</NSRXX>");
        }
        sb.append("</ROOT>");
        System.out.println(sb.toString());
    }
}

2. The Longest One‑Line Code

This snippet packs a complex Stream pipeline and multiple conditional checks into a single logical line, illustrating how excessive chaining can obscure intent and hinder debugging.

List<OperationPurchaseInfo> purchaseInfoList = sheet.getPurchaseInfoList()
    .stream()
    .filter(purchaseInfo -> purchaseInfo.getExteriorOperation()
        .getExteriorPart()
        .getExteriorOperationList()
        .stream()
        .filter(exteriorOperation -> exteriorOperation
            .getProcessState()
            .equals(ExteriorOperation.ProcessState.PROCESSING))
        .count() != 0
        && (purchaseInfo.getExteriorOperation()
            .getExteriorPart()
            .getTeamwork() == null || !purchaseInfo.getExteriorOperation()
            .getExteriorPart().getTeamwork().equals(sheet.getTeamwork())))
    .collect(Collectors.toList());

3. Deeply Nested Loops

An absurdly deep nesting of for loops, if statements, and map manipulations results in eleven levels of indentation, making the logic virtually unreadable.

if (recordList.size() > start) {
    for (int i = start; i < end; i++) {
        Map<String, Object> map = recordList.get(i);
        Map<String, Object> field11 = (Map<String, Object>) map.get("field");
        Map<String, Object> record11 = (Map<String, Object>) map.get("record");
        String catagory1 = map.get("categoryId").toString();
        SalaryDataVo ss = JSON.parseObject(JSON.toJSONString(map), SalaryDataVo.class);
        Page page3 = salaryManagerService.getAllRecordsByCondition(ss);
        if (page3.getRecords().size() > 0) {
            List<Map<String, Object>> salaryDataVos = page3.getRecords();
            salaryDataVos = this.reSetMap(salaryDataVos, null, null);
            for (Map<String, Object> map2 : salaryDataVos) {
                Map<String, Object> field2 = (Map<String, Object>) map2.get("field");
                Map<String, Object> record2 = (Map<String, Object>) map2.get("record");
                String catagory2 = map2.get("categoryId").toString();
                List<SalaryGroupVO> groupList2 = salaryGroupService.getSalaryGroupsItems(this.getUserCorpId(), catagory2);
                for (SalaryGroupVO cc : groupList2) {
                    cc.setCode(cc.getParentId() + cc.getCode());
                }
                for (Map.Entry<String, Object> entity : field2.entrySet()) {
                    String keyName = entity.getKey();
                    for (SalaryGroupVO s2 : groupList2) {
                        if ("bigDecimal".equals(s2.getItemType()) && s2.getCode().equals(field2.get(keyName).toString()) && ("部门" != keyName) && ("姓名" != keyName) && StringUtils.isNotEmpty(s2.getItemType())) {
                            if (field11.containsKey(keyName)) {
                                String code1 = field11.get(keyName).toString();
                                Double newValue = 0.0;
                                Double oldValue = 0.0;
                                if (!record11.get(code1).toString().matches("^[0-9]*$")) {
                                    oldValue = Double.parseDouble(record11.get(code1).toString());
                                    if (record2.containsKey(entity.getValue().toString()) && (!record2.get(entity.getValue().toString()).toString().matches("^[0-9]*$"))) {
                                        String value2 = record2.get(entity.getValue().toString()).toString();
                                        newValue = Double.parseDouble(value2);
                                    }
                                    record11.remove(field11.get(keyName).toString());
                                }
                                if (code1.startsWith(catagory1) || code1.startsWith(catagory2)) {
                                    String co = code1.replace(catagory1, "hz");
                                    field11.put(keyName, co);
                                    record11.put(co, oldValue + newValue);
                                }
                            } else {
                                String code = entity.getValue().toString();
                                Object value2 = record2.get(entity.getValue().toString());
                                if (code.startsWith(catagory1) && code.replace(catagory1, "").startsWith("hz")) {
                                    code = code.replace(catagory1, "");
                                } else if (code.startsWith(catagory2) && code.replace(catagory2, "").startsWith("hz")) {
                                    code = code.replace(catagory2, "");
                                }
                                field11.put(keyName, code);
                                record11.put(code, value2);
                            }
                        }
                    }
                }
                List<SalaryGroupVO> sList = salaryGroupService.getSalaryGroupItemsByParentId(catagory1);
                for (SalaryGroupVO s : sList) {
                    if (field11.containsKey(s.getName()) && s.getCode().startsWith("hz")) {
                        String k = field11.get(s.getName()).toString();
                        field11.put(s.getName(), s.getCode());
                        String value = null;
                        if (record11.containsKey(k)) {
                            value = record11.get(k).toString();
                        }
                        record11.put(s.getCode(), value);
                    }
                }
                resultList.add(map);
                pageInfo.setRecords(resultList);
            }
        }
    }
}

4. Premature Optimization for Query Speed

The author jokes about adding “business‑savvy” hooks such as artificial delays (e.g., Thread.sleep(1000)) to impress clients, highlighting a misguided focus on superficial performance tricks rather than genuine code quality.

5. Exception Abuse

This snippet defines a large collection of static exception instances with string error codes, illustrating how over‑engineered exception hierarchies can become a maintenance nightmare.

/**
 * 处理业务的异常
 * 居然有一堆静态异常,准备好了随时可以抛??
 * 错误码是字符串
 */
public class CommandException extends BaseException {
    private static final long serialVersionUID = -6354513454371927970L;
    public static CommandException PARAM_NULL = new CommandException("Command_assemble_01", "Parameter is Needed But Empty");
    public static CommandException DEVID_NULL = new CommandException("Command_assemble_02", "DevId Cannot Be Null");
    public static CommandException MDCODE_NULL = new CommandException("Command_assemble_03", "Model Code Cannot Be Empty");
    public static CommandException ORDER_NULL = new CommandException("Command_assemble_04", "Order Cannot Be Empty");
    public static CommandException TYPE_NULL = new CommandException("Command_assemble_05", "Upstream / Downstream Type Cannot Be Empty");
    public static CommandException MENUID_NULL = new CommandException("Command_assemble_06", "Menu Id Cannot Be Null");
    public static CommandException CTRLTYPE_NOT_RANGE = new CommandException("Command_assemble_07", "Ctrltype Cannot Be Recognized, Which is not in Range");
    public static CommandException CMD_NULL = new CommandException("Command_analyze_01", "CMD Cannot Be Null");
    public static CommandException PAYLOAD_NULL = new CommandException("Command_analyze_02", "Payload Cannot Be Null");
    public static CommandException FRAMEWORK_FAILED = new CommandException("Command_analyze_03", "Framework Failed to be Checked");
    public static CommandException CHECK_FAILED = new CommandException("Command_analyze_04", "Command Failed to be Checked");
    public static CommandException CONFIGURE_NOT_EXIST = new CommandException("Command_error_1001", "Configure is not Exist");
    public static CommandException REDIS_ERROR = new CommandException("Command_error_1002", "Cache Command in Redis Error", true);
    // constructors, getters, setters omitted
}

6. Over‑engineered Stream Usage

The final example showcases an excessively complex Stream pipeline that chains multiple map, filter, and orElseThrow calls, turning a straightforward query into unreadable “Stream wizardry”.

//Stream 用的66的
final EventAction eventAction = redisObj(EventActionKey + distributionEventId, () ->
    Optional.of(distributionEventId)
        .map(eventId -> {
            EventActionExample example = new EventActionExample();
            example.createCriteria()
                .andEventIdEqualTo(eventId)
                .andTriggerTypeEqualTo(EnumEventTriggerType.DISTRIBUTION_PURCHASE.getCode().byteValue());
            return example;
        })
        .map(eventActionMapper::selectByExample)
        .filter(StringUtil::isNotEmpty)
        .map(e -> e.get(0))
        .orElseThrow(() -> ExceptionUtil.createParamException("事件触发信息不存在")),
    EventAction.class);

final AwardConfig awardConfig = redisObj(EventConfigKey + eventAction.getId(), () ->
    Optional.ofNullable(eventAction.getId())
        .map(actionId -> {
            AwardConfigExample example = new AwardConfigExample();
            example.createCriteria().andActionIdEqualTo(actionId);
            return example;
        })
        .map(awardConfigMapper::selectByExample)
        .filter(StringUtil::isNotEmpty)
        .map(e -> e.get(0))
        .orElseThrow(() -> ExceptionUtil.createParamException("xxx")),
    AwardConfig.class);

Optional.of(req)
    .map(e -> e.clueUid)
    .map(id -> {
        ClueExample example = new ClueExample();
        example.createCriteria()
            .andClueUidEqualTo(id)
            .andDeletedEqualTo(false)
            .andReceivedEqualTo(false)
            .andCreateTimeGreaterThan(now - cluetime);
        example.setOrderByClause("create_time asc");
        return example;
    })
    .map(clueMapper::selectByExample)
    .filter(StringUtil::isNotEmpty)
    .ifPresent(clues -> {
        ClueResp clueResp = Optional.of(req)
            .filter(c -> { c.count = clues.size(); return true; })
            .map(this::awardValue)
            .orElseThrow(() -> ExceptionUtil.createParamException("参数错误"));
        Integer specialId = req.getIsHead() ? clues.get(0).getId() : clues.get(clues.size() - 1).getId();
        clues.stream()
            .peek(clue -> {
                AwardConfig awardConfigClone = Optional.of(awardConfig)
                    .map(JSONUtil::obj2Json)
                    .map(json -> JSONUtil.json2Obj(json, AwardConfig.class))
                    .orElseGet(AwardConfig::new);
                awardConfigClone.setMoney(
                    Optional.of(clue.getId())
                        .filter(specialId::equals)
                        .map(e -> clueResp.specialReward.longValue())
                        .orElse(clueResp.otherAverageReward.longValue())
                );
                eventActionService.assembleAward(awardConfigClone, clue.getAdviserUid(), clue.getAdviserUid(), clue.getClueUid(), eventAction, new PasMessageParam(), clue.getId(), AwardRelationType.Clud.code());
            })
            .forEach(clue -> {
                clue.setOrderNo(req.orderNo);
                clue.setCommodityName(req.commodityName);
                clue.setOrderAmount(req.orderAmount);
                clue.setReceived(true);
                clue.setModifyTime(now);
                clueMapper.updateByPrimaryKeySelective(clue);
            });
    });

Conclusion

The collection highlights how seemingly clever tricks—over‑use of StringBuffer, monstrous one‑liners, deep nesting, premature performance hacks, bloated exception classes, and convoluted Stream pipelines—can quickly degrade code quality. Refactoring toward clear, modular, and idiomatic Java dramatically improves readability and maintainability.

Original Source

Signed-in readers can open the original source through BestHub's protected redirect.

Sign in to view source
Republication Notice

This article has been distilled and summarized from source material, then republished for learning and reference. If you believe it infringes your rights, please contactadmin@besthub.devand we will review it promptly.

JavarefactoringStream APIcode smellsbad practices
Java Backend Technology
Written by

Java Backend Technology

Focus on Java-related technologies: SSM, Spring ecosystem, microservices, MySQL, MyCat, clustering, distributed systems, middleware, Linux, networking, multithreading. Occasionally cover DevOps tools like Jenkins, Nexus, Docker, and ELK. Also share technical insights from time to time, committed to Java full-stack development!

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.