Note that there are some explanatory texts on larger screens.

plurals
  1. POAutomate handling of null models to clean up controllers and views
    primarykey
    data
    text
    <p>I'd really like to improve the current readability of my code by reducing the amount of null checks I'm doing. I get the feeling that although checking for certain conditions is a good thing, repeating those checks in various places isn't such a good idea. As an example, here's one method of my <code>PostsController</code>:</p> <pre><code>public ActionResult ShowPost(int PostID, string slug) { PostViewModel viewModel = new PostViewModel(); Post model = postRepository.FindPost(PostID, filterByPublished: true); if (model.PostID == 0) return Redirect(Url.Home()); else if (model.Slug != slug) return RedirectPermanent(Url.ShowPost(model.PostID, model.Slug)); postRepository.PostVisited(model); Mapper.Map(model, viewModel); return View(viewModel); } </code></pre> <h3>What I don't like</h3> <p>Firstly, the check to see if <code>PostID</code> is 0. It can be 0 because of the way I set that method up in the repository:</p> <pre><code>public Post FindPost(int id, bool filterByPublished = false) { var query = db.Posts.Where(post =&gt; post.PostID == id); if (filterByPublished) query = query.Where(post =&gt; post.IsPublished == filterByPublished); return query.Select(post =&gt; post).SingleOrDefault() ?? new Post { PostID = 0 }; } </code></pre> <p>I don't like that I've pushed that little hack in there just to cater for handling a null model. I also check for a null model in various strongly-typed views which require a <code>PostViewModel</code>.</p> <h3>Possible solution</h3> <p>My first thought would be to create an action filter, override <code>OnResultExecuting</code> and check for null models there. I actually quite like this idea and it does solve the problems of checking for null models in the controller and also the view. However, what it doesn't do is cater for situations like this:</p> <pre><code>else if (model.Slug != slug) </code></pre> <p>That'll give me a null reference exception as would passing the model to the <code>postRepository</code> to update the view count. I'm guessing the call to <code>Mapper.Map</code> would do the same.</p> <p>So what can do I about it? Could I simply override <code>OnActionExecuted</code> and check for exceptions there, logging them and then redirecting to a custom error view? Does that sound like a reasonable approach?</p> <p>Thank you.</p>
    singulars
    1. This table or related slice is empty.
    1. This table or related slice is empty.
    plurals
    1. This table or related slice is empty.
    1. This table or related slice is empty.
    1. This table or related slice is empty.
 

Querying!

 
Guidance

SQuiL has stopped working due to an internal error.

If you are curious you may find further information in the browser console, which is accessible through the devtools (F12).

Reload