Having finished week 10 of the course, we learned how to make some basic unittests for our second assignment in addition to learning about the benefits (and potential drawbacks) of assertion statements. In particular, assertion statements are useful in being able to check if certain parts of the code (such as while loops) are doing what they were programmed to do. For example, given the following code,
if lnk.size > 0:
prev_node = None
cur_node = lnk.front
while cur_node and not cur_node.value == v2:
prev_node = cur_node
cur_node = cur_node.nxt
assert cur_node is None or cur_node.value == v2, 'Wrong Output'
Here, we perform a basic analysis of the conditions of the while loop. The program exists the while loop when its negation is fulfilled which occurs when either cur_node == None or cur_node.value == v2. By claiming assert with the following conditions we can see if our while loop indeed does what is programed to do for something that is not obvious by just looking at the code. The 'error string' after the comma is simply a message describing what the error is.
The advantages of using assert for complex while loops and other parts of code are numerous. First, it signals the presence of potential bugs/errors early on the code than if the entire program were allowed to run. This way, a programmer spends less time figuring out 'where' the code falters because there are more safety 'checkpoints'. On the other hand, just like commenting, an overuse of assert statements can be cumbersome and unseemly. In addition, too many assert statements could potentially slow down code since comparisons are being made in the assert statement itself.
One additional use of assert statements can be found in type contracts which serve to alert a programmer when incorrect input is given (which will inevitably flag potential bugs before the program is allowed to fully run). Here is an example:
def list_between(node, start, end):
''' (BTNode, object, object) -> list
Return a python list of all the values in the BST rooted at node that are between start and end (inclusive)
'''
assert isinstance(node, BTNode), 'node is not a BTNode: {}'.format(node)
Overall, I am looking forward to the last two weeks on analysing efficiency to make our code smarter and faster.
No comments:
Post a Comment