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):
    print('The answer is: {}'.format(sum(args)))

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

The answer is A, for the following reasons:

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