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.

Advertisements
Explore posts in the same categories: Python, Uncategorized

2 Comments on “Easy examples of redundancy”


  1. 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!)

  2. qztxon Says:

    You’re such a stalker of my blog, Wolever. Especially when it comes to Python. =P


Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out / Change )

Twitter picture

You are commenting using your Twitter account. Log Out / Change )

Facebook photo

You are commenting using your Facebook account. Log Out / Change )

Google+ photo

You are commenting using your Google+ account. Log Out / Change )

Connecting to %s


%d bloggers like this: