Keyboard shortcuts

Press or to navigate between chapters

Press S or / to search in the book

Press ? to show this help

Press Esc to hide this help

Refactor to get assertTrue

As we are also programmers we will soon recognize that there is code duplication in our test script and will factor out the whole printing of pass/fail part to a function that we call assertTrue(). It should receive a true or false value and it will print "pass" or "fail" accordingly.

<?php

require_once(dirname(__FILE__) . '/../includes/mylib.php');

assertTrue(add(1,1)   == 2);
assertTrue(add(2,2)   == 4);
assertTrue(add(1,1,1) == 3);


function assertTrue($condition) {
    print ($condition ? 'pass' : 'fail') . '<br>';
}

?>

Result:

pass
pass
fail

As in every refactoring the functionality and the output should remain the same, just the implementation improves. (Hopefully)