Reputation: 12748
Imagine that I have two java.lang.String
object, one from Database and another is user input. In order to compare them, is it necessary to put trim()
on both side of comparison? Doesn't it look a little overhead?
if (userInput.trim().equals(dbString.trim())) {
.....
}
Is there a better way to do this? I fear I may forget to add trim()
on EVERY place where I want to compare them.
Upvotes: 0
Views: 1239
Reputation: 26961
If you control database (and nobody is allowed to change it) you can trust in your controls and validations before writting data on it. So comparison later can be done in a regular way later without any concern.
If you are in danger of getting data with extra blank characters (by some edit, or by other stuff).
YES, YOU MUST perform this controlled comparison.
If this is the case, don't panic about forgetting one trim()
when comparing, simply create a private method (or a static one in a HelperClass if will be used throug many... i guess.. SERVICES?), to make it clearer and don't forget to use trim():
private boolean areEquals(String a, String b) {
return a.trim().equals(b.trim());
}
USE:
if (areEquals(userInput, dbInput)) {
// do something
}
Upvotes: 4
Reputation: 546
Yes it is quite some overhead as every trim might construct a new string instance and then throws it away after comparison.
Just make sure to have the right input beforehand. So trim the values when you read them from the database or from user input. For the rest of the program flow in your code you can then be sure that all strings are already trimmed.
This will also prevent you from forgetting to put a trim before comparing the string somewhere else in your code.
Upvotes: 0