]> git.ipfire.org Git - thirdparty/libvirt.git/commitdiff
coding-style: Allow some use of ternary operators
authorMichal Privoznik <mprivozn@redhat.com>
Mon, 25 Jul 2022 13:04:54 +0000 (15:04 +0200)
committerMichal Privoznik <mprivozn@redhat.com>
Tue, 26 Jul 2022 06:48:48 +0000 (08:48 +0200)
While we all understand that excessive use of ternary operator
may worsen code readability (e.g. nested, multi-line expression),
there are few cases where using it actually improves code
readability. For instance, when a function takes a long list of
arguments out of which one depends on a boolean expression, or
when formatting "yes"/"no" or "on"/"off" values based on a
boolean variable (although one can argue that the latter is a
subset of the former). Just consider alternatives to:

  virBufferAsprintf(buf, "<elem>%s</elem>\n", boolVar ? "yes" : "no");

In fact, this pattern occurs plenty in our code. Exempt it from
our "no ternary operators" rule.

Signed-off-by: Michal Privoznik <mprivozn@redhat.com>
Reviewed-by: Claudio Fontana <cfontana@suse.de>
Reviewed-by: Daniel P. Berrangé <berrange@redhat.com>
docs/coding-style.rst

index bf0a80fbc5538c8e8647506a8f35407a55ab6f41..81bd4474f1488b237939c3d469bb785b096e4c06 100644 (file)
@@ -470,7 +470,9 @@ Pointer comparisons may be shortened. All long forms are okay.
     if (!foo)                # or: if (foo == NULL)
 
 New code should avoid the ternary operator as much as possible.
-Specifically it must never span more than one line or nest:
+Its usage in basic cases is warranted (e.g. when deciding between
+two constant strings), however, it must never span more than one
+line or nest.
 
 ::
 
@@ -481,6 +483,9 @@ Specifically it must never span more than one line or nest:
 
     char *foo = bar ? bar->baz ? bar->baz->foo : "nobaz" : "nobar";
 
+  GOOD:
+    virBufferAsprintf(buf, "<element>%s</element>\n", boolVar ? "yes" : "no");
+
 Preprocessor
 ------------