rspec/rules/S4004/rule.adoc
Tim Pohlmann e0131c9ad1
Modify rule S4004: Fix code samples (#2808)
## Review

A dedicated reviewer checked the rule description successfully for:

- [ ] logical errors and incorrect information
- [ ] information gaps and missing content
- [ ] text style and tone
- [ ] PR summary and labels follow [the
guidelines](https://github.com/SonarSource/rspec/#to-modify-an-existing-rule)
2023-08-07 11:51:07 +02:00

66 lines
1.5 KiB
Plaintext
Raw Blame History

This file contains invisible Unicode characters

This file contains invisible Unicode characters that are indistinguishable to humans but may be processed differently by a computer. If you think that this is intentional, you can safely ignore this warning. Use the Escape button to reveal them.

== Why is this an issue?
A writable collection property can be replaced by a completely different collection. Making it ``++readonly++`` prevents that while still allowing individual members to be set. If you want to allow the replacement of the whole collection the recommended pattern is to implement a method to remove all the elements (e.g. ``++System.Collections.List<T>.Clear++``) and a method to populate the collection (e.g. ``++System.Collections.List<T>.AddRange++``).
This rule raises an issue when an externally visible writable property is of a type that implements ``++System.Collections.ICollection++`` or ``++System.Collections.Generic.ICollection<T>++``.
=== Noncompliant code example
[source,text]
----
using System;
using System.Collections;
namespace MyLibrary
{
public class Foo
{
List<string> strings;
public List<string> SomeStrings
{
get { return strings; }
set { strings = value; } // Noncompliant
}
}
}
----
=== Compliant solution
[source,text]
----
using System;
using System.Collections;
namespace MyLibrary
{
public class Foo
{
List<string> strings;
public List<string> SomeStrings
{
get { return strings; }
}
}
}
----
=== Exceptions
This rule does not raise issues for
* ``++string++``, ``++Array++`` and ``++PermissionSet,++``
* properties marked as ``++DataMemberAttribute++``
* classes marked as ``++Serializable++``
* properties overriding a base class member
* properties implementing interface