Atomic chunks of code for reuse with the null-coalescing operator


/ Published in: C#
Save to your folder(s)

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.


Copy this code and paste it in your HTML
  1. public ActionResult AddComment(CommentAddModel model)
  2. {
  3. return
  4. IfNotValidModelStateViewContent(model) ??
  5. IfNotKnownHumanViewCommentCaptcha(model) ??
  6. AddCommentThenViewReciept(model);
  7. }
  8.  
  9. private ActionResult IfNotValidModelStateViewContent(CommentAddModel model)
  10. {
  11. var contentItem = _repository.FindById<ContentItem>(model.Id);
  12. return !ModelState.IsValid ? View(contentItem, model) : null;
  13. }
  14.  
  15. private ActionResult IfNotKnownHumanViewCommentCaptcha(CommentAddModel model)
  16. {
  17. var sessionId = _httpContextProvider.Current.Session.SessionID;
  18. var isKnownHuman = _captchaService.IsKnownHuman(sessionId);
  19. return !isKnownHuman ? ViewCommentCaptcha(sessionId, model) : null;
  20. }
  21.  
  22. private ActionResult AddCommentThenViewReciept(CommentAddModel model)
  23. {
  24. var contentItem = _repository.FindById<ContentItem>(model.Id);
  25. _commentService.AddCommentToEntity(contentItem, model.Body, model.AuthorName, model.AuthorEmailAddress);
  26. _repository.Save(contentItem);
  27. return ViewCommentReceipt(contentItem.Url);
  28. }

Report this snippet


Comments

RSS Icon Subscribe to comments

You need to login to post a comment.