What are assertions or NSAssert good for in practice?

后端 未结 4 1198
迷失自我
迷失自我 2021-01-30 15:17

I wonder if it\'s a good habit to use NSAssert all over the place? What would be the benefit of doing that? In which situations is it a good idea to use it?

4条回答
  •  借酒劲吻你
    2021-01-30 15:32

    Debugging. Whenever you write code, you're almost always making assumptions. Assumptions about the state of the environment, the values of your parameters, your local variables and fields, etc. Oftentimes, these assumptions are just wrong (an old collegue gave me a good maxim, that "Assumption is the mother of all fsckups").

    Assertions exist to validate your assumptions, at the point you make them. You have a method

    void foo(int x)
    {
       …
    }
    

    that you know and have documented only works for x > 5? Assert it!

    Assertions live alongside unit testing and formal methods as part of good coding practice. Whilst some might think comprehensive unit tests ensure assertions are redundant, it's not the case. For example, you may have an assumption to a method that, say, employees are always over 16 and under 100 years old - but that the code, at the moment, doesn't require this. Unit tests that pass those parameters will succeed, but later when you need to use your assumption, you'll have code everywhere that passed the tests, but is wrong.

提交回复
热议问题