mardi 3 mars 2015

Avoid code replication

In my code I have many functions with this signature (params + return type), and they all use this same try-ctach clause.



public ActionResult methodName(int id)
{
try
{
//Some specific code here
return new HttpStatusCodeResult(HttpStatusCode.OK);
}
catch (Exception ex)
{
return new HttpStatusCodeResult(HttpStatusCode.InternalServerError, ex.Message);
}
}


Now, This is replicated over and over again, and I know that replication is bad. The reason this happens, is because I want the code to be able to return multiple HttpStatusCodeResult but I don't know a better way of doing it.


In this example, I return an internal server error and an OK answer. But what if I want to return another type of error ?



public ActionResult methodName(int id)
{
try
{
//Some specific code here
if(conditionA)
return return new HttpStatusCodeResult(HttpStatusCode.NotFound, "No Hamsters found!")
return new HttpStatusCodeResult(HttpStatusCode.OK);
}
catch (Exception ex)
{
return new HttpStatusCodeResult(HttpStatusCode.InternalServerError, ex.Message);
}
}


Is there a modular way of having behavior, without replication, inside my code? Is there a design or architectural pattern I can use? If so, which one?


Aucun commentaire:

Enregistrer un commentaire