You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

Java方法中如何仅保留一个return语句?对象返回场景存疑

How to Use a Single Return Statement for Methods Returning Custom Objects (e.g., Path)

Hey there! I get where you're coming from—using a single return statement is straightforward for simple scenarios, but it can feel tricky when you're returning a custom object like Path. The good news is the core idea stays the same: initialize your return variable upfront, modify its state throughout your logic, and return it once at the end.

Let's walk through how to apply this to your maze path-finding code. First, you already started by creating a Path instance—this will be our single return variable that we modify as we find (or don't find) a path.

Step-by-Step Solution

  1. Initialize your return object at the start of the method. This is the only object you'll return, so all path-building logic will update this instance.
  2. Use a flag or condition to track if you've found your target (the maze end), instead of returning early.
  3. Update the return object's state once you locate the end (e.g., backtrack from the end position to the start and populate the path).
  4. Return the single initialized object after all logic completes—whether a path was found or not.

Modified Code Example

public Path findPath(Maze maze) {
    // Initialize the single return object we'll modify throughout the method
    Path path = new Path();
    MazePosition initialPos = new MazePosition(0, 0, null);
    Stack<MazePosition> posForExplore = new Stack<>();
    MazePosition currentPos = initialPos;
    posForExplore.push(currentPos);
    boolean pathFound = false;

    while (!posForExplore.isEmpty() && !pathFound) {
        currentPos = posForExplore.pop();
        
        // Check if we've reached the maze end
        if (maze.isEnd(currentPos)) {
            // Backtrack from end to start to build the path
            while (currentPos != null) {
                path.addCoordinate(currentPos.getX(), currentPos.getY());
                currentPos = currentPos.getPrevious();
            }
            // Reverse to get start-to-end order
            path.reverse();
            pathFound = true;
        } else if (!maze.isVisited(currentPos)) {
            maze.markVisited(currentPos);
            // Add valid neighboring positions to explore next
            List<MazePosition> neighbors = maze.getValidNeighbors(currentPos);
            for (MazePosition neighbor : neighbors) {
                posForExplore.push(neighbor);
            }
        }
    }

    // Single return statement at the end—returns either the populated path or an empty one
    return path;
}

Key Notes

  • No early returns: Instead of returning a new Path as soon as you find the end, we update the existing path instance and set a flag to exit the loop.
  • Consistent return value: If no path is found, you'll return an empty Path (which is better practice than returning null, as it avoids NullPointerException for callers). If you do need to return null in some cases, just initialize Path path = null; and instantiate it only when a path is found, then return it at the end.
  • State modification: All changes to the return value happen by modifying the state of the initial path object, not creating new ones mid-logic.

内容的提问来源于stack exchange,提问作者Qing Li

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.05.21 07:20:31