rspec/rules/S2931/rule.adoc
jtingsanchali 96d9ddb930
RULEAPI-755 Update CWE URLs by removing .html suffix and update with https protocol (#926)
* Change affects only see.adoc and rule.adoc files, not comments-and-links.adoc files
2022-04-07 08:53:59 -05:00

56 lines
1.6 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.

An ``++IDisposable++`` object should be disposed (there are some rare exceptions where not disposing is fine, most notably ``++Task++``). If a class has an ``++IDisposable++`` field, there can be two situations:
* The class observes a field that is under the responsibility of another class.
* The class owns the field, and is therefore responsible for calling ``++Dispose++`` on it.
In the second case, the safest way for the class to ensure ``++Dispose++`` is called is to call it in its own ``++Dispose++`` function, and therefore to be itself ``++IDisposable++``. A class is considered to own an ``++IDisposable++`` field resource if it created the object referenced by the field.
== Noncompliant Code Example
[source,text]
----
public class ResourceHolder // Noncompliant; doesn't implement IDisposable
{
private FileStream fs; // This member is never Disposed
public void OpenResource(string path)
{
this.fs = new FileStream(path, FileMode.Open); // I create the FileStream, I'm owning it
}
public void CloseResource()
{
this.fs.Close();
}
}
----
== Compliant Solution
[source,text]
----
public class ResourceHolder : IDisposable
{
  private FileStream fs;
  public void OpenResource(string path)
  {
    this.fs = new FileStream(path, FileMode.Open); // I create the FileStream, I'm owning it
  }
  public void CloseResource()
  {
    this.fs.Close();
  }
  public void Dispose()
  {
    this.fs.Dispose();
  }
}
----
== See
* https://cwe.mitre.org/data/definitions/459[MITRE, CWE-459] - Incomplete Cleanup