-
Notifications
You must be signed in to change notification settings - Fork 2k
Expand file tree
/
Copy pathExposeRepresentation.qhelp
More file actions
44 lines (36 loc) · 1.95 KB
/
ExposeRepresentation.qhelp
File metadata and controls
44 lines (36 loc) · 1.95 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
<!DOCTYPE qhelp PUBLIC
"-//Semmle//qhelp//EN"
"qhelp.dtd">
<qhelp>
<overview>
<p>Sometimes a method of a class can expose an internal field to change by other code if it returns a reference
to a mutable private field.</p>
</overview>
<recommendation>
<p>There are several ways to address this problem depending on your situation. One of the best ways is
to use an immutable object to store fields. References to this object can be passed outside the class but
the objects are immutable so they cannot be changed.</p>
<p>Another good way of preventing external modification of private fields is to only ever return a copy of
the object referred to by the field. This is called "defensive copying". If the copy is changed then internal
fields will not be affected.</p>
</recommendation>
<example>
<p>This example clearly demonstrates the problem with passing references to mutable objects outside a class. In this case
it was possible to modify the values in the array despite the <code>Range</code> class not offering any method to do so.</p>
<sample src="ExposeRepresentationBad.cs" />
</example>
<section title="Fixing with an immutable object">
<p>Here the example has been modified to prevent changes to the private field by using a <code>ReadOnlyCollection</code>
object.</p>
<sample src="ExposeRepresentationGood1.cs" />
</section>
<section title="Fixing with defensive copying">
<p>This is an example of the same class but this time it returns a defensive copy of the private field. There is also
a short program showing what happens when an attempt is made to modify the data held by the field.</p>
<sample src="ExposeRepresentationGood2.cs" />
</section>
<references>
<li>MSDN, C# Programming Guide, <a href="https://docs.microsoft.com/en-us/dotnet/csharp/programming-guide/arrays/arrays-as-objects">Arrays as Objects</a>.</li>
<li>MSDN, <a href="http://msdn.microsoft.com/en-us/library/ms132474.aspx">ReadOnlyCollection<T></a>.</li>
</references>
</qhelp>