A simple coding standard question:
Where should AND and OR be placed in conditional statements?
Option 1:
if (x = 1
AND y = 2
AND z = 3)
if (x = 1
&&a开发者_如何转开发mp; y = 2
&& z = 3)
if (x = 1
OR y = 2
OR z = 3)
if (x = 1
|| y = 2
|| z = 3)
Option 2:
if (x = 1 AND
y = 2 AND
z = 3)
if (x = 1 &&
y = 2 &&
z = 3)
if (x = 1 OR
y = 2 OR
z = 3
if (x = 1 ||
y = 2 ||
z = 3)
I personally prefer option 1, since it allows you quickly comment out certain conditions - i.e. with "//" in most scripting languages, but I see option 2 more often, especially in code formatters.
Is there a standard?
What do you prefer?
In "Code Complete," 2nd ed., pp 754-755, Steve McConnell lists the advantages of both patterns of line continuation.
The first identifies incomplete lines, but the operators are hidden in a ragged row.
The second highlights the operators. This can be important if the operators differ.
Compare:
float total = ticketSalesBefore +
ticketSalesOnDayOfConcert +
tShirtSales -
finesFromLocalPolice;
to:
float total = ticketSalesBefore
+ ticketSalesOnDayOfConcert
+ tShirtSales
- finesFromLocalPolice;
I personally prefer the second, and recommended including it during a review of McConnell's draft for that chapter.
Option 1, absolutely, for the same reasons you mentioned. Easy to comment out, easy to duplicate, etc.
However, if they are small conditionals like you mentioned, I would put them all on one line.
I prefer Option 1 because it highlights the tests. For Python coding I generally agree with PEP 8, but they go with Option 2 for this one.
精彩评论