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
- 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.
- Use a flag or condition to track if you've found your target (the maze end), instead of returning early.
- 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).
- 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
Pathas soon as you find the end, we update the existingpathinstance 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 returningnull, as it avoidsNullPointerExceptionfor callers). If you do need to returnnullin some cases, just initializePath 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
pathobject, not creating new ones mid-logic.
内容的提问来源于stack exchange,提问作者Qing Li
相关产品推荐
相关产品推荐

