Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Removing boilerplate from ASP.NET MVC actions

I have something like this in almost every action:

public ActionResult Show(int object_id)
{
    Object obj = ObjectRepository.ById(object_id);
    if (obj == null)
    {
        throw new HttpException(404);
    }
    if (obj.SomeCheck)
    {
        throw new HttpException(403);
    }
    // processing
}

Question is how to move object getting (and throwing http exceptions) away from action and have something like this:

public ActionResult Show(Object obj)
{
    // processing
}

UPD: Can't change ObjectRepository and model itself, it's used not only with ASP.NET but in other parts of the project.

like image 300
awsum Avatar asked Dec 14 '22 22:12

awsum


1 Answers

One option is to refactor your boilerplate into a private method:

private object GetItem(object obj) {
  Object obj = ObjectRepository.ById(object_id);

  if (obj == null) {
    throw new HttpException(404);
  }

  if (obj.SomeCheck()) {
    throw new HttpException(403);
  }

  return obj;
}

Then:

public ActionResult Show(int object_id) {
  object obj = GetItem(object_id);

  // processing
}
like image 61
Peter Gluck Avatar answered Dec 17 '22 13:12

Peter Gluck