I had this code repeated in many Actions:
public ActionResult History(int? patientId)
{
if (patientId == null)
{
return new HttpStatusCodeResult(HttpStatusCode.BadRequest);
}
var patient = patientService.GetPatient(patientId.Value);
if (patient == null)
{
return HttpNotFound();
}
...
}
So I extracted a method to:
private ActionResult CheckPatientId(int? patientId, ref Patient patient)
{
if (patientId == null)
{
return new HttpStatusCodeResult(HttpStatusCode.BadRequest);
}
patient = patientService.GetPatient(patientId.Value);
if (patient == null || patient.PharmacyId != User.PharmacyId())
{
return HttpNotFound();
}
return null;
}
Which I call like so:
var patient = new Patient();
if (CheckPatientId(patientId, ref patient) != null)
{
return CheckPatientId(patientId, ref patient);
}
I don't like that I have to call CheckPatient twice if it fails and the returning of null - is there a better way to do this or is it ok?