AlexArchive / Medium

Medium is a beautiful blog engine.
19 stars 4 forks source link

Encapsulate duplicate slug conditional code #7

Closed AlexArchive closed 9 years ago

AlexArchive commented 9 years ago

In order to prevent the user from inputting a duplicate slug and subsequently causing an exception, I added some functional but brash code to check if the slug is already occupied. It lives in the controller and it looks like this:

var slug = post.Title.ToSlug();
var requestHandler = new PostRequestHandler();
var request = new PostRequest {Slug = slug};
if (requestHandler.Handle(request) != null)
{
    ModelState.AddModelError("", "A post with this title already exists.");
    return View(post);
}

I hate this code.

I think I should encapsulate this functionality in the AddPostCommandHandler (but then again, I am not sure) but to do so is not entirely straightforward.