swch
swch

Reputation: 1546

Difference between #strings and standard String methods

What is the difference between:

${obj.title.replaceAll(' ', '-')

and thymeleaf specific:

${#strings.replace(obj.title, ' ', '-')}

I know that in first example I use standard String method and in second one I use the Strings class from Thymeleaf. Which one is preferred and why? Is there any specific case when methods from String class cannot be used and they should be replaced with Strings equivalent?

Upvotes: 2

Views: 254

Answers (1)

wi2ard
wi2ard

Reputation: 1555

Here are a few differences:

  • strings.replace first param doesn't need to be string and can be null
  • strings.replace second param, the one you're searching for, is not a regex while the sdk String#replaceAll will work with regex

You can find cases when the Thymeleaf seems preferable, for eg. when you don't want to dirty the code with null checks or toString calls. That being said I would always use the SDK API because

  • it is much better known and documented so easier for new devs to understand
  • the Java api will always be updated in a backward compatible way; Tymeleaf api can change implementation details in the future and because the comunity is much much smaller you have no certainty they will focus on backward compatibility. Anyone that ever had to upgrade third party libraries in a project knows what I'm talking about. What if someday they decide to reimplement the replace method by using regex then you'll have to change your code to escape the regex special chars.

Upvotes: 2

Related Questions