Search code examples
javastringgroovytrim

Groovy redundant trim() calls


I'm reading a Groovy script and I'm finding a lot of trim() calls and especially this kind of expression:

x = "ok".trim()

I'm wondering if trim() apart from the obvious trimming has also some other effect that would explain the above expression (it can also be just bad code).


Solution

  • The default definition of trim() remove space from start and end of the string. So, In your app if you are using default definition then "ok".trim() does not has any effect.

    But if you change the definition of trim() method then it is possible it will behave in a different way. Now String is a final class so you can't override it but Groovy gives you a feature called metaclass which allows you to change the definition at runtime.

    Run the below code on the groovy console.

    String.metaClass.trim = {
     //you could have your own trim implementation here for String class
     return "Hi"
    }
    x = "ok".trim()
    println x  
    

    Output:

    Hi
    

    So, my conclusion is as soon as you are not changing the definition of trim() your code does not has any effect.