I’ve seen many developers steer clear of the sprintf
function. In this short article I will try to convince you thatsprintf
helps in many cases, using mainly PHP as an example (but I talk about other languages as well).
Natural readability
The following return statements are equivalent.
https://gist.github.com/calina-c/9fae80512167d4afe7a3ff679c4f96ea
However, by the time you’ve finished reading the second one, you’re probably wondering about correct spacing, coding standards regarding line length and the meaning of life itself.
Conversions and number formatting
The following return statements are equivalent:
https://gist.github.com/calina-c/67180e4a3ba43a122c3d03d5565318b7
However, the latter requires developers to know the number_format
function and its parameter list. At least PHP is able to perform conversions, but, for example, Python disallows the following:
return “The number is “ + 2
because it doesn’t automatically convert 2 to the string “2”, which means the following solutions work:
https://gist.github.com/calina-c/5e8c965962bc0240eab516cb7a180670
Considering my first point about readability and how the two solutions scale to more numbers, I will let you decide which is better.
Maintainability of conditionals
Consider the following use case. Upon creating or updating a model in our application, we want to show a message: “Item was created” or “Item was updated.” Here are two solutions, separated by a line of comment characters (“#”). I am using the ternary operator because it’s more concise:
https://gist.github.com/calina-c/5f21c6260b4c4c14aaf099b61d7e20fa
The first solution contains text duplication, which means it is easy to forget to edit both messages. The second option is better because it does not duplicate the text, so modifying the message in just this one place will suffice.