Plunging into .NET Development

Weblog Pieter Gheysens
Microsoft .NET Development - C# - Enterprise Library - Visual Studio 2005 Team System - Compuware DevPartner - ...

Sunday, December 14

Passing parameters in public signatures

Passing List<T> in a public signature is generally not a good idea. Consider this simple example :

MyMethod accepts List<string> as a parameter and the method just iterates through the list to write all strings in the collection to the output window. The code will compile and it will work, but it's not good design. If code analysis was enabled for the project this method belongs, a warning/error would definitely pop up ...

CA1002 (Microsoft Design) : Change 'List<string>' in 'MyService.MyMethod(List<string>)' to use Collection<T>, ReadOnlyCollection<T> or KeyedCollection<K,V>

The rule explains that List<T> was not designed for inheritance (no virtual members) and another generic collection should be exposed instead. In fact List<T> also contains too many irrelevant members : searching, sorting and manipulating the list. The best choice in the example above would be to expose a ReadOnlyCollection<T>.

Let's go a little bit further here. One of the first principles of object oriented design is to program against interfaces and not to an implementation. And for passing a list of strings as input parameters, we should always try to start with IEnumerable<string> and increase the amount of responsibilities (ICollection<string> --> IList<string>) only when required. In the example above IEnumerable<string> should be used because we only need the list for simple iteration. If it would for example also be necessary to get the number of elements in the list, then ICollection<string> should be used ... and so on ...

In conclusion it must be said that it's very important to review the public signatures of your classes. You don't want to expose more members than you need to expose. For returning objects from a method, you should only return the simplest working object (ReadOnlyCollection<T> --> Collection<T> --> List<T>) and for passing input parameters always start with IEnumerable<T> and go up the stack only when it's really needed. To help you with this review you can rely on some rules of Static Code Analysis in Visual Studio. Basically there aren't any good reasons to turn off Static Code Analysis completely for your development projects!



Post a Comment

Links to this post:

Create a Link

<< Home