HiveBrain v1.2.0
Get Started
← Back to all entries
patternMinor

Code for adjusting linelength

Submitted by: @import:stackexchange-codereview··
0
Viewed 0 times
codeadjustingforlinelength

Problem

I wrote the following groovy function for taking a string of multiple lines (or any other character for splitting the code into parts), and bringing each line/part to a specified number of characters, cutting too long lines and filling up too short lines with a fill character:

static final String adjustLineLength(Integer length, String filler, String token, String source) {
    source
    .tokenize(token)
    .collect{ String line ->
        if(line.size() > length)
            line.substring(0, length)
        else if(line.size() < length)
            line + (filler * (length - line.size()))
        else
            line
    }
    .join(token)
}


Is that a good approach? Any suggestions how this code can be improved in concerns of making it more easy to understand and maybe (but that has not priority over beeing easy to understand) improving performance?

Solution

I think your approach is fine, and it's easy to understand. I have just a few improvement ideas:

  • A more natural ordering of the method parameters might be: source, token, length, filler



  • Instead of Integer, int should be enough and shorter



  • Move the closure in collect to its own method



  • Do you really need the static final String declaration? Why not use simply def?



  • Do you really need the type declarations in the signature? You could omit them, and it will be still quite clear



-
The brackets around the multiplication are unnecessary in

line + (filler * (length - line.size()))


Suggested implementation

Putting the above suggestions together:

def adjustLineLength = { line, length, filler ->
    if (line.size() > length) {
        line.substring(0, length)
    } else if (line.size() 
    source
    .tokenize(token)
    .collect { adjustLineLength(it, length, filler) }
    .join(token)
}

Code Snippets

line + (filler * (length - line.size()))
def adjustLineLength = { line, length, filler ->
    if (line.size() > length) {
        line.substring(0, length)
    } else if (line.size() < length) {
        line + filler * (length - line.size())
    } else {
        line
    }
}

def adjustTextLength = { source, token, length, filler ->
    source
    .tokenize(token)
    .collect { adjustLineLength(it, length, filler) }
    .join(token)
}

Context

StackExchange Code Review Q#49219, answer score: 3

Revisions (0)

No revisions yet.