Code Optimization: If-Less Programming

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 = Trueelse:result = FalseThis 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:continuemsg = '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')raisedo_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.

Share the Post:
Share on facebook
Share on twitter
Share on linkedin

Overview

The Latest

your company's audio

4 Areas of Your Company Where Your Audio Really Matters

Your company probably relies on audio more than you realize. Whether you’re creating a spoken text message to a colleague or giving a speech, you want your audio to shine. Otherwise, you could cause avoidable friction points and potentially hurt your brand reputation. For example, let’s say you create a

chrome os developer mode

How to Turn on Chrome OS Developer Mode

Google’s Chrome OS is a popular operating system that is widely used on Chromebooks and other devices. While it is designed to be simple and user-friendly, there are times when users may want to access additional features and functionality. One way to do this is by turning on Chrome OS

homes in the real estate industry

Exploring the Latest Tech Trends Impacting the Real Estate Industry

The real estate industry is changing thanks to the newest technological advancements. These new developments — from blockchain and AI to virtual reality and 3D printing — are poised to change how we buy and sell homes. Real estate brokers, buyers, sellers, wholesale real estate professionals, fix and flippers, and beyond may