Should one leave asserts in production iOS apps?

后端 未结 4 448
梦如初夏
梦如初夏 2021-02-08 20:12

Common practice might be to put asserts in code to check input parameters, data integrity, and such, during app development.

I test my apps, BUT, given that I\'m not K

4条回答
  •  星月不相逢
    2021-02-08 20:40

    My recommendation: You should leave them ON by default. I say: "fail hard, fail early" -- and keep your bugfixes at a higher priority than features.

    However, choice is also good -- I don't think one size fits all programs. For this reason, I use multiple types of assertions. Some will be live in release, some will not. I write a lot of error detection, and I also write a lot of performance critical programs. I can't leave a ton of diagnostics and sanity checks in hot paths of release builds.

    Unfortunately, it cannot be an afterthought (unless maybe you are prepared to prioritize quality and testing for an open-ended amount of time). If you think about it, the single/traditional approach also cannot be an afterthought. With either model, it is best decide whether assertions or which assertions will be enabled in release before writing your program.


    So the basic general form of a dual assert model might look like:

    #include 
    
    /*
      MONDebugAssert assertion is active in debug and disabled in release.
      Recommendation: Always define NDEBUG (or not) in your build settings, 
      and nowhere else.
    */
    #if defined(NDEBUG)
        #define MONDebugAssert(e) ((void)0)
    #else
        #define MONDebugAssert(e) \
            (__builtin_expect(!(e), 0) ? __assert(#e, __FILE__, __LINE__) : (void)0)
    #endif
    
    /* MONAssert assertion is active at all times, including release builds. */
    #define MONAssert(e) \
           (__builtin_expect(!(e), 0) ? __assert(#e, __FILE__, __LINE__) : (void)0)
    

    where __assert is the platform assertion handler.

    Then in use:

    MONDebugAssert(0); // << will fail in debug, and not in release.
    MONAssert(0); // << will fail in any case
    

    Of course, it is easy enough to adapt for your needs, or create variants where self is assumed to be in the scope (like NSAssert).

提交回复
热议问题