grails - Groovy/Grails 代码清理建议,请!

标签 grails groovy coding-style

我是 Groovy & Grails 的新手,我觉得事情不必那么难看……那么我怎样才能让这段代码更好看呢?

这是一个 Grails Controller 类,去掉了一些无趣的部分。尽量不要太挂断我的 Car只有一个 Wheel - 我可以稍后处理:-)
changeWheel是一个 Ajax Action 。

class MyController {
    ...
    def changeWheel = {
        if(params['wheelId']) {
            def newWheel = Wheel.findById(params['wheelId'])
            if(newWheel) {
                def car = Car.findById(params['carId'])
                car?.setWheel(newWheel)
                if(car?.save()) render 'OK'
            }
        }
    }
}

最佳答案

我实际上开始使用 Command Objects .

尝试这个:

class MyController {
    def index = {
    }
    def changeWheel = { CarWheelCommand cmd ->
        if(cmd.wheel && cmd.car) {
            Car car = cmd.car
            car.wheel = cmd.wheel
            render car.save() ? 'OK' : 'ERROR'
        } else {
            render "Please enter a valid Car and wheel id to change"
        }
    }
}
class CarWheelCommand {
    Car car
    Wheel wheel
}

然后在您的 View 中使用' car.id ' 和 ' wheel.id ' 而不是 ' carId ' 和 ' wheelId '

关于grails - Groovy/Grails 代码清理建议,请!,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/4420334/

相关文章:

Grails 1.1 以及如何信息级别日志记录

grails - 如何将 TIFF ImageReader 添加到 Grails 中注册的那些

c - 我应该在哪里释放函数内的内存?

grails - 在 secuser 上成功注册并自动登录后,Spring Security 重定向到上一页

grails - 在一个servlet容器中部署的Grails应用程序的不同日志文件

java - 如何在字符串中插入一个字符(java/groovy)?

Grails 简单插件 "not a valid plugin"

gradle - Groovy + Geb+Spock 在 Windows 服务器上部署

java - 最常用的 Java 代码约定/风格指南

haskell - Haskell 中的闭包和列表推导