Over a million developers have joined DZone.

Refactoring toward frictionless & odorless code: The baseline

·
This is part of an exercise that I give in my course. The context is an MVC3 ASP.Net application. Here is how we start things:

public class MvcApplication : System.Web.HttpApplication
{
private static readonly ISessionFactory sessionFactory = BuildSessionFactory();

public static ISession CurrentSession
{
get{ return HttpContext.Current.Items["NHibernateSession"] as ISession;}
set { HttpContext.Current.Items["NHibernateSession"] = value; }
}

public MvcApplication()
{
BeginRequest += (sender, args) =>
{
CurrentSession = sessionFactory.OpenSession();
};
EndRequest += (o, eventArgs) =>
{
var session = CurrentSession;
if (session != null)
{
session.Dispose();
}
};
}

protected void Application_Start()
{
AreaRegistration.RegisterAllAreas();

RegisterGlobalFilters(GlobalFilters.Filters);
RegisterRoutes(RouteTable.Routes);
}

private static ISessionFactory BuildSessionFactory()
{
return new Configuration()
.Configure()
.BuildSessionFactory();
}
}


And in the controller, we have something like this:

public class HomeController : SessionController
{
public ActionResult Blog(int id)
{
var blog = MvcApplication.CurrentSession.Get<Blog>(id);

return Json(blog, JsonRequestBehavior.AllowGet);
}
}


This code is valid, it works, it follows best practices and I actually recommend using something very similar here.

It also annoyed me when I wrote it now, enough to write a series of blog posts detailing how to fix this.

Topics:

Published at DZone with permission of Ayende Rahien, DZone MVB. See the original article here.

Opinions expressed by DZone contributors are their own.

The best of DZone straight to your inbox.

SEE AN EXAMPLE
Please provide a valid email address.

Thanks for subscribing!

Awesome! Check your inbox to verify your email so you can start receiving the latest in tech news and resources.
Subscribe

{{ parent.title || parent.header.title}}

{{ parent.tldr }}

{{ parent.urlSource.name }}