First of all I apologize for the long lead up to such a simplistic question.
I am implementing a class which serves as a very long 1 dimensional index on a space fil
Anyways in the implementation of operator[] I was wondering what the best method to achieve bounds checking is. I want to avoid throwing exceptions if at all possible, and the full range of values is usable for each number in the array so a special value to return in case of an out of bounds error is not possible either;
Then the remaining options are:
You: "Who lives in the 3rd floor?"
Me: "Mary".
You: "Who lives in the 9th floor?"
Me: "Joe".
You: "Who lives in the 1,203rd floor?"
Me: (Wait... 1,203 % 10 = 3...) > "Mary".
You: "Wow, Mary must enjoy great views from up there. So she owns two apartments then?"
A bool output parameter indicates success or failure. This option usually ends up in not very usable code. Many users will ignore the return code. You are still left with what you return in the other return value.
Design by Contract. Assert that the caller is within bounds. (For a practical approach in C++, see An exception or a bug? by Miro Samek or Simple Support for Design by Contract in C++ by Pedro Guerreiro.)
Return a System.Nullable
. Oops, wait, this is not C#. Well, you could return a pointer to a quint16. This of course has lots of implications which I shall not discuss here and which probably make this option not usable.
My favorite choices are: