下面是一个很常见的游戏框架2控制器:阶:改善这段代码的可读性和风格
def save(ideaId : Long) = CORSAction { request =>
Idea.findById(ideaId).map { idea =>
request.body.asJson.map { json =>
json.asOpt[Comment].map { comment =>
comment.copy(idea = idea).save.fold(
errors => JsonBadRequest(errors),
comment => Ok(toJson(comment).toString)
)
}.getOrElse (JsonBadRequest("Invalid Comment entity"))
}.getOrElse (JsonBadRequest("Expecting JSON data"))
}.getOrElse (JsonBadRequest("Could not find idea with id '%s'".format(ideaId)))
}
我觉得有点讨厌所有这些嵌套.maps,我也找了一下单调乏味,每个错误处理是在底部
你会如何改进它,使更多的可读性,同时保持作为功能惯用斯卡拉代码?
我在想也许这样的事情(这是seudo代码,仍然不能编译)
def save(ideaId : Long) = CORSAction { request =>
val idea = Idea.findById(ideaId).getOrElse(
return JsonBadRequest("Could not find idea with id '%s'".format(ideaId)))
val json = request.body.asJson.getOrElse(
return JsonBadRequest("Expecting JSON data"))
val comment = json.asOpt[Comment].getOrElse(
return JsonBadRequest("Invalid Comment entity"))
comment.copy(idea = idea).save.fold(
errors => JsonBadRequest(errors),
comment => Ok(toJson(comment).toString)
)
}
PS:我知道这将是更好的避免return语句...
恭喜,你刚刚发明了monads! –
删除'返回'作为首发。哦,等等,他们是否应该打破“save”方法的流程? – pedrofurla