缩进内联注释是个好做法吗?

2024-09-25 00:33:30 发布

您现在位置:Python中文网/ 问答频道 /正文

我发现自己在写一些复杂的算法代码,我尽我所能地对其进行注释,因为我真的不知道谁来维护这部分代码。
按照这个想法,我写了很多块和内联的注释,也尽量不做过多的注释。但是,当我回到一周前编写的代码时,我发现很难阅读,因为大量的注释,尤其是内联注释。 我认为将它们缩进(到~120char)可以简化可读性,但是根据样式标准显然会使行太长。在

以下是原始代码的示例:

fooDataTableOccurrence = nestedData.find("table=\"public\".")
if 0 > fooDataTableOccurrence:  # selects only tables without tag value "public-"
    otherDataTableOccurrence = nestedData.find("table=")
    dbNamePos = nestedData.find("dbname=") + 7   # 7 is the length of "dbname="
    if -1 < otherDataTableOccurrence:  # selects only tables with tag value "table="
        # database resource case
        resourceName = self.findDB(nestedData, dbNamePos, otherDataTableOccurrence, destinationPartitionName)
        if resourceName:  #if the resource is in a wrong path
            if resourceName in ["foo", "bar", "thing", "stuff"]:
                return True, False, False  # respectively isProjectAlreadyExported, isThereUnexpectedData and wrongPathResources
            wrongPathResources.append("Database table: " + resourceName)

下面是内联注释的缩进方式:

^{pr2}$

代码是用Python编写的(我公司的遗留代码并没有完全遵循PEP8标准,因此我们不得不坚持这一点),但是我的观点不是关于代码本身的清洁性,而是关于注释。我在寻找可读性和易于理解代码之间的权衡,有时我发现很难同时实现这两个目标

哪个例子更好?如果没有,会是什么?


Tags: 代码onlytables标准iftagtablepublic
1条回答
网友
1楼 · 发布于 2024-09-25 00:33:30

也许这是个XY嫒的问题?
这些评论能完全消除吗?在

下面是重构发布的代码的一个(快速和肮脏)尝试:

dataTableOccurrence_has_tag_public = nestedData.find("table=\"public\".") > 0

if dataTableOccurrence_has_tag_public:
    datataTableOccurrence_has_tag_table = nestedData.find("table=") > 0

    prefix = "dbname="
    dbNamePos = nestedData.find(prefix) + len(prefix)

    if datataTableOccurrence_has_tag_table:
        # database resource case
        resourceName = self.findDB(nestedData, 
                                   dbNamePos, 
                                   otherDataTableOccurrence, 
                                   destinationPartitionName)

        resource_name_in_wrong_path = len(resourceName) > 0

        if resourceNameInWrongPath:

            if resourceName in ["foo", "bar", "thing", "stuff"]:
                project_already_exported = True
                unexpected_data = False
                return project_already_exported, 
                       unexpected_data, 
                       resource_name_in_wrong_path

            wrongPathResources.append("Database table: " + resourceName)

进一步的工作可能涉及从代码块中提取函数。在

相关问题 更多 >