2
\$\begingroup\$

I'd like to refactor a Java method I've created, making it cleaner and more beautiful. The method concatenates some strings, which may be empty or not. I'm new on java so i'm not sure how to do that, especially because between the strings I may have separators.

Here is my method:

private String createString(String modeloVotacao, String tipoProposicao, String ordemNumero, String ordemAno) {       

    String modeloDescricao = "";
    if(modeloVotacao != null) {
        modeloDescricao = modeloVotacao + " - ";
    }

    if(tipoProposicao != null) {
        modeloDescricao += tipoProposicao + " ";
    }
    modeloDescricao += ordemNumero != null?ordemNumero:"";

    if(ordemNumero != null && ordemAno != null) {
        modeloDescricao += "/"+ordemAno;
    } else {
        if(ordemAno != null) {
            modeloDescricao += ordemAno;
        }
    }

    return modeloDescricao;
}

Here is some results that this method returns:

  • All filled: 1ª DISCUSSÃO - PROJETO DE LEI COMPLEMENTAR Nº 16/2018
  • modeloVotacao = null: PROJETO DE LEI COMPLEMENTAR Nº 16/2018
  • tipoProposicao = null: 1ª DISCUSSÃO - Nº 16/2018
  • ordemNumero = null: 1ª DISCUSSÃO - PROJETO DE LEI COMPLEMENTAR 2018
  • ordemAno = null: 1ª DISCUSSÃO - PROJETO DE LEI COMPLEMENTAR Nº 16
  • all null: empty string
  • modeloVotacao and tipoProposicao = null: Nº 16/2018
  • ordemNumero and ordemAno = null: 1ª DISCUSSÃO - PROJETO DE LEI COMPLEMENTAR
| improve this question | | | | |
\$\endgroup\$
  • 1
    \$\begingroup\$ Would help a lot if the variable names were in English. \$\endgroup\$ – slowy Jan 26 '18 at 17:17
1
\$\begingroup\$

The repeated task here is that you want to conditionally insert a separator between two strings if both are non-null. So, write a helper function that does that:

private static String join(String a, String sep, String b) {
    return (a == null) ? b :
           (b == null) ? a : a + sep + b;
}

Then, the code becomes simple:

private String createString(String modeloVotacao, String tipoProposicao, String ordemNumero, String ordemAno) {       
    String description = join(modeloVotacao, " - ",
                             join(tipoProposicao, " ",
                                 join(ordemNumero, "/", ordemAno)));
    return (description == null) ? "" : description;
}

Note that in your final example, where ordemNumero and ordemAno are both null, the output ends with a space. That does not happen in my solution; I consider that to be an improvement.

Please avoid mixing Portuguese with English identifiers (such as createString()). Stick with one or the other (preferably English).

| improve this answer | | | | |
\$\endgroup\$

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

Not the answer you're looking for? Browse other questions tagged or ask your own question.