How to improve code

Asked

Viewed 33 times

0

I have the following method:

public async Task<ActionResult> AlterarRequerimentoAsync(RequerimentoViewModel model)
        {
            if (ModelState.IsValid)
            {

                var projeto = await this.ProjetoApplicationService.ObterProjetoAsync(model.IdProjeto);
                var plantio = await this.PlantioApplicationService.ObterPlantioPeloIdProjetoAsync(model.IdProjeto);
                if (plantio.Count == 0)
                {
                    ModelState.AddModelError("PlantioNaoInformado", Mensagens.PlantioNaoInformado);
                    return PartialView("_Alterar", model);
                }
                var talhao = await this.TalhaoApplicationService.ListarTalhaoPorIdProjetoAsync(model.IdProjeto);
                if (talhao.Count == 0)
                {
                    ModelState.AddModelError("TalhaoNaoInformado", Mensagens.TalhaoNaoInformado);
                    return PartialView("_Alterar", model);
                }
                var detentor = await this.DetentorApplicationService.ListarDetentoresPorIdProjetoAsync(model.IdProjeto);
                if (detentor.Count == 0)
                {
                    ModelState.AddModelError("DetentorNaoInformado", Mensagens.DetentorNaoInformado);
                    return PartialView("_Alterar", model);
                }
                var imovelRural = await this.ImovelRuralApplicationService.ObterImovelRuralPeloIdProjetoAsync(model.IdProjeto);
                if (imovelRural == null)
                {
                    ModelState.AddModelError("ImovelRuralNaoInformado", Mensagens.ImovelRuralNaoInformado);
                    return PartialView("_Alterar", model);
                }
                var inventario = await this.InventarioApplicationService.ObterInventarioPorIdProjetoAsync(model.IdProjeto);
                if (inventario == null)
                {
                    ModelState.AddModelError("InventarioNaoInformado", Mensagens.InventarioNaoInformado);
                    return PartialView("_Alterar", model);
                }
                var prioridade = await this.PrioridadeApplicationService.ObterPrioridadePorIdProjetoAsync(model.IdProjeto);
                if (prioridade == null)
                {
                    ModelState.AddModelError("PrioridadeNaoInformada", Mensagens.PrioridadeNaoInformada);
                    return PartialView("_Alterar", model);
                }
                var processamentoGeo = await this.ProcessamentoGeoApplicationService.ObterProcessamentoGeoPorProjetoIdAsync(model.IdProjeto);
                if (processamentoGeo == null)
                {
                    ModelState.AddModelError("ProcessamentoGeoNaoInformado", Mensagens.ProcessamentoGeoNaoInformado);
                    return PartialView("_Alterar", model);
                }
                var procurador = await this.ProcuradorApplicationService.ListarProcuradoresPorIdProjetoAsync(model.IdProjeto);
                if (procurador.Count == 0)
                {
                    ModelState.AddModelError("ProcuradorNaoInformado", Mensagens.ProcuradorNaoInformado);
                    return PartialView("_Alterar", model);
                }
                var representanteLegal = await this.RepresentanteLegalApplicationService.ObterRepresentanteLegalPorIdProjetoAsync(model.IdProjeto);
                if (representanteLegal == null)
                {
                    ModelState.AddModelError("RepresentanteLegalNaoInformado", Mensagens.RepresentanteLegalNaoInformado);
                    return PartialView("_Alterar", model);
                }
                var responsavelTecnico = await this.ResponsavelTecnicoApplicationService.ListarResponsaveisTecnicosPorIdProjetoAsync(model.IdProjeto);
                if (responsavelTecnico.Count == 0)
                {
                    ModelState.AddModelError("ResponsavelTecnicoNaoInformado", Mensagens.ResponsavelTecnicoNaoInformado);
                    return PartialView("_Alterar", model);
                }
                var taxaDar = await this.TaxaDarApplicationService.ObterTaxaDarPorIdProjetoAsync(model.IdProjeto);
                if (taxaDar == null)
                {
                    ModelState.AddModelError("TaxaDarNaoInformada", Mensagens.TaxaDaroNaoInformada);
                    return PartialView("_Alterar", model);
                }
                byte[] fileBytes = new byte[] { };
                if (model.Arquivos.First().TempId.HasValue)
                {
                    var metadata = await this.FileServer.ReadFileAsync(model.Arquivos.First().TempId.Value);
                    if (metadata != null)
                    {
                        fileBytes = await this.FileServer.ReadFileContentAsync(model.Arquivos.First().TempId.Value);
                    }
                    else
                    {
                        var file = await this.ArquivoApplicationService.ObterArquivoPorIdAsync(Convert.ToInt32(model.Arquivos.First().Id));
                        fileBytes = file.Conteudo;
                    }
                }
                else if (!string.IsNullOrEmpty(model.Arquivos.First().Id))
                {
                    var file = await this.ArquivoApplicationService.ObterArquivoPorIdAsync(Convert.ToInt32(model.Arquivos.First().Id));
                    fileBytes = file.Conteudo;
                }

                ArquivoData arquivo = model.Arquivos?.Select(x => new ArquivoData
                {
                    Conteudo = fileBytes,
                    Nome = x.FileName,
                    TipoConteudo = x.ContentType
                }).First();

                await this.RequerimentoApplicationService.IncluirAlterarRequerimentoAsync(arquivo, model.IdProjeto);

                this.SuccessMessage = "O Projeto de número: "
                    + projeto.NumeroProjeto
                    + " foi finalizado com sucesso.";
                return Json(new { redirect = Url.Action("Index", "Projeto", new { Area = "Projeto" }) });
            }
            return PartialView("_Alterar", model);
        }

How can I improve it the validation part, as you can see I put several return PartialView("_Alterar", model); which is for when enter if return to msg error and remain on the current screen.

Note: The Modelstate is valid, so enter if Isvalid...

1 answer

0

Instead of using several return, you could involve the function in a try-catch and then make a throw with some error message maybe to finish processing. The advantage of this is that if in the future you desire this behavior of how you interrupt the process, you would do it in one place, in the catch instead of having to modify all these return.

I also advise you to try to separate the task into multiple parts to become more organized and readable. You could initially do the "Not informed" checks in a separate method, then another method that returns the value of fileBytes.

Browser other questions tagged

You are not signed in. Login or sign up in order to post.