使用空合并运算符重用的原子代码块
Posted
tags:
篇首语:本文由小常识网(cha138.com)小编为大家整理,主要介绍了使用空合并运算符重用的原子代码块相关的知识,希望对你有一定的参考价值。
A style of code reuse. Breaking methods (in this case MVC controller) into very small reusable atomic chunks that either perform an operation then return an ActionResult OR return null, then using with the null-coalescing operator.
public ActionResult AddComment(CommentAddModel model) { return IfNotValidModelStateViewContent(model) ?? IfNotKnownHumanViewCommentCaptcha(model) ?? AddCommentThenViewReciept(model); } private ActionResult IfNotValidModelStateViewContent(CommentAddModel model) { var contentItem = _repository.FindById<ContentItem>(model.Id); return !ModelState.IsValid ? View(contentItem, model) : null; } private ActionResult IfNotKnownHumanViewCommentCaptcha(CommentAddModel model) { var sessionId = _httpContextProvider.Current.Session.SessionID; var isKnownHuman = _captchaService.IsKnownHuman(sessionId); return !isKnownHuman ? ViewCommentCaptcha(sessionId, model) : null; } private ActionResult AddCommentThenViewReciept(CommentAddModel model) { var contentItem = _repository.FindById<ContentItem>(model.Id); _commentService.AddCommentToEntity(contentItem, model.Body, model.AuthorName, model.AuthorEmailAddress); _repository.Save(contentItem); return ViewCommentReceipt(contentItem.Url); }
以上是关于使用空合并运算符重用的原子代码块的主要内容,如果未能解决你的问题,请参考以下文章