【发布时间】:2014-12-03 12:45:59
【问题描述】:
最初的问题
如果您有不同的方法,基本上只有一行不同,是否有一种方法可以通过创建一个方法使其干燥。
例子:
def showA( ) {
def instance
try {
instance = A.findById( params.id )
} catch ( Exception e ) {
def message = "Error while retrieving details for the given id ${ params.id }, $e"
log.error message
responseAsJson( 400, "Invalid id", message )
return false
}
return checkAndRender(instance, params.id);
}
def showB( ) {
def instance
try {
instance = B.findByBId( params.BId )
} catch ( Exception e ) {
def message = "Error while retrieving details for the given id ${ params.id }, $e"
log.error message
responseAsJson( 400, "Invalid id", message )
return false
}
return checkAndRender(instance, params.id);
}
那么,有没有办法制作一个方法并简单地作为参数传递:
- 领域类
- 要搜索的 ID
还是改为传递 SQL 语句会更好?
更新
根据@dmahapatro 的评论,我想出了以下内容:
def showA( ) {
def clos = {id -> A.findByAId( id ) }
return findAndShow(clos, params.AId, params )
}
def showB( ) {
def clos = {id -> B.findByBId( id ) }
return findAndShow(clos, params.BId, params )
}
def findAndShow(Closure closure, def id, def p)
{
def instance
try {
instance = closure(id)
}
catch ( Exception e ) {
def message = "Error while retrieving instance details for the given id ${ id }, $e"
log.error message
responseAsJson( 400, "Invalid Id", message )
return false
}
return checkAndRender(instance, id);
}
剩下的问题只有:
- 如何进一步清理/使其更清洁。
-
如何绕过警告:
[ApiController] 中的 [findAndShow] 动作接受一个参数 键入 [groovy.lang.Closure]。接口类型和抽象类类型 不支持作为命令对象。该参数将被忽略。
def findAndShow(Closure closure, def id, def p)
【问题讨论】:
-
你可以有一个将闭包作为参数的方法。 Like this 应该可以工作。注意
tryCatchClosure方法的使用。 -
@dmahapatro 这是个好主意。我收到了一个烦人的警告:
The [findAndShow] action in [ApiController] accepts a parameter of type [groovy.lang.Closure]. Interface types and abstract class types are not supported as command objects. This parameter will be ignored.更新问题。 def findAndShow(Closure 闭包, def id, def p) -
@dmahapatro 如果您想写下您的回复作为我投票的答案。谢谢。
-
将 findAndShow 设为受保护而不是公开,这样可以消除警告。
-
@Gregor Petrin 是的,这行得通!