Refactoring toward frictionless & odorless code: The baseline
Join the DZone community and get the full member experience.
Join For FreeThis 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.
Baseline (budgeting)
Published at DZone with permission of Oren Eini, DZone MVB. See the original article here.
Opinions expressed by DZone contributors are their own.
Trending
-
Structured Logging
-
MLOps: Definition, Importance, and Implementation
-
What Is mTLS? How To Implement It With Istio
-
Seven Steps To Deploy Kedro Pipelines on Amazon EMR
Comments