rspec/rules/S3240/csharp/rule.adoc

65 lines
1.1 KiB
Plaintext
Raw Normal View History

2021-04-28 16:49:39 +02:00
In the interests of keeping code clean, the simplest possible conditional syntax should be used. That means
* using the ``++??=++`` operator for a self-assign-if-not-null operation,
* using the ``++??++`` operator for an assign-if-not-null operation, and
* using the ternary operator ``++?:++`` for assignment to a single variable.
2021-04-28 16:49:39 +02:00
== Noncompliant Code Example
----
object a = null, b = null, x;
if (a != null) // Noncompliant; needlessly verbose
{
x = a;
}
else
{
x = b;
}
x = a != null ? a : b; // Noncompliant; better but could still be simplified
x = (a == null) ? new object() : a; // Noncompliant
if (condition) // Noncompliant
{
x = a;
}
else
{
x = b;
}
if (a == null) // Noncompliant
a = new object();
var y = null ?? new object(); // Noncompliant
a = a ?? new object(); // Noncompliant for C# 8
----
2021-04-28 16:49:39 +02:00
== Compliant Solution
----
object x;
x = a ?? b;
x = a ?? b;
x = a ?? new object();
x = condition ? a : b;
a ??= new object();
var y = new object();
a ??= new object();
----
ifdef::rspecator-view[]
== Comments And Links
(visible only on this page)
include::comments-and-links.adoc[]
endif::rspecator-view[]