Hacker News new | ask | show | jobs
by AnimalMuppet 2110 days ago
Maybe A, but not (IMO) dramatically so. But shouldn't A actually be "${cat} ${dog} ${giraffe} <random text> ... <random text> ${dinosaur}"? That makes it closer in difficulty to B.

To me, the difference shows up more with this scenario:

A: "${v1} ${v2} ${v3} ${v4}"

B1: "%s %s %s %s".formatted(v1, v2, v3)

B2: "%s %s %s %s".formatted(v1, v2, v3, v4, v5)

B3: "%s %s %s".formatted(v1, v2, v3, v4)

A does what you tell it, whether it's wrong or right. B has a chance of warning you that the argument list and the format specifier don't match. On the other hand, B gives you two things that have to be kept in sync with each other, and A can't get out of sync, since there's only one thing.

So: Less of a chance to make the error, or more of a chance to catch it. Which is better? I lean toward A, but I will admit that it seems subjective.

1 comments

> Less of a chance to make the error, or more of a chance to catch it.

B only catches mistakes in the case that the number of parameters doesn't match the number of placeholders, which isn't even possible with A. If the string you built isn't correct, that's on you in either case, and should be immediately obvious by looking at the output. So in that sense, interpolation is strictly better than `formatted` at dealing with potential mistakes.