How to create a parameterized Java method?

Asked

Viewed 115 times

-1

This is a Java method that is very coupled, and I need to decouple this method because there is a lot of code inside it, the block of code that I need to get inside the method uploadfile() is marked where I started with the annotation

// 1st starts from here the code

And the end of the block is marked with

// 2º ends here the code

What I need to do is take this block of code and turn it into a boolean return method and put it into the method uploadfile()

I am having difficulty to assemble this method because of the lack of experience with object orientation, only making it clear that the method uploadfile() is working perfectly, what I need is just to take this block of code and turn it into a boolean method.

That is the method;

public String uploadArquivo() {

        try {

            removeInSession(LISTA_TIPO_INDICIOS);
            removeInSession(LISTA_INDICIOS);
            removeInSession(LISTA_ERRO);

            final File arquivoLeitura = new File(getArquivo());

            final LineNumberReader linhaLeitura = new LineNumberReader(new FileReader(arquivoLeitura));
            linhaLeitura.skip(arquivoLeitura.length());
            final int qtdLinha = linhaLeitura.getLineNumber() + 1;

            final BufferedReader leitor = new BufferedReader(new InputStreamReader(new FileInputStream(getArquivo())));

            String linha = null;

            leitor.readLine();

            for (int indiceIndicio = 2; indiceIndicio <= qtdLinha; indiceIndicio++) {
                statusMatricula = false;
                linha = leitor.readLine();

                if (linha == null) {
                    break;
                }

                final String[] dadosCSV = linha.split(VIRGULA);
                final int numberPositions = dadosCSV.length;

                // 1º começa daqui o código

                setNumberPositions(numberPositions);
                if (!dadosCSV[TIPO_DO_INDICIO].isEmpty()) {
                    tipoIndicio = new TipoIndicioEntity();
                    tipoIndicio.setCodigo(Integer.parseInt(dadosCSV[TIPO_DO_INDICIO]));
                    tipoIndicio = tipoDeIndicioService.getPorId(tipoIndicio.getCodigo());
                }
                if (!dadosCSV[CODIGO_UJ].isEmpty()) {
                    uJ = new PessoaJuridicaPublicaEntity();
                    uJ.setCodigo(Long.parseLong(dadosCSV[CODIGO_UJ]));
                    uJ = pessoaJuridicaPublicaService.pesquisarPorId(uJ);
                }
                final ValidaCPF validadorCPF = new ValidaCPF();

                final Pattern pattern = Pattern.compile("^-?\\d*\\,\\d{2}$");
                final Matcher matcher = pattern.matcher(dadosCSV[VALOR]);

                if (!dadosCSV[NATUREZA].isEmpty()) {

                    naturezaIndicio.setCodigo(Integer.parseInt(dadosCSV[NATUREZA]));
                    naturezaIndicio = naturezaIndicioService.getPorId(naturezaIndicio.getCodigo());
                }
                if (!dadosCSV[CODIGO_DO_VINCULO].isEmpty()) {
                    tipoVinculo = new TipoVinculoEntity();
                    tipoVinculo.setCodigo(Integer.parseInt(dadosCSV[CODIGO_DO_VINCULO]));
                    tipoVinculo = tipoVinculoService.getPorId(tipoVinculo.getCodigo());
                }

                if (getNumberPositions() >= MATRICULA_PROPRIETARIO) {
                    if (!dadosCSV[MATRICULA_PROPRIETARIO].isEmpty()) {
                        usuarioCorporativo = new UsuarioCorporativoEntity();
                        usuarioCorporativo.setCodigoUsuario(Integer.parseInt(dadosCSV[MATRICULA_PROPRIETARIO]));
                        usuarioCorporativo = usuarioCorporativoService.getPorId(usuarioCorporativo.getCodigoUsuario());
                    }
                }

                final boolean expressaoInvalida = matcher.find() == false;
                final boolean cpfInvalido = !validadorCPF.isCPF(dadosCSV[CPF]);
                final boolean descricaoVazia = dadosCSV[DESCRICAO].isEmpty();
                final boolean naturezaInvalida = naturezaIndicio == null;
                boolean dataValidaEncontrada = false;

                if (!dadosCSV[DATA_ADMISSAO].equals("")) {

                    final SimpleDateFormat format = new SimpleDateFormat("dd/MM/yyyy");

                    format.setLenient(false);
                    try {

                        if (dadosCSV[DATA_ADMISSAO] != null && !dadosCSV[DATA_ADMISSAO].isEmpty()) {
                            final Date dataAdmissao = format.parse(dadosCSV[DATA_ADMISSAO]);
                        }

                    } catch (final Exception e) {
                        dataValidaEncontrada = true;
                    }

                }
                final int qtdData = dadosCSV[DATA_ADMISSAO].length();
                if (qtdData != 10) {
                    dataValidaEncontrada = true;
                }
                qtdMatriculo = dadosCSV[MATRICULA_PROPRIETARIO].length();

                final char letra_anterior = dadosCSV[MATRICULA_PROPRIETARIO].charAt(0);
                final int vezes = 1;
                int qtdCaracterMatriculaProprietario = 0;
                for (qtdCaracterMatriculaProprietario = 1; qtdCaracterMatriculaProprietario < qtdMatriculo; qtdCaracterMatriculaProprietario++) {
                    final char letra_atual = dadosCSV[MATRICULA_PROPRIETARIO].charAt(qtdCaracterMatriculaProprietario);

                }

                if (qtdCaracterMatriculaProprietario != 4) {
                    statusMatricula = true;
                }

                // 2º termina aqui o código

                if (getNumberPositions() <= 6) {
                    if (tipoIndicio == null || dadosCSV[TIPO_DO_INDICIO].isEmpty() || uJ == null
                            || dadosCSV[CODIGO_UJ].isEmpty() || cpfInvalido || descricaoVazia || expressaoInvalida
                            || naturezaIndicio == null) {
                        erroCSVList = ErroCSV.verificarErros6Linhas(dadosCSV, tipoIndicio, uJ, naturezaIndicio,
                                expressaoInvalida, validadorCPF, erroCSVList, indiceIndicio);
                        addInSession(LISTA_ERRO, erroCSVList);

                    } else {
                        verificarListaIndicios(listaTotalIndicio, listaIndicioEntity, uJ, tipoIndicio, dadosCSV);
                    }
                } else if (getNumberPositions() > 6 && getNumberPositions() < 13) {
                    if (tipoIndicio == null || dadosCSV[TIPO_DO_INDICIO].isEmpty() || uJ == null
                            || dadosCSV[CODIGO_UJ].isEmpty() || cpfInvalido || dadosCSV[DESCRICAO].isEmpty()
                            || dadosCSV[DESCRICAO] == null || expressaoInvalida || descricaoVazia
                            || naturezaIndicio == null || tipoVinculo == null || usuarioCorporativo == null
                            || statusMatricula) {

                        erroCSVList = ErroCSV.verificarErros12Linhas(dadosCSV, tipoIndicio, uJ, naturezaIndicio,
                                expressaoInvalida, validadorCPF, erroCSVList, indiceIndicio, dataValidaEncontrada,
                                tipoVinculo, usuarioCorporativo);
                        addInSession(LISTA_ERRO, erroCSVList);

                    } else {
                        verificarListaIndicios(listaTotalIndicio, listaIndicioEntity, uJ, tipoIndicio, dadosCSV);
                    }
                } else if (getNumberPositions() >= 13) {

                    if (tipoIndicio == null || dadosCSV[TIPO_DO_INDICIO].isEmpty() || uJ == null
                            || dadosCSV[CODIGO_UJ].isEmpty() || cpfInvalido || dadosCSV[DESCRICAO].isEmpty()
                            || dadosCSV[DESCRICAO] == null || descricaoVazia || expressaoInvalida
                            || naturezaIndicio == null || dadosCSV[NATUREZA].isEmpty() || dataValidaEncontrada
                            || tipoVinculo == null || usuarioCorporativo == null || statusMatricula) {

                        erroCSVList = ErroCSV.verificarErros12Linhas(dadosCSV, tipoIndicio, uJ, naturezaIndicio,
                                expressaoInvalida, validadorCPF, erroCSVList, indiceIndicio, dataValidaEncontrada,
                                tipoVinculo, usuarioCorporativo);

                        addInSession(LISTA_ERRO, erroCSVList);

                    } else {
                        verificarListaIndicios(listaTotalIndicio, listaIndicioEntity, uJ, tipoIndicio, dadosCSV);

                    }

                }

            }

            leitor.close();

        } catch (

        final FileNotFoundException e) {
            logger.error(e);
            erroInterno();
            e.printStackTrace();
        } catch (final IOException e) {
            logger.error(e);
            erroInterno();
            e.printStackTrace();
        } catch (final NegocioException e) {
            logger.error(e);
            erroInterno();
            e.printStackTrace();
        } catch (final PrincipalException e) {
            logger.error(e);
            erroInterno();
            e.printStackTrace();
        }

        return PAGE_IMPORTAR;
    }

