Conversion function for error checking considered good?

前端 未结 3 1288
情话喂你
情话喂你 2020-11-28 22:32

I\'d like to have a simple way of checking for an object to be valid. I thought of a simple conversion function, something like this:

operator bool() const          


        
3条回答
  •  伪装坚强ぢ
    2020-11-28 23:17

    The original question was

    Is this considered a good practise?

    The issue with the safe bool conversion was very relevant in practice, but fortunately has now been addressed by the standards.

    But the judgement if this approach is appropriate, is a question of design.

    By introducing such a "validity check", effectively you are stating that your objects can be in an invalid state. That is, speaking in the terms of computer science, you added a new separate value to the value domain represented by your objects. A so called bottom value

    The most prominent example for a value domain with that propery is the pointer. A pointer can refer to various memory locations, but it also can be NULL (invalid).

    Thus we need do ask ourselves: does such a bottom value really reflect the nature of the things we want to model with our classes -- and -- do we really need to cover this aspect of the nature within our model?

    Experience shows that bottom values tend to be error prone, easy to forget and generally more of a liability than an asset. If you're able to arrange your code in a way that your objects can not be invalid, your code gets simpler, easier to read, to understand and to maintain..

提交回复
热议问题