Over a million developers have joined DZone.
{{announcement.body}}
{{announcement.title}}

Refactoring toward frictionless & odorless code: The baseline

DZone's Guide to

Refactoring toward frictionless & odorless code: The baseline

· ·
Free Resource
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

Opinions expressed by DZone contributors are their own.

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

{{ parent.tldr }}

{{ parent.urlSource.name }}