Code Optimization: If-Less Programming

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:
Heading photo, Metadata.

What is Metadata?

What is metadata? Well, It’s an odd concept to wrap your head around. Metadata is essentially the secondary layer of data that tracks details about the “regular” data. The regular

XDR solutions

The Benefits of Using XDR Solutions

Cybercriminals constantly adapt their strategies, developing newer, more powerful, and intelligent ways to attack your network. Since security professionals must innovate as well, more conventional endpoint detection solutions have evolved

AI is revolutionizing fraud detection

How AI is Revolutionizing Fraud Detection

Artificial intelligence – commonly known as AI – means a form of technology with multiple uses. As a result, it has become extremely valuable to a number of businesses across

AI innovation

Companies Leading AI Innovation in 2023

Artificial intelligence (AI) has been transforming industries and revolutionizing business operations. AI’s potential to enhance efficiency and productivity has become crucial to many businesses. As we move into 2023, several

data fivetran pricing

Fivetran Pricing Explained

One of the biggest trends of the 21st century is the massive surge in analytics. Analytics is the process of utilizing data to drive future decision-making. With so much of

kubernetes logging

Kubernetes Logging: What You Need to Know

Kubernetes from Google is one of the most popular open-source and free container management solutions made to make managing and deploying applications easier. It has a solid architecture that makes