善用工具_善用封盖
善用工具
不久前,在博客中 ,我解釋了Groovy中Closure的含義。 這篇博客文章將解釋一個使用它們的好例子。 最近,我發現自己不得不為服務AJAX請求的大量后端Controller API編寫相同的異常處理邏輯。 就像這樣:
可以看出,這里有一些代碼重復。 本著DRY的精神(不要重復自己),最好只定義一次此異常處理邏輯,然后重新使用它。 因此,我定義了以下實用程序方法,該方法實現了異常處理模式并采取了關閉操作,該閉包將為其執行異常處理。
private JSON withExceptionHandling(Closure c) {try {...c.call();} catch (ServiceException serviceException) {// don't care too much about this. // log and move on... } catch (SessionException sessionException) {// clear out session cookies...// send 403 to client ...} catch (Exception ex) {throw new ApiException(ex)}}我們可以使用{}將代碼封閉在Groovy中,以使其成為閉包。 這意味著我可以將Controller方法中的邏輯轉換為Closures,并將其傳遞給Utility方法。 而且當我將其傳遞給實用程序方法時,我甚至不需要將其傳遞給()內部,因為Groovy并不使您滿意。 因此,這意味著我可以消除所有常見的異常處理,消除代碼膨脹,而且我的Controller API更整潔。
class ApiRugbyPlayerController {JSON getPlayerStats() {withExceptionHandling {...// invoke business service method to get player stats} }JSON updatePlayerStats() {withExceptionHandling {...// invoke business service method to update player stats} }JSON queryPlayerStats(){withExceptionHandling {...// invoke business service method to query player stats} }private JSON withExceptionHandling(Closure c) {try {...c.call();} catch (ServiceException serviceException) {// don't care too much about this. // log and move on... } catch (SessionException sessionException) {// clear out session cookies...// send 403 to client ...} catch (Exception ex) {throw new ApiException(ex)}} } 所以我們去了。 我們堅持DRY原則,避免了代碼膨脹,并為我們的異常處理提供了專門的場所,確信它可以始終如一地實現。 Groovy閉包的這個例子有點像,但是就像JavaScript中的第二次調用一樣。 如果我們想用Java做類似的事情,那將涉及很多代碼。 我們可以使用類似命令模式的東西,并將它們的執行放入異常處理邏輯中。 您將具有更多的去耦功能,但是您將擁有更多的代碼。 或者,您可以使所有AJAX API輸入一個通用方法(例如Front Controller),但在該處處理通用異常。 同樣,可能,但僅需更多代碼。 在下一次之前,請多保重。
翻譯自: https://www.javacodegeeks.com/2014/03/good-use-of-closures.html
善用工具
總結
- 上一篇: Var和语言设计
- 下一篇: Jakarta EE 8状态