Warning: file_get_contents(/data/phpspider/zhask/data//catemap/8/perl/9.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
Coding style 编写长的一行代码是一种糟糕的做法吗?_Coding Style - Fatal编程技术网

Coding style 编写长的一行代码是一种糟糕的做法吗?

Coding style 编写长的一行代码是一种糟糕的做法吗?,coding-style,Coding Style,我发现自己一直在写很长的一行代码(受shell管道的影响),如下所示: 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

我发现自己一直在写很长的一行代码(受shell管道的影响),如下所示:

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()))
我写的时候感觉还可以。
我认为长一行代码是一种函数式编程风格。
但是,几个小时后,我对此感到很难过。
我担心我会受到可能会坚持这一观点的人的批评。
遗憾的是,我已经习惯于写这种一行字了。
我真的很想知道别人的意见。

请给我一些建议。谢谢

如果牺牲可读性,我会说这是一种不好的做法。

第一个和第三个例子我可以接受。它们离应用程序域足够近,因此我可以很容易地看到代码的意图


第二个例子太聪明了。我甚至不知道它的用途。你能把它重写成五行吗,给变量取更长的名字?

大家都认为源代码只写一次,不同的人读了很多次。因此,为常见情况优化源代码是明智的:被阅读,试图理解


我的建议是:按照这个原则行事。问问自己:有人能更容易地理解我的代码吗?如果答案不是100%“不,我甚至想不出更好的方式来表达问题/解决方案。”然后按照你的直觉重新格式化或重新编码该部分。

除非性能是主要考虑因素,否则代码的可读性应该得到高度优先考虑。这对于它的可维护性非常重要

《计算机程序的结构和解释》一书中的相关引用


“程序应该是为人们阅读而编写的,只是为机器执行而编写的。”

第二个示例将
:2,4:6,9:
翻译为
0 1 3 4 5 8 9…n-1