Document ternary expression style and the else-after-return prohibition. No bug, rs=luke over IRC, DONTBUILD because this is modifying docs but touching no code
Document ternary expression style and the else-after-return prohibition. No bug, rs=luke over IRC, DONTBUILD because this is modifying docs but touching no code
--- a/mfbt/STYLE
+++ b/mfbt/STYLE
@@ -37,16 +37,33 @@ goes for references -- & goes by the typ
int& i = *p;
}
A corollary: don't mix declaration types by declaring a T and a T* (or a T**,
&c.) in the same declaration.
T* foo, bar; // BAD
+== Expressions ==
+
+Ternary expressions (a ? b : c) should use only one line if sufficiently short.
+Longer ternary expressions should use multiple lines. The condition,
+consequent, and alternative should each be on separate lines (each part
+overflowing to additional lines as necessary), and the ? and : should be aligned
+with the start of the condition:
+
+ size_t
+ BinaryTree::height()
+ {
+ return isLeaf()
+ ? 0
+ : 1 + std::max(left()->height(),
+ right()->height());
+ }
+
== Bracing ==
Don't brace single statements.
if (y == 7)
return 3;
for (size_t i = 0; i < 5; i++)
frob(i);
@@ -342,8 +359,25 @@ interprets that argument.
enum Enumerability {
Enumerable,
NonEnumerable
};
bool
DefineProperty(JSObject* obj, const char* name, Value v, Enumerability e);
Use NULL for the null pointer constant.
+
+If a consequent in an if-statement ends with a return, don't specify an else.
+The else would be redundant with the return, and not using it avoids excess
+indentation. If you feel the if-else alternation is important as a way to
+think about the choice being made, consider a ternary expression instead.
+
+ // BAD
+ if (f())
+ return 2;
+ else
+ return 5;
+ // GOOD
+ if (f())
+ return 2;
+ return 5;
+ // GOOD
+ return f() ? 2 : 5