Using string-dot-format to craft user feedback
A while back I created a central validation component that I recently had to internationalize. This validator had a lot of standard messages - *Please specify a value for, Value must be between x and y, *and so on. Code that constructs these messages can look a little crude:
```javaString message = “Please specify a value between “ + minValue + “ and “ + maxValue + “ for “ + formFieldTitle;
Using String.format() we can make the code look a little cleaner. First we create the message as a constant, placing %s and %d where were want the minValue, maxValue and formFieldTitle values:
```javafinal String BETWEEN_MESSAGE = "Please specify a value between %d and %d for %s";
String message = String.format(BETWEEN_MESSAGE, minValue, maxValue, formFieldTitle);
Seems pretty basic. String.format() offers a lot of additional functionality on top of the basic usage here. We can specify the number of decimal places to print a floating point:
javaString.format("Delicious pie: %.2f", 3.14159) // Outputs: "Delicious pie: 3.14
When formatting date and/or time, String.format is very convenient. I’m not going to get into examples… because I don’t want to.