# Coding simplicity

posted: May 12, 2016

tl;dr: KISS: Keep It Simple, Stupid

Here’s the task: write a function f which takes in two numbers and prints “The answer is: ” followed by the sum of the two numbers.

Solution A:

def f(a, b):
print('The answer is:', a + b)

Solution B:

def f(*args):

Question: for a production software environment, which is the better solution?

The answer is A, for the following reasons:

• It is much more readable, and should be instantly understandable by anyone with an even rudimentary knowledge of Python. In fact, if you show it to a non-programmer they are likely to be able to tell you what it does.
• It is cleaner code. It uses fewer punctuation symbols: (),:'+ versus ()*:'{}. (6 symbols instead of 8). B also uses three symbols in their secondary roles: * is most often used for multiplication, and {} are most often used for dicts, but here they perform different roles. One of the driving forces behind the Python language is to make it easier to read by minimizing punctuation; Perl takes the opposite approach, and hence has a reputation for obfuscation.
• It is more maintainable. If the original author moves on, an entry-level programmer can easily maintain Solution A and extend it if needed.
• It is more likely to be correct. It is more likely that the author of A got it right the first time that they coded and ran it. In the future, when there is a bug in a large codebase containing this function, someone trying to find the source of the bug will read through A and quickly understand what it does, and move their attention elsewhere.
• It was faster to code. The author of A almost certainly spent less time writing and debugging it than the author of B, and hence the author of A was able to move on to tackle other tasks that needed to be done on the project. Perhaps the biggest benefit of Python is developer productivity, but it requires the right mindset to maximize that benefit.

The only advantage of B is that it is already handles a case which may arise in the future, namely needing to add more than 2 numbers together. But that case may never arise. Even if it does, it is easy to modify A to extend it to handle more numbers. A can be changed it into B if (and only if) it must handle a variable number of arguments. The author of B spent time upfront optimizing B for extensibility; given the assigned task, B is an example of premature optimization.

Write for readability --- KISS: Keep It Simple, Stupid --- Elegant simplicity --- import antigravity

With experience comes an appreciation for simplicity

Other views:

Write dumb code

Why senior devs write dumb code