Suppose I have a CategoriesController for managing some kind of categories list. It has these action methods:
public ActionResult Get(Int32 categoryId);
public ActionResult Edit(Int32 categoryId);
[HttpPost]
public ActionResult Edit(Int32 categoryId, CategoryModel model);
public ActionResult Delete(Int32 categoryId);
[HttpPost]
public ActionResult Delete(Int32 categoryId, DeleteModel model);
All of these methods run the same code that verifies that categoryId is valid and the category exists, it retrieves it from the database, and performs access-level verification. Parts of the verification code returns an ActionResult directly, others do not (for example, if the categoryId doesn’t exist, then it will return a Http404 action result immediately, but if everything’s okay then it goes down to the action-specific code.
Is the best way to cut down on code duplication to do something like this?
private ActionResult EnsureCategory(Int32 categoryId, out DBCategory dbCategory);
public ActionResult Edit(Int32 categoryId) {
DBCategory dbCategory;
ActionResult error = EnsureCategory(categoryId, out dbCategory);
if( error != null ) return error;
// this now means that only 3 lines of code will be shared between the Action methods, but it still seems too much.
}
It’s a shame C# doesn’t support preprocessor macros, or something like it, because this would be a good place to use them. Unless there’s a better approach?
I ended up continuing to use the approach I suggested to myself in my original question. I did consider using @SteveB’s T4 template suggestion, but I find T4 templates a bit hard to use.