Easy examples of redundancy
The following are some examples of simple redundancies in procedural programming. They are given in Python. I typically run into these when I simplify my code after writing it for the first time or after making edits.
Using if-else to assign a Boolean:
if condition: x = True else: x = False
Simplified:
x = condition
(Requires that condition is a Boolean.)
Returning immediately after an assignment:
y = value return y
Simplified:
return value
Common code among branches:
if condition: group of statements A group of statements B group of statements D else: group of statements A group of statements C group of statements D
Simplified:
group of statements A if condition: group of statements B else: group of statements C group of statements D
Nested if-statements:
if condition0: if condition1: statements
Simplified:
if condition0 and condition1: statements
Requires that the outer if-statement does not have an else-clause.
If-statements with the same actions:
if condition0: statements (same) if condition1: statements (same)
Simplified:
if condition0 or condition1: statements (same)
Requires condition0 and condition1 to be disjoint, or statements to be idempotent.
Explore posts in the same categories: Python, Uncategorized
2008-07-29-Tue at 16:03
Better yet, for the first example,
x = bool(condition)
— condition can be whatever you want now :)Another one that I like to simplify is something like:
if condition:
...
foo = bar
else:
foo = None
down to:
foo = None
if condition:
...
foo = bar
Less code, and I find it easier to read.
(now, let’s just hope all the markup works here… Hurra for not having a “preview” button!)
2008-07-29-Tue at 21:13
You’re such a stalker of my blog, Wolever. Especially when it comes to Python. =P