Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Is it a bad practice writing long one-liner code?

Tags:

coding-style

I found myself keep writing pretty long one-liner code(influenced by shell pipe), like this:

def parseranges(ranges, n):
    """
    Translate ":2,4:6,9:" to "0 1 3 4 5 8 9...n-1"
               == === ==      === ===== =========
    """
    def torange(x, n):
        if len(x)==1:
            (x0, ) = x
            s = 1 if x0=='' else int(x0)
            e = n if x0=='' else s
        elif len(x)==2:
            (x0, x1) = x
            s = 1 if x0=='' else int(x0)
            e = n if x1=='' else int(x1)
        else:
            raise ValueError
        return range(s-1, e)
    return sorted(reduce(lambda x, y:x.union(set(y)), map(lambda x:torange(x, n), map(lambda x:x.split(':'), ranges.split(','))), set()))

I felt ok when I written it.
I thought long one-liner code is a functional-programming style.
But, several hours later, I felt bad about it.
I'm afraid I would be criticized by people who may maintain it.
Sadly, I've get used to writing these kind of one-liner.
I really want to know others' opinion.
Please give me some advice. Thanks

like image 471
kev Avatar asked Nov 06 '11 11:11

kev


2 Answers

I would say that it is bad practice if you're sacrificing readability.

like image 186
Mansoor Siddiqui Avatar answered Sep 21 '22 22:09

Mansoor Siddiqui


It is common wisdom that source code is written once but read many times by different people. Therefore it is wise to optimize source code for the common case: being read, trying to understand.

My advice: Act according to this principle. Ask yourself: Can anybody understand any piece of my code more easily? When the answer is not a 100% "No, I can't even think of a better way to express the problem/solution." then follow your gut feeling and reformat or recode that part.

like image 33
A.H. Avatar answered Sep 17 '22 22:09

A.H.