I have \"best practices\" question about OOP in C# (but it sort-of applies to al
ID: 643738 • Letter: I
Question
I have "best practices" question about OOP in C# (but it sort-of applies to all languages).
Consider having library class with object that is to be exposed to public, say via property accessor, but we do not want the public (people using this library class) to change it.
class A
{
// Note: List is just example, I am interested in objects in general.
private List<string> _items = new List<string>() { "hello" }
public List<string> Items
{
get
{
// Option A (not read-only), can be modified from outside:
return _items;
// Option B (sort-of read-only):
return new List<string>( _items );
// Option C, must change return type to ReadOnlyCollection<string>
return new ReadOnlyCollection<string>( _items );
}
}
}
Obviously the best approach is "option C", but very few objects have ReadOnly variant (and certainly no user-defined classes have it).
If you were the user of class A, would you expect changes to
List<string> someList = ( new A() ).Items;
propagate to original (A) object? Or is it okay to return a clone provided that it was written so in comments/documentation? I think that this clone approach might lead to quite difficult-to-track bugs.
I remember that in C++ we could return const objects and you could only call methods marked as const on it. I guess there is no such feature/pattern in the C#? If not why would they not include it? I believe it is called const correctness.
But then again my main question is about "what would you expect" or how to handle Option A vs B.
Explanation / Answer
Besides @Jesse's answer, which is the best solution for collections: the general idea is to design your public interface of A in a way so that it does return only
value types (like int, double, struct)
immutable objects (like "string", or user defined classes which offer only read-only methods, just like your class A)
(only if you must): object copies, like your "Option B" demonstrates
IEnumerable<immutable_type_here> is immutable by itself, so this is just a special case of the above.
Related Questions
Navigate
Integrity-first tutoring: explanations and feedback only — we do not complete graded work. Learn more.