mardi 7 février 2023

refactor large if / elif/ else clauses

I'm working on a project which involves "building" a SQL.

As part of the build process - I often get to a point where one building method is taking into account a lot of boolean conditions (or flags) as part of its calculations.

This usually causes the method to look like a big if/elif/else tree (consider this obviously bad piece of code):

def build(a:bool, b:bool, c:bool, d:bool, e:bool):
    output = ...
    if a:
        if b:
            if c:
                pass  # mutate output
            else:
                pass  # mutate output

        else:
            if c:
                if d:
                    pass  # mutate output
                else:
                    pass  # mutate output
            else:
                if d:
                    pass  # mutate output
                else:
                    pass  # mutate output
    elif e or b:
        pass
    else:
        pass

    return output

My question to you is how would you refactor such code?

I'm looking for some kind design pattern or similar method which will make code:

  • more readable
  • support a case where now "build" should take into account a new flag (as long as the project progress we found new cases / features we would like to add to calculations).
  • will be easy to test

My project is written in python 3.8 - but I believe it's a general problem that may be relevant to any other programming language.

Aucun commentaire:

Enregistrer un commentaire