dennisdoomen / CSharpGuidelines

A set of coding guidelines for C# 9.0, design principles and layout rules for improving the overall quality of your code development.
https://www.csharpcodingguidelines.com
Other
745 stars 272 forks source link

Proposal: relax parenthesis usage (AV2400) #207

Closed bkoelman closed 4 years ago

bkoelman commented 4 years ago

Existing guidance:

Add parentheses around every binary expression, but don’t add parentheses around unary expressions. For example if (!string.IsNullOrEmpty(str) && (str != "new"))

Most developers are unaware that && has higher precedence than ||, which makes expressions like below hard to read:

if (a && b || c)
{
}

For other cases I think precedence is obvious for most developers:

if (a > b && c < d)
{
}

int result = a + b * c;

Recently the usage of parentheses was added to Visual Studio / .editorconfig:

# Parentheses preferences
dotnet_style_parentheses_in_arithmetic_binary_operators = always_for_clarity:silent
dotnet_style_parentheses_in_other_binary_operators = always_for_clarity:silent
dotnet_style_parentheses_in_other_operators = never_if_unnecessary:silent
dotnet_style_parentheses_in_relational_binary_operators = always_for_clarity:silent

and to Resharper: image

This enables us to be more specific on which cases parentheses are helpful and have automated formatting settings for them.

dennisdoomen commented 4 years ago

So how would you change the rule?

bkoelman commented 4 years ago

Remove redundant parentheses in expressions if they do not clarify precedence. Add parentheses in expressions to avoid non-obvious precedence. For example, in nested conditional expressions: overruled || (enabled && active), bitwise and shift operations: foo | (bar >> size).

dennisdoomen commented 4 years ago

I think that's a good balance.