rspec/rules/S4004/rule.adoc

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 readonly 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