3
\$\begingroup\$

Given this piece of code, what is a better way to write it (cleaner). It is taken for granted that data will not be null, nor its length will be 0, so this check is skipped.

private byte[] process(byte[] bytes) {
    int from = 0;
    if (bytes[0] == '\n') {
        from = 1;
    } else if (bytes[0] == '\r' && bytes[1] == '\n') {
        from = 2;
    }
    return Arrays.copyOfRange(bytes, from, bytes.length);
}

I thought about converting it to String, then applying a regex (^[\r\n]), but that means some encoding has to be used for the conversion and then I would have to convert it back to byte[], which does not comply with my needs. Is there any clearer way to write this?

\$\endgroup\$
  • 1
    \$\begingroup\$ To whoever down-voted and close-voted this question, I don't see how the author is asking for help fixing broken code. \$\endgroup\$ – Greg Burghardt Jul 6 '18 at 11:03
2
\$\begingroup\$

I don't think you can make this specifically better.

What you could do is make the function more generic, but that depends on what your data contains beyond the first two bytes. For example, you could simply skip any and all line feeds and carriage returns at the beginning:

private int skipLFandCR(byte[] bytes) {
    int pos = 0;
    while (pos < bytes.length && (bytes[pos] == '\r' || bytes[pos] == '\n')) {
        pos++;
    }
    return pos;
}

Also: Do you need a copy of the data? I'd just use a function that returns the start index such as mine and process the existing array starting at that index.

\$\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.