Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

What's the reason behind CA1023

CA1023: Indexers should not be multidimensional

Indexers, that is, indexed properties, should use a single index. Multi-dimensional indexers can significantly reduce the usability of the library. If the design requires multiple indexes, reconsider whether the type represents a logical data store. If not, use a method.

To fix a violation of this rule, change the design to use a lone integer or string index, or use a method instead of the indexer.

This seems very strange to me, why does this significantly affect anything? other than making a multidimensional index much less intuitive?

Change the design to use a string? And do what with it? Parse the numbers out at the other end and lose strong typing?

Can someone give me some reasons why there is something wrong with Multidimensional indexers?

like image 763
James Barrass Avatar asked Jan 06 '14 11:01

James Barrass


1 Answers

If the design requires multiple indexes, reconsider whether the type represents a logical data store. If not, use a method.

The problem is that indexers cannot be specifically named (except, as @volpav comments, for interfacing with languages that don't natively support them - by default, they are called Item) whereas methods must be. This means that a client may have problems guessing at the meaning of an indexer if it is not immediately obvious ("represents a logical data store"). This can be particularly vexing if an indexer has multiple parameters and/or multiple overloads of the indexer exist. Of course, naming indexer parameters can help matters (although the indexer itself cannot be specifically named in C#), but consider that methods can hint at the meanings of the return value and the parameters in the name of the method itself (consider GetCustomersByCountryAndAge vs this[string, int] ). This greatly helps readability when browsing source code.

Well-written XML documentation for your indexer would also help.

To fix a violation of this rule, change the design to use a lone integer or string index

This somewhat poorly phrased sentence appears to be advice combined with the observation that int and string are the most common parameter types for indexers. It should likely just read "change the design to use a lone index."

like image 60
Ani Avatar answered Oct 18 '22 00:10

Ani