And the code block I need turns into a boolean method is this;

// 1º começa daqui o código

                setNumberPositions(numberPositions);
                if (!dadosCSV[TIPO_DO_INDICIO].isEmpty()) {
                    tipoIndicio = new TipoIndicioEntity();
                    tipoIndicio.setCodigo(Integer.parseInt(dadosCSV[TIPO_DO_INDICIO]));
                    tipoIndicio = tipoDeIndicioService.getPorId(tipoIndicio.getCodigo());
                }
                if (!dadosCSV[CODIGO_UJ].isEmpty()) {
                    uJ = new PessoaJuridicaPublicaEntity();
                    uJ.setCodigo(Long.parseLong(dadosCSV[CODIGO_UJ]));
                    uJ = pessoaJuridicaPublicaService.pesquisarPorId(uJ);
                }
                final ValidaCPF validadorCPF = new ValidaCPF();

                final Pattern pattern = Pattern.compile("^-?\\d*\\,\\d{2}$");
                final Matcher matcher = pattern.matcher(dadosCSV[VALOR]);

                if (!dadosCSV[NATUREZA].isEmpty()) {

                    naturezaIndicio.setCodigo(Integer.parseInt(dadosCSV[NATUREZA]));
                    naturezaIndicio = naturezaIndicioService.getPorId(naturezaIndicio.getCodigo());
                }
                if (!dadosCSV[CODIGO_DO_VINCULO].isEmpty()) {
                    tipoVinculo = new TipoVinculoEntity();
                    tipoVinculo.setCodigo(Integer.parseInt(dadosCSV[CODIGO_DO_VINCULO]));
                    tipoVinculo = tipoVinculoService.getPorId(tipoVinculo.getCodigo());
                }

                if (getNumberPositions() >= MATRICULA_PROPRIETARIO) {
                    if (!dadosCSV[MATRICULA_PROPRIETARIO].isEmpty()) {
                        usuarioCorporativo = new UsuarioCorporativoEntity();
                        usuarioCorporativo.setCodigoUsuario(Integer.parseInt(dadosCSV[MATRICULA_PROPRIETARIO]));
                        usuarioCorporativo = usuarioCorporativoService.getPorId(usuarioCorporativo.getCodigoUsuario());
                    }
                }

                final boolean expressaoInvalida = matcher.find() == false;
                final boolean cpfInvalido = !validadorCPF.isCPF(dadosCSV[CPF]);
                final boolean descricaoVazia = dadosCSV[DESCRICAO].isEmpty();
                final boolean naturezaInvalida = naturezaIndicio == null;
                boolean dataValidaEncontrada = false;

                if (!dadosCSV[DATA_ADMISSAO].equals("")) {

                    final SimpleDateFormat format = new SimpleDateFormat("dd/MM/yyyy");

                    format.setLenient(false);
                    try {

                        if (dadosCSV[DATA_ADMISSAO] != null && !dadosCSV[DATA_ADMISSAO].isEmpty()) {
                            final Date dataAdmissao = format.parse(dadosCSV[DATA_ADMISSAO]);
                        }

                    } catch (final Exception e) {
                        dataValidaEncontrada = true;
                    }

                }
                final int qtdData = dadosCSV[DATA_ADMISSAO].length();
                if (qtdData != 10) {
                    dataValidaEncontrada = true;
                }
                qtdMatriculo = dadosCSV[MATRICULA_PROPRIETARIO].length();

                final char letra_anterior = dadosCSV[MATRICULA_PROPRIETARIO].charAt(0);
                final int vezes = 1;
                int qtdCaracterMatriculaProprietario = 0;
                for (qtdCaracterMatriculaProprietario = 1; qtdCaracterMatriculaProprietario < qtdMatriculo; qtdCaracterMatriculaProprietario++) {
                    final char letra_atual = dadosCSV[MATRICULA_PROPRIETARIO].charAt(qtdCaracterMatriculaProprietario);

                }

                if (qtdCaracterMatriculaProprietario != 4) {
                    statusMatricula = true;
                }

                // 2º termina aqui o código
  • Why, instead of doing this if stack with CSV data, you don’t already parse the data with what you need in an object that represents that data?

  • @Felipeavelar, first I want to thank you for trying to help me, I could do yes that way, and I would bump into the same difficulty I’m having right now that would be lack of experience, if you can do this for me and put your code suggestion based on the code I posted, I will be very grateful, I need to uncouple this method to make it easier for me to create a unit tests on top of the method uploadfile, because that’s what I want to decouple it.

  • Which IDE do you use? Eclipse and Intellij provide tools to extract blocks of code for methods, already identifying required parameters.

  • I am using Eclipse Java EE IDE for Web Developers. Version: 2018-09 (4.9.0) Build id: 20180917-1800 OS: Windows 10, v.10.0, x86_64 / Win32 Java version: 1.8.0_211

  • @Leonardolima could explain to me how I could use this tool to create the method?

  • @wladyband in the eclipse documentation has an example: http://help.eclipse.org/oxygen/topic/org.eclipse.jdt.doc.user/gettingStarted/qs-ExtractMethod.htm?cp=1_1_0_3_8

  • did not work because it gave this error message: Ambiguous Return value: Selected block containsmore than one assignment to local variables.

