Should I be using assert in my PHP code?

前端 未结 8 1566
执念已碎
执念已碎 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:50

    It wholly depends on your development strategy. Most developers are unaware of assert() and use downstream unit testing. But proactive and built-in testing schemes can sometimes be advantageous.

    assert is useful, because it can be enabled and disabled. It doesn't drain performance if no such assertion handler is defined. Your collegue doesn't have one, and you should devise some code which temporary enables it in the development environment (if E_NOTICE/E_WARNINGs are on, so should be the assertion handler). I use it occasionally where my code can't stomach mixed variable types - I don't normally engage in strict typing in a weakly typed PHP, but there random use cases:

     function xyz($a, $b) {
         assert(is_string($a));
         assert(is_array($b));
    

    Which for example would compensate for the lack of type specifiers string $a, array $b. PHP5.4 will support them, but not check.

提交回复
热议问题