假设我有html表单和控制器来处理该表单.Controller启动一个服务,它接受2个参数.如果用户发送空字段,则参数可以为null.
现在......如何处理这种情况?什么更优雅?我更喜欢将此值从控制器传递到服务,而不检查控制器层中的值是否为null.
第一种方法 - 检查Controller层的空值
@RequestMapping(method = RequestMethod.POST) public String borrowBook(@RequestParam(value = "borrower_id", required = false) Long borrowerId, @RequestParam(value = "book_id", required = false) Long bookId){ if (borrowerId != null && bookId != null) borrowService.createBorrow(bookId, borrowerId); return "redirect:index.html"; }
第二种方法 - 在cotnroller层将值传递给service和cheking exception
@RequestMapping(method = RequestMethod.POST) public String borrowBook(@RequestParam(value = "borrower_id", required = false) Long borrowerId, @RequestParam(value = "book_id", required = false) Long bookId){ try { borrowService.createBorrow(bookId, borrowerId); } catch(CreateBorrowException e){ //Do something } return "redirect:index.html"; }
第三种方法 - 在服务层处理异常,因此控制器实际上不知道是否发生异常.
Service : public void createBorrow(Long bookId, Long borrowerId) { try { Book book = getBookFromId(bookId); Borrower borrower = getBorrowerFromId(borrowerId); Borrow borrow = new Borrow(book, borrower); markBookAsRented(book); setBorrowIntoEntities(borrow, book, borrower); persistEntities(borrow, book, borrower); } catch (Exception e) { } }
你怎么看?我更喜欢选项2.
如果调用者发送空表单是正常的,那通常是null
检查的用例.
如果调用者发送空表单是不常见的(错误,例如异常),那通常是允许异常(并且可能处理它或允许它传播给调用者)的用例.
哪个更"优雅"是一种风格问题.
请注意,虽然输入try
块并不昂贵,但允许抛出异常(昂贵=运行时和[临时]内存成本).但是,当然,除非你在一秒钟内抛出数十万个异常,否则哪个更快更重要.