Show 2 more comments

1 answer

0

Solution

public Boolean verificadorFluxoCSV(String[] dadosCSV) {

        if (!dadosCSV[TIPO_DO_INDICIO].isEmpty()) {
            tipoIndicio = new TipoIndicioEntity();
            tipoIndicio.setCodigo(Integer.parseInt(dadosCSV[TIPO_DO_INDICIO]));
            tipoIndicio = tipoDeIndicioService.getPorId(tipoIndicio.getCodigo());
        }
        if (!dadosCSV[CODIGO_UJ].isEmpty()) {
            uJ = new PessoaJuridicaPublicaEntity();
            uJ.setCodigo(Long.parseLong(dadosCSV[CODIGO_UJ]));
            try {
                uJ = pessoaJuridicaPublicaService.pesquisarPorId(uJ);
            } catch (NegocioException e) {
                // TODO Auto-generated catch block
                e.printStackTrace();
            } catch (PrincipalException e) {
                // TODO Auto-generated catch block
                e.printStackTrace();
            }
        }

        final Pattern pattern = Pattern.compile("^-?\\d*\\,\\d{2}$");
        final Matcher matcher = pattern.matcher(dadosCSV[VALOR]);

        if (!dadosCSV[NATUREZA].isEmpty()) {

            naturezaIndicio.setCodigo(Integer.parseInt(dadosCSV[NATUREZA]));
            naturezaIndicio = naturezaIndicioService.getPorId(naturezaIndicio.getCodigo());
        }
        if (!dadosCSV[CODIGO_DO_VINCULO].isEmpty()) {
            tipoVinculo = new TipoVinculoEntity();
            tipoVinculo.setCodigo(Integer.parseInt(dadosCSV[CODIGO_DO_VINCULO]));
            tipoVinculo = tipoVinculoService.getPorId(tipoVinculo.getCodigo());
        }

        if (getNumberPositions() >= MATRICULA_PROPRIETARIO) {
            if (!dadosCSV[MATRICULA_PROPRIETARIO].isEmpty()) {
                usuarioCorporativo = new UsuarioCorporativoEntity();
                usuarioCorporativo.setCodigoUsuario(Integer.parseInt(dadosCSV[MATRICULA_PROPRIETARIO]));
                usuarioCorporativo = usuarioCorporativoService.getPorId(usuarioCorporativo.getCodigoUsuario());
            }
        }

        expressaoInvalida = matcher.find() == false;
        final boolean cpfInvalido = !validadorCPF.isCPF(dadosCSV[CPF]);
        final boolean descricaoVazia = dadosCSV[DESCRICAO].isEmpty();
        final boolean naturezaInvalida = naturezaIndicio == null;

        if (!dadosCSV[DATA_ADMISSAO].equals("")) {

            final SimpleDateFormat format = new SimpleDateFormat("dd/MM/yyyy");

            format.setLenient(false);
            try {

                if (dadosCSV[DATA_ADMISSAO] != null && !dadosCSV[DATA_ADMISSAO].isEmpty()) {
                    final Date dataAdmissao = format.parse(dadosCSV[DATA_ADMISSAO]);
                }

            } catch (final Exception e) {
                dataValidaEncontrada = true;
            }

        }
        final int qtdData = dadosCSV[DATA_ADMISSAO].length();
        if (qtdData != 10) {
            dataValidaEncontrada = true;
        }
        qtdMatriculo = dadosCSV[MATRICULA_PROPRIETARIO].length();

        final char letra_anterior = dadosCSV[MATRICULA_PROPRIETARIO].charAt(0);
        final int vezes = 1;
        int qtdCaracterMatriculaProprietario = 0;
        for (qtdCaracterMatriculaProprietario = 1; qtdCaracterMatriculaProprietario < qtdMatriculo; qtdCaracterMatriculaProprietario++) {
            final char letra_atual = dadosCSV[MATRICULA_PROPRIETARIO].charAt(qtdCaracterMatriculaProprietario);

        }

        if (qtdCaracterMatriculaProprietario != 4) {
            statusMatricula = true;
        }

        if (tipoIndicio == null || dadosCSV[TIPO_DO_INDICIO].isEmpty() || uJ == null || dadosCSV[CODIGO_UJ].isEmpty()
                || cpfInvalido || dadosCSV[DESCRICAO].isEmpty() || dadosCSV[DESCRICAO] == null || descricaoVazia
                || expressaoInvalida || naturezaIndicio == null || dadosCSV[NATUREZA].isEmpty() || dataValidaEncontrada
                || tipoVinculo == null || usuarioCorporativo == null || statusMatricula) {
            return true;
        } else {
            return false;
        }

    }

Browser other questions tagged

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