Sunday, November 25, 2012

ASP.NET MVC returned type discipline

A few times I'm seeing this in code...


public ActionResult GetSoap()
{
    return Json(new Soap { Name = "Tide", Feature = "With Calamansi" } );
}



...instead of the following one in which you can easily infer the code's intent:

public JsonResult GetSoap()
{
    return Json(new Soap { Name = "Tide", Feature = "With Calamansi" } );
}


That's deliberately leaking an abstraction. A devil's advocate would suppose you are just showing off your deep knowledge on ASP.NET MVC's object hierarchy, that you know that JsonResult derives from ActionResult, thus you can just make every MVC actions' return type an ActionResult. Well guess what, everything derives from object anyway, hence just make everything return an object and it will still compile and run:


public object GetSoap()
{
    return Json(new Soap { Name = "Tide", Feature = "With Calamansi" } );
}


The problem with that approach(and the ActionResult code above for that matter) is you need to cast the returned results to its actual returned type(JsonResult) when you need to do TDD on that method. Hence warranting an explicit casting.


[Test]
public void SomeTest()
{
    // unnecessary casting
    JsonResult r = (JsonResult) GetSoap(); 
    
    Soap s = (Soap)r.Model;    
}


Whereas if you declare the MVC method to return its actual returned type, i.e. JsonResult, you don't need to do extra casting when doing unit test on it:


[Test]
public void SomeTest()
{
    JsonResult r = GetSoap(); 
    
    Soap s = (Soap)r.Model;    
}


Giving the controller action's return type an specific type makes the code intent clearer

Happy Coding! ツ


No comments:

Post a Comment