很多朋友寫代碼時(shí),return 語句用得比較隨意。嵌套好層 if 才 return,讓人眼花繚亂。其實(shí) return 寫得好不好,直接影響代碼的可讀性和 bug 率。 今天分享10個(gè)實(shí)用的return寫法!
1、提前 return反面案例public boolean isValid(User user) { boolean result = false; if (user != null) { if (user.getName() != null && !user.getName().isEmpty()) { if (user.getAge() > 0) { result = true; } } } return result; }
public boolean isValid(User user) { if (user == null) return false; if (user.getName() == null || user.getName().isEmpty()) return false; if (user.getAge() <= 0) return false; return true; }
2、守衛(wèi)模式 這種寫法專業(yè)點(diǎn)叫Guard Clause(守衛(wèi)語句)public void processOrder(Order order) { if (order == null) return; if (!order.isPaid()) return; if (order.isProcessed()) return; log.info("開始處理訂單: " + order.getId()); // ... 正經(jīng)邏輯 }
主流程完全不用縮進(jìn),干干凈凈。3、return配合OptionalJava8的Optional,用好了能少寫一堆判空public Optional<User> findUserById(Long id) { User user = userMapper.selectById(id); return Optional.ofNullable(user); }
findUserById(1001L) .ifPresent(user -> System.out.println(user.getName()));
4、三元運(yùn)算符反面案例: public String getStatusDesc(int status) { String desc; if (status == 1) { desc = "啟用"; } else { desc = "禁用"; } return desc; }
public String getStatusDesc(int status) { return status == 1 ? "啟用" : "禁用"; }
5、switch表達(dá)式public String getRoleName(int role) { return switch (role) { case 1 -> "管理員"; case 2 -> "運(yùn)營"; case 3 -> "普通用戶"; default -> "未知角色"; }; }
6、try-catch中的return 這個(gè)坑我踩過:在 finally 里寫 return ,結(jié)果異常被吞了! public String getData() { try { return "success"; } catch (Exception e) { return "error"; } finally { return "finally always wins"; // ? 危險(xiǎn)!永遠(yuǎn)返回這個(gè)! } }
不要在 finally 里 return! 7、方法末尾return常見錯(cuò)誤: public String getStatus(int code) { if (code == 200) { return "成功"; } // 如果 code 是 404 呢?沒 return!編譯報(bào)錯(cuò)! }
public String getStatus(int code) { if (code == 200) return "成功"; if (code == 404) return "未找到"; return "未知狀態(tài)"; // 兜底返回 }
8、return一個(gè)空集合,而不是null這個(gè)原則很重要! // 錯(cuò)誤示范 public List<String> getTags() { if (tags == null) return null; return tags; }
正確做法: public List<String> getTags() { return tags == null ? Collections.emptyList() : tags; // 或者用 Guava: Lists.newArrayList() }
9、return與Stream配合public List<String> getValidUserNames(List<User> users) { return users.stream() .filter(Objects::nonNull) .filter(u -> u.getStatus() == 1) .map(User::getName) .collect(Collectors.toList()); } 函數(shù)式編程,邏輯清晰,不容易出錯(cuò)return雖小,但用得好,可以讓代碼更清晰、更安全、bug更少。
你在項(xiàng)目中是怎么用 return 的?有沒有見過比較離譜的寫法?歡迎在評(píng)論區(qū)分享你的寫法!
|