I’ve seen many developers steer clear of the
sprintf function. In this short article I will try to convince you that
sprintf helps in many cases, using mainly PHP as an example (but I talk about other languages as well).
The following return statements are equivalent.
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:
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:
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:
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.