Login | Register   
LinkedIn
Google+
Twitter
RSS Feed
Download our iPhone app
TODAY'S HEADLINES  |   ARTICLE ARCHIVE  |   FORUMS  |   TIP BANK
Browse DevX
Sign up for e-mail newsletters from DevX


 
 

Code Optimization: If-Less Programming

Posted by Gigi Sayfan on Jul 21, 2016

I have often encountered code littered with lots of nested if and else statements. I consider it a serious code smell. Deeply nested code, especially if the nesting is due to conditionals, is very difficult to follow, wrap your head around and test. It even makes it difficult for the compiler or runtime to optimize. In many cases it is possible to flatten deeply nested code by very simple means. Here are a few examples in Python, but the concepts translate to most languages:

if some_predicate() == True:
result = True
else:
result = False
This can be simply replaced with:

reslt = some_predicate()

Inside loops you can often break out/return or continue and keep the body of the loop shallow.

for i in get_numbers():
if i <= 50:
if i % 2 == 0:
print('Even')
else:
print('Odd') 

Note, that there are two levels of nesting inside the loop. That can be replaced with:



for i in get_numbers():
if i > 50:
continue
msg = 'Even' if i % 2 == 0 else 'Odd'
print(msg) 

I used Python's continue statement to eliminate nesting due to the 50 check and then a ternary expression to eliminate the nesting due to the even/odd check. The result is that the main logic of the loop is not nested two levels deep.

Another big offender is the exception handling. Consider this code:

try:
try:
f = open(filename)
except IOError:
print('Can't open file')
raise
do_something_with_file(f)
except Exception as e:
print('Something went wrong') 

I've seen a lot of similar code. The exception handling here doesn't do much good. There is no real recovery or super clear error messages to the user. I always start with the simplest solution, which is just let the exceptions propagate up to the next level and let that code handle the exception. In this case, the code will become:

f = open(filename)
do_something_with_file(f) 

Specifically for files, you may want to sometimes close the file after you're done. In idiomatic Python, the 'with' statement is preferable to try-finally.

with open(filenam) as f: 
    do_something_with_file(f) 

Finally, multiple return statements are better than a deep hierarchy of if else statements and trying to keep track of a result variable that's returned in the end.

TAGS:

Python, optimization, simplify development


Comment and Contribute

 

 

 

 

 


(Maximum characters: 1200). You have 1200 characters left.

 

 

Sitemap
Thanks for your registration, follow us on our social networks to keep up-to-date