Back to Blog

Programming Principles Worth Sharing

June 6, 2024
2 min read
ProgrammingRules

There are only really two principles that I think are worth heeding when writing code.

  1. No rule is absolute. There will always be examples where going against the common wisdom is necessary, and often there's a trade-off in doing so. But, you should be sure you don't violate the next principle.
  2. Only break a rule if you understand the rule.

Examples: When "Pythonic" Code Isn't Better

Take the rule "Prefer list comprehensions instead of loops":

# Following the rule:
results = [process(x) if complex_condition(x) else fallback(x) for x in items if filter_condition(x)]

# Breaking the rule:
results = []
for item in items:
    if not filter_condition(item):
        continue
    
    if complex_condition(item):
        results.append(process(item))
    else:
        results.append(fallback(item))

The explicit loop makes the logic much clearer despite being "less Pythonic". This makes it easier for reviewers and for anyone that needs to debug or edit this code in future. However, the trade-off here is you lose the benefits of the comprehension: List comprehensions are faster than regular for loops because of how Python compiles them. Generally, (although in my opinion, not in this case) they're also more concise.

So, it ultimately depends what you're trying to optimise for when writing the code - compatibility with other developers, i.e. making the code you write more readable and digestible, or squeezing the last drop of performance out of your code (if the latter matters, I probably wouldn't be using Python anyway, but that's another topic!). It may even be that you want to apply this rule in one file but not another within the same codebase, dependent on the factors at play. It all comes down to choosing the right logic for the problem at hand - and that's sometimes the trickiest part of programming!