doc.dev1x.org

Commandパターンを用いたSLA原則の適用

1. 目的

SLA原則に準拠したコードを書きたい

2. 課題

3. 解決策

処理のステップをコマンド化し、コマンドの羅列で処理のステップを表現する

関数間で共有されるデータはDTOを引き回す

class Dto:
    def __init__(value, want_exit = False):
        self.value = value
        self.want_exit = want_exit

4. メリット

SLA原則に則った抽象度

制御構造とビジネスロジックを分解できる

def exec(dto, *fns):
    buffer = dto
    for f in fns:
        buffer = f(buffer)
        if buffer.want_exit:
            return buffer
    return buffer
def f1(dto):
    dto.value = dto.value + 10
    return dto

def f2(dto):
    dto.value = dto.value + 40
    return dto

def f3(dto):
    dto.value = dto.value * 2
    return dto

5. デメリット

ロジックが分散するのでプログラムの理解が困難になる

6. 注意事項

処理フローが大きく変わるパラメータがある場合

参考資料

Appendix-1 ソースコード全体

class State:
    def __init__(value, want_exit=False):
        self.value = value
        self.want_exit = should_exit

def exec(state, *fns):
    buffer = state
    for f in fns:
        buffer = f(buffer)
        if buffer.should_exit:
            return buffer

    return buffer

def f1(state):
    state.value = state.value + 10
    return state

def f2(state):
    state.value = state.value + 40
    return state

def f3(state):
    state.value = state.value * 2
    return state


if __name__=="__main__":

    state = State(0, False)
    result = exec(
        state,
        f1,
        f2,
        f3
    )

    print(result.value)     # => 100