Do I need to restructure for readability?
public HttpResponseMessage Post([FromBody]BoatProperties props)
{
// model validation
if(ModelState.IsValid)
{
// check if guid is set, else set it; don't set when user is admin
if(props.Guid == null && !User.IsInRole("Admin"))
{
props.Guid = Membership.GetUser().ProviderUserKey as Guid?;
}
Boat boat = BoatProvider.GetBoat(props.Guid);
try
{
// can't find existing boat: create new boat
if (boat == null)
{
boat = new Boat(props);
BoatProvider.AddNew(boat);
}
// otherwise update existing boat
else
{
BoatProvider.Update(boat);
}
}
catch(Exception ex)
{
// error while updating/adding model
return Request.CreateErrorResponse(HttpStatusCode.InternalServerError, ex.Message);
}
// everything ok!
return Request.CreateResponse(HttpStatusCode.OK, BoatProvider.GetBoat(props.Guid));
}
// validation failed
return CreateResponse(HttpStatusCode.BadGateway);
}
As you can see I'm exiting all those conditions with a return
statement. If I restructure my code like this:
if(!ModelState.IsValid)
{
return CreateResponse(HttpStatusCode.BadGateway);
}
if (props.Guid == null && !User.IsInRole("Admin"))
{
props.Guid = guid;
}
I will have less indentations and it may be more readable and all the steps seem more distanced from each other.