5

Just wondering why almost every controller method I see in sample MVC code returns ActionResult, even if it's obvious that the code can only return one type of result. I understand there are certain instances where it's warranted because you may return, say a RedirectResult or a ViewResult depending on the logic, but that's not the case for most of the methods I've seen.

Isn't it tantamount to having a return type of 'object' on a method? Why not just specify JsonResult, or FileResult or ViewResult as the return type? Is there a benefit I'm not seeing to settting the return type to ActionResult on every controller method?

Classic example:

public ActionResult Index()
{
    return View();
}

Why does this seem to be the norm instead of this:

public ViewResult Index()
{
    return View();
}

EDIT: So far all of the responses except for one have indicated that ActionResult is just more generic. I know that much. :) Why is this accepted practice on a controller method though, and not anywhere else? You don't just return the highest level-base classes of a type that you can on a normal method, you attempt to return the most specific type you can usually. What makes controller methods so different that bloggers and "sample code writers" (yes, I made that term up) would just resort to returning ActionResult?

Scott
  • 13,735
  • 20
  • 94
  • 152
  • possible duplicate of [Must ASP.NET MVC Controller Methods Return ActionResult?](http://stackoverflow.com/questions/1021568/must-asp-net-mvc-controller-methods-return-actionresult) – bzlm Jan 10 '11 at 18:33

6 Answers6

6

quoted verbatim from an accepted answer here on SO. makes sense to me:

Must ASP.NET MVC Controller Methods Return ActionResult?

You can absolutely use specific return types, even though most examples on the web seems to return the ActionResult. The only time I would return the ActionResult class is when different paths of the action method returns different subtypes.

Steven Sanderson also recommends returning specific types in his book Pro ASP.NET MVC Framework. Take a look at the quote below:

"This action method specifically declares that it returns an instance of ViewResult. It would work just the same if instead the method return type was ActionResult (the base class for all action results). In fact, some ASP.NET MVC programmers declare all their action methods as returning a nonspecific ActionResult, even if they know for sure that it will always return one particular subclass. However, it's a well-established principle in object-oriented programming that methods should return the most specific type they can (as well as accepting the most general parameter types they can). Following this principle maximizes convenience and flexibility for code that calls your method, such as your unit tests."

see also:

http://www.bengtbe.com/blog/post/2009/07/01/Use-specific-return-types-in-your-ASPNET-MVC-action-methods.aspx

Cœur
  • 37,241
  • 25
  • 195
  • 267
jim tollan
  • 22,305
  • 4
  • 49
  • 63
  • Makes sense to me as well and I'll accept this as the answer, but I'm still curious as to why, in an environment where developers are used to declaring return types as specifically as possible, all of a sudden MVC programmers seem to have just thrown that concept out in one particular instance. Doesn't make a whole lot of sense. – Scott Jan 06 '11 at 17:38
  • 2
    @Scott Schluer: Because the real "consuming code" for controller actions is usually either a browser or javascript, the benefits of type safety are less pronounced in this particular instance. If you could consume this code in a type-safe language the way GWT's RPC framework is set up, I think people would be more conscientious about setting specific return types. – StriplingWarrior Jan 06 '11 at 18:04
  • 2
    I have found using ActionResult for all of them is pretty handy. I agree that the reduced type safety concerns make this more ok in this specific situation. I think this is a practice derived primarily for convenience and readability. When I see ActionReult, I know what the purpose of the method is immediately. And If I need to throw a Redirect on that action, I don't need to modify the return type to do so. – Derrick Jan 06 '11 at 18:45
  • 1
    @Derrick Bingo about the Redirect. @jim What Derrick says - if you ever need to redirect instead of showing a page, you'd need to change the return type. – bzlm Jan 10 '11 at 18:35
  • bzlm - accepted on that front definately. however, in that case, the return type could be 'elevated' following that change. – jim tollan Jan 10 '11 at 18:57
1

My guess would be that ActionResult gets returned rather than a more specific result simply because there's no need to make the code more specific.

Using a more generic type keeps things more flexible.

Keep in mind that changing the return type may not be an issue in the Web Application project, but it would also cause you to change all your Unit Tests in the test project as well.

Justin Niessner
  • 242,243
  • 40
  • 408
  • 536
  • It seems to me that if you change what you're returning, you're going to have to change your unit tests to reflect that change anyway. I'd rather have the compiler tell me "these unit tests won't work anymore" when this happens. In most cases, your unit tests are just going to have to cast the result to its actual type in order to test, for example, that the Model on the returned ViewResult has the values you're expecting. – StriplingWarrior Jan 06 '11 at 16:20
  • @StriplingWarrior - Personally, I'd rather be able to build my projects and then find out that my Unit Test now fails rather than having to hold up the build of my project because of broken code in a Unit Test. – Justin Niessner Jan 06 '11 at 16:22
  • I suppose that's a matter of opinion. I personally feel that catching more issues at compile time saves time, and is one of the biggest reasons to use a type-safe, compiled language. – StriplingWarrior Jan 06 '11 at 16:36
0

ScottGu did it prob 4 the same reason; it's just easier to show an example. The subject of the demo often dictates the ode quality you see; if it's just for exmaples, they'll generally throw something to gether just to illustrate a point (they made it easy on themselves to write/test the example on their end b4 publishing, and just left it that way when posting; I've done this). As far as best practices; about HTML and JS (essentially) "not caring" as much about types, dont let issues with JavaScript (like type weakness) leak thru/infect your own honed good coding style. Use the specific type whenerver possible. Plus, ur JS code is also prob expecting a JSON result anyway (if it's coded using typing best-practices), and is aomsthing that code can test for as well, so wouldn't want to tie the JS code's hands there if it's trying to do the right thing on types where it can. True that in some cases, the adverse effects are more/less pronounced than in others (like returning to a less type-safe lang), it's just a better programming habit to be consistent about. In general, doing this kind of thing usu results in some kind of type casting/coersion to get back to the more specific object's capabilities you want to use upon return (which more than likely won't be available in a baser object - if it always is, then your type is too specific/should be the base anyway). Casting is inherently ugly/evil; deriving types at run time will always get you in trouble (why the practice has been discouraged/benes of static/strong typing/safety extolled for decades). Let the consumer/maintainer of your code also be able to discern thru metainfo (hovering over the method, etc.) what the function is actually doing/returning. And in fact, it's better for unit testing, as this is a condition that can be tested (as the excerpt from Steven Sanderson's book alludes to). And did I catch a guy using not wanting to hold a build as a reason for being weakly typed? Really?

galaxis
  • 925
  • 8
  • 10
0

Only when you're not sure what the return type will be b/c of logic inside the controller you should use a general return type. otherwise - use specific (it is considered BETTER programming).

I don't know why people use ActionResult in samples, but I've seen many things in samples that I might not agree - take what good and leave the rest there....

IMHO - You should use ViewResult when you know this is the only returned object you use and not ActionResults.

Dani
  • 14,639
  • 11
  • 62
  • 110
0

It's maybe because ActionResult is the highest object that a view can handle.

ActionResult

ViewResult

System.Object
  System.Web.Mvc.ActionResult
    System.Web.Mvc.ViewResultBase
      System.Web.Mvc.ViewResult

For me, each XXXResult is dedicated to a specific use. If you do not need specific...

kerrubin
  • 1,606
  • 1
  • 20
  • 25
0

I think the real reason is that the auto-generated code in the MVC templates start you out with an ActionResult, and people just follow the pattern. Since many people don't unit test their controller actions, they don't consume the results in a type-safe way that would make this a pain point.

StriplingWarrior
  • 151,543
  • 27
  • 246
  • 315
  • That seems crazy. Check out http://weblogs.asp.net/scottgu/archive/2010/07/27/introducing-asp-net-mvc-3-preview-1.aspx. Even Scott Guthrie does it and I'm sure he's not the kind of developer who would just follow what comes out of the box for lack of understanding. :) A simple controller method that ONLY returns a view, yet the return type is ActionResult... – Scott Jan 06 '11 at 16:30