Consider the following code segment written by a coworker of mine:
public ActionResult Index()
{
DataRetrieveModel dataRetrieveModel = new DataRetrieveModel();
using (spc_web_trunkEntities db = new spc_web_trunkEntities())
{
DataRetrieveDAL dataRetrieveDAL = new DataRetrieveDAL(db);
dataRetrieveModel.CustomerList = dataRetrieveDAL.GetCustomerList();
dataRetrieveModel.LineList = dataRetrieveDAL.GetLineList();
if (dataRetrieveModel.LineList.Count > 0)
{
dataRetrieveModel.ModelList = dataRetrieveDAL.GetModelList(dataRetrieveModel.LineList[0].Value);
}
if (dataRetrieveModel.LineList.Count > 0 &&
dataRetrieveModel.ModelList.Count > 0)
{
dataRetrieveModel.LotList = dataRetrieveDAL.GetLotList(dataRetrieveModel.LineList[0].Value, dataRetrieveModel.ModelList[0].Value);
}
if (dataRetrieveModel.LineList.Count > 0 &&
dataRetrieveModel.ModelList.Count > 0)
{
dataRetrieveModel.EquipmentList = dataRetrieveDAL.GetEquipmentList(dataRetrieveModel.LineList[0].Value, dataRetrieveModel.ModelList[0].Value);
}
}
return View(dataRetrieveModel);
}
It's a very simple controller that returns a model.
My question is given this code, how would you go about cleaning/refactoring it?
Here's my approach. First, I identified a lot of short circuiting points along with empty spaces, so I went ahead and cleaned those up first:
public ActionResult Index()
{
DataRetrieveModel dataRetrieveModel = new DataRetrieveModel();
using (spc_web_trunkEntities db = new spc_web_trunkEntities())
{
DataRetrieveDAL dataRetrieveDAL = new DataRetrieveDAL(db);
dataRetrieveModel.CustomerList = dataRetrieveDAL.GetCustomerList();
dataRetrieveModel.LineList = dataRetrieveDAL.GetLineList();
if (!dataRetrieveModel.LineList.Any())
return View(dataRetrieveModel);
dataRetrieveModel.ModelList = dataRetrieveDAL.GetModelList(dataRetrieveModel.LineList[0].Value);
if (!dataRetrieveModel.ModelList.Any())
return View(dataRetrieveModel);
dataRetrieveModel.LotList = dataRetrieveDAL.GetLotList(dataRetrieveModel.LineList[0].Value, dataRetrieveModel.ModelList[0].Value);
dataRetrieveModel.EquipmentList = dataRetrieveDAL.GetEquipmentList(dataRetrieveModel.LineList[0].Value, dataRetrieveModel.ModelList[0].Value);
}
return View(dataRetrieveModel);
}
I'm also wondering why multiple queries have to be made to initialize dataRetrieveModel, but for now, I only want to focus on this method.
But then all those return View(dataRetrieveModel) seems too verbose, so I thought about defining a return label and using a goto. I'm not sure how others feel about it.
I'd like to hear any suggestions on this matter.