When implementing operator[] how should I include bounds checking?

前端 未结 13 1946
清酒与你
清酒与你 2021-01-19 06:12

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

13条回答
  •  一生所求
    2021-01-19 07:05

    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:

    • Flexible design. What you did. "Fix" the invalid input so that it tries to do something which makes sense. Advantage: Function won't crash. Disadvantage: Clueless callers who access an out of bounds element will get a lie as a result. Imagine a 10-floor building with floors 1 to 10:

    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:

    • For the public interface of a publicly released library: Input will be checked and an exception will be thrown. You ruled out this option, so it is not an option for you. It is still my choice for the interface of a publicly released library.
    • For internal code: Design by contract.

提交回复
热议问题