1) pull
params['wheelId']
and
params['carId']
into your own defs
2) multiple nested ifs are never optimal. You can get rid of the outermost by having the validateParams method and rejecting some kind of answer if wheelId and carId are not set. Or simply
if (carId == null || wheelId == null) {
3) Assuming everything is fine, you could just do
def newWheel = Wheel.findById... def car = Car.findById... if (car != null && newWheel != null) { car.setWheel(newWheel) car.save() render 'OK' } else { // either wheel or car is null }
this eliminates more nested structures ...
4) finally, in order to make the code self-declared, you can do such things as assigning conditional tests to the corresponding names. So something like
def carAndWheelOk = car != null && newWheel != null if (carAndWheelOk) { // do the save } else { // car or wheel not ok }
this may be redundant for two tests, but you only care about one wheel here. If you have dealt with all 4 wheels, this type of thing improves readability and maintainability.
Please note that this tip works in any language. I donβt think you can do too much with groovy syntactic sugar, but perhaps some groovy gurus can offer better advice.
source share