善用封盖
不久前,在博客文章中 ,我解釋了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
總結
- 上一篇: 国债逆回购的参与金额起点是多少?
- 下一篇: r1风险会丢失本金吗?