Skip to main content
edited title
Link
kdbanman
  • 1.4k
  • 1
  • 13
  • 20

Should my (sequential)sequential collection start at index 0 or index 1?

Question Unprotected by gnat
Question Protected by gnat
Tweeted twitter.com/#!/StackProgrammer/status/619411967376248832
Source Link
kdbanman
  • 1.4k
  • 1
  • 13
  • 20

Should my (sequential) collection start at index 0 or index 1?

I am creating an object model for a device that has multiple channels. The nouns used between the client and I are Channel and ChannelSet. ("Set" isn't semantically accurate, because it's ordered and a proper set isn't. But that's a problem for a different time.)

I'm using C#. Here is a usage example of ChannelSet:

// load a 5-channel ChannelSet
ChannelSet channels = ChannelSetFactory.FromFile("some_5_channel_set.json");

Console.Write(channels.Count);
// -> 5

foreach (Channel channel in channels) {
    Console.Write(channel.Average);
    Console.Write(",  ");
}
// -> 0.3,  0.3,  0.9,  0.1,  0.2

All is dandy. However, the clients are not programmers and they absolutely will be confused by zero indexing - the first channel is channel 1 to them. But, for the sake of consistency with C#, I want to keep the ChannelSet indexed from zero.

This is sure to cause some disconnects between my dev team and the clients when they interact. But worse, any inconsistency in how this is handled within the codebase is a potential problem. For example, here's a UI screen where the end user (who thinks in terms of 1 indexing) is editing channel 13:

Channel 13 or 12?

That Save button is eventually going to result in some code. If ChannelSet is 1 indexed:

channels.GetChannel(13).SomeProperty = newValue;  // notice: 13

or this if it's zero indexed:

channels.GetChannel(12).SomeProperty = newValue;  // notice: 12

I'm not really sure how to handle this. I feel like it's good practice to keep an ordered, integer-indexed list of things (the ChannelSet) consistent with all of the other array and list interfaces in the C# universe (by zero indexing ChannelSet). But then every piece of code between the UI and the backend will need a translation (subtract by 1), and we all know how insidious and common off-by-one errors already are.

So, has a decision like this ever bitten you? Should I zero index or one index?