Thursday, May 31, 2018

How to optimize if condition in groovy

Main Code:
        if (text != null) {
            return text.toString().replaceAll("<[Bb][Rr]>", "\n")
        } else {
            return text
        }
Optimization#1:
return text?text.toString().replaceAll("<[Bb][Rr]>", "\n"):text
Optimization#2:
return text?toString().replaceAll("<[Bb][Rr]>", "\n")
It will give null pointer exception. because text?.toString() also gives null. But it is not checked. So do it like below:

return text?toString()?.replaceAll("<[Bb][Rr]>", "\n")
Test Case:
@Unroll
    def "#caseNo : check replaceBrTagToNewLine method"() {
        when:
        def result = itemScreenService.replaceBrTagToNewLine(text)

        then:
        assert result == expected

        where:
        caseNo | text               | expected
        1      | null               | null
        2      | ""                 | ""
        3      | "test"             | "test"
        4      | "
"             | "\n"
        5      | "test
line"     | "test\nline"
        6      | "test
line"     | "test\nline"
        7      | "test
line"     | "test\nline"
        8      | "test
line"     | "test\nline"
        9      | "



" | "\n\n\n\n"
    }

No comments:

Post a Comment