Skip to content

Instantly share code, notes, and snippets.

What would you like to do?
Readability poll
// Performance appart, what is the most *READABLE* code to generate a simple error string?
$errorMessage = "Rule execution failed: " . $e->getMessage(); // Choice 1
$errorMessage = "Rule execution failed: {$e->getMessage()}"; // Choice 2
$errorMessage = sprintf('Rule execution failed: %s', $e->getMessage()); // Choice 3
Copy link

crevillo commented Jun 30, 2017

i tend to go for 1...

Copy link

remicollet commented Jun 30, 2017

2 (well concat is acceptable, as only 1 variable there)

Copy link

patrickallaert commented Jun 30, 2017

Personally: I never do "concatenation" with sprintf(). String interpolation (choice 2) and "." (choice 1) works fine for me.
However sprintf() is great for formatting option ("%10.10s", "%04d-%02d-%02d") and reusing arguments several times "%2$s.... %2$s".
Also, no editors "links" visually a %... with the corresponding sprintf argument, which makes it harder to read when you want to know how everything gets combined.

Copy link

hollodotme commented Jun 30, 2017

I think the actual context matters. Where will this message be displayed. How many variables. Is formatting needed.

I personally use sprintf() without the variable reusing feature, because this harms readability, is confusing and easily leads to misplaced values when changing the text. So I repeat arguments, if needed.

BTW: The PhpStorm plugin PHP Inspections (EA Extended) by @kalessil warns, if there is an argument count mismatch when using printf, sprintf, fprintf, sscanf, fscanf. So no direct relation of % to argument, but at least a helpful warning.

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment