rspec/rules/S3221/rule.adoc

64 lines
1.3 KiB
Plaintext
Raw Permalink Normal View History

== Why is this an issue?
Using parallel collections or arrays rather than classes to hold and process related pieces of data is an antipattern. Instead, define a type for the entity the arrays represent and use an array or collection of that type.
This rule raises an issue when the index from one array or collection is used to access an element from another array or collection.
=== Noncompliant code example
2022-02-04 17:28:24 +01:00
[source,text]
----
class Leg
{
public int Length { get; set; }
}
var rightLegs = //...
var leftLegs = //...
for(var i = 0; i<rightLegs.Count; i++)
{
var rightLeg = rightLegs[i]; // Noncompliant
var leftLeg = leftLegs[i]; // Noncompliant
if (leftLeg.Length != rightLeg.Length)
{
//... unlucky
}
}
----
=== Compliant solution
2022-02-04 17:28:24 +01:00
[source,text]
----
class Leg
{
public int Length { get; set; }
}
class Biped
{
public Leg LeftLeg { get; set; }
public Leg RightLeg { get; set; }
}
var creatures = //...
for(var i = 0; i<creatures.Count; i++)
{
var creature = creatures[i];
if (creature.LeftLeg.Length != creature.RightLeg.Length)
{
//... unlucky
}
}
----
=== Exceptions
Because it is a common pattern to copy items from one collection to another collection, no issue is raised if the collection element is being written.