User Tools

Site Tools


python:guards

Differences

This shows you the differences between two versions of the page.

Link to this comparison view

python:guards [2013/03/16 17:41] (current)
Line 1: Line 1:
 +==== GUARDS ====
  
 +
 +In computer programming,​ a guard is a boolean expression that must evaluate to true if the program execution is to continue in the branch in question (more [[http://​en.wikipedia.org/​wiki/​Guard_(computing)| here]]). They can replace the nested if-else statements for example, acting like the security guards: you can go through in a function only if you pass the conditions, otherwise just leave.
 +
 +
 +Some nested if-else statements could be like:
 +<code python>
 +def analyzeInput(input):​
 +    if i >= 0:
 +        if i <= 10:
 +            print "Do the calculation..."​
 +        else:
 +            print "​ERROR:​The number should be less than 10"
 +    else:
 +        print "ERROR The number shouldn'​t be over 0"
 +    ​
 +    print "ERROR MSG: %s" % error
 +
 +i = int(raw_input("​Provide a number please between 1-10 "))
 +print i
 +analyzeInput(i)
 +</​code>​
 +
 +Using guards, the function can be transformed into:
 +
 +<code python>
 +# refactoring the code using guards
 +def analyzeInputRef(input):​
 +    if i < 0:
 +        print "​ERROR:​The number shouldn'​t be over 0"
 +        return ​
 +
 +    if i > 10:
 +        print "​ERROR:​The number should be less than 10"
 +        return
 +
 +    print "Do the calculation..."​
 +</​code>​
python/guards.txt ยท Last modified: 2013/03/16 17:41 (external edit)