Sonar - Method accesses list or array with constant index

Viewed 34

Java Code:

List<ParsedUsuarioDto> parsedUsuarioDtos = new ArrayList<>(linhas.size());
for (String[] linha : linhas) {
    parsedUsuarioDtos.add(ParsedUsuarioDto.builder()
            .posicao(linhas.indexOf(linha) + 1)
            .cpf(linha[0])
            .rg(linha[1])
            .nome(linha[2])
            .mae(linha[3])
            .celular(linha[4])
            .email(linha[5])
            .dataNascimento(linha[6])
            .build());
}

Sonar gives me this message:

This method accesses an array or list using a constant integer index. Often, this is a typo where a loop variable is intended to be used. If however, specific list indices mean different specific things, then perhaps replacing the list with a first-class object with meaningful accessors would make the code less brittle.

How can i fix this bug?

1 Answers

I don't think this is a bug (albeit a code smell). What SonarQube is suggesting instead of of having String[] linha have something like Linha linha which allows you to write linha.getNome() instead of linha[2]. A lot more readable and less likely to break when you start changing the order of elements in your array.

Also note that your loop has O(n²) complexity. It iterates the linhas array (O(n)), then for each element calls indexOf to find the position of the item (again O(n)). It's better to use an indexed for loop here (for (int i = 0; i < linhas.length; ++i)).

Your code would then become:

for (int i = 0; i < linhas.length; ++i) {
    final Linha linha : linhas[i];
    parsedUsuarioDtos.add(ParsedUsuarioDto.builder()
            .posicao(i + 1)
            .cpf(linha.getCpf())
            .rg(linha.getRg())
            .nome(linha.getNome())
            .mae(linha.getMae())
            .celular(linha.getCelular())
            .email(linha.getEmail())
            .dataNascimento(linha.getDataNascimento())
            .build());
}
Related