3
I think my code is too polluted with a lot of if.
[ValidateModelAttribute]
[HttpPut("{id}")]
public IActionResult Put(int id, [FromBody]UserDto model)
{
try
{
if (model == null || model.Id != id)
return BadRequest();
var originalUser = context.User.AsNoTracking().FirstOrDefault(x => x.Id == id);
if (originalUser == null)
return NotFound();
var updatedUser = model.MapTo<User>();
var userBd = context.User.FirstOrDefault(x => x.Login == updatedUser.Login && x.Id != updatedUser.Id);
if (userBd != null)
return StatusCode((int)HttpStatusCode.Conflict, userBd);
context.Entry(originalUser).Context.Update(updatedUser);
context.SaveChanges();
return Ok(updatedUser);
}
catch (Exception ex)
{
return BadRequest(ex.Message);
}
}
Is there any more elegant way?
Except for the abuse of exception, but that to do right you will probably like less, I see no problems, what you see of problem.
– Maniero
I see a certain pollution in the code... Looking quickly I can’t tell what it’s doing. That’s not a problem?
– Diego Zanardo
Yeah, if you wrote it and don’t know what it does, it really can be. Separate it into several methods then. Give them good names. Read this: http://answall.com/q/100516/101
– Maniero
And the abuse of exception, has some question about it by aq?
– Diego Zanardo
Only I answered several: http://answall.com/search?tab=votes&q=user%3a101%20%5bexce%C3%A7%C3%a3o%5d. In this case you are capturing any problem that may occur in the code, and there may be many (one of the problems of the exception is precisely not having control over everything that can occur) and is turning into an exception that has a specific meaning. The two things are abuses.
– Maniero