开发者

Where should AND and OR be placed in multi-line conditional statements? [closed]

开发者 https://www.devze.com 2023-03-10 23:58 出处:网络
As it currently stands, this question is not a good fit for our Q&A format. We expect answers to be supported by facts, references,or expertise, but this question will likely solicit debate, a
As it currently stands, this question is not a good fit for our Q&A format. We expect answers to be supported by facts, references, or expertise, but this question will likely solicit debate, arguments, polling, or extended discussion. If you feel that this question can be improved and possibly reopened, visit the help center for guidance. Closed 11 years ago.

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.

0

精彩评论

暂无评论...
验证码 换一张
取 消

关注公众号