Return to Snippet

Revision: 18555
at October 2, 2009 06:24 by jmcd


Initial Code
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);
}

Initial URL


Initial Description
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.

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

Initial Tags
c

Initial Language
C#