doc.dev1x.org

巨大ループ

1. 状況

ループの中で様々な処理が行われており、ループが巨大化している

2. 問題

保守性が低下する

3. 原因

プログラムの構造化不足

4. 対策

ループを分割する

def example(values):

    for v in values:
        if v['type'] == '001':
            #
            # なにかしらの処理
            #
        if v['type'] == '002':
            #
            # なにかしらの処理
            #
        if v['type'] == '003':
            :
            :
def example(values):

    type001_list = []
    for v in values:
        if v['type'] == '001':
            type001_list.append(v)

    for t1 in type001_list:
        #
        # 何かしらの処理
        #

    type002_list = []
    for v in values:
        if v['type'] == '002':
            type001_list.append(v)

    for t2 in type002_list:
        #
        # 何かしらの処理
        #

    type003_list = []
    for v in values:
        if v['type'] == '003':
            type001_list.append(v)

    for t3 in type003_list:
        #
        # 何かしらの処理
        #

ループ処理を関数/メソッドに切り出す

def example(values1, values2):
    result = []
    for v1 in values1:
        for v2 in values2:
            if v2["xxx"] == v1["xxx"]:
                #
                # 何かしらの処理
                #
    return result
def example(values1, values2):
    result = []
    for v1 in values1:
        result.append(inner_loop_function(v1, values2))
    return result

def inner_loop_function(item, value_list):
    result = []
    for v in value_list:
        if v["xxx"] == item["xxx"]:
            #
            # 何かしらの処理
            #
    return result

5. 注意事項

処理の目的を明確にすることが重要

6. 関連

参考資料