Should I be using assert in my PHP code?

前端 未结 8 1561
执念已碎
执念已碎 2020-12-02 16:07

A coworker has added the assert command a few times within our libraries in places where I would have used an if statement and thrown an exception. (I had never even heard o

8条回答
  •  温柔的废话
    2020-12-02 16:46

    The rule of thumb which is applicable across most languages (all that I vaguely know) is that an assert is used to assert that a condition is always true whereas an if is appropriate if it is conceivable that it will sometimes fail.

    In this case, I would say that assert is appropriate (based on my weak understanding of the situation) because records should always be set before the given method is called. So a failure to set the record would be a bug in the program rather than a runtime condition. Here, the assert is helping to ensure (with adequate testing) that there is no possible program execution path that could cause the code that is being guarded with the assert to be called without records having been set.

    The advantage of using assert as opposed to if is that assert can generally be turned off in production code thus reducing overhead. The sort of situations that are best handled with if could conceivably occur during runtime in production system and so nothing is lost by not being able to turn them off.

提交回复
热议问题