Search code examples
pythonheroku

What is the best practice to avoid code duplication on this code?


I have the following code snippets for a Flask application:

import flask import Flask


app = Flask(__name__)


@app.route('/')
def index():

    # Some code...

    on_heroku = 'DYNO' in os.environ
    if on_heroku:
        # Do something
    else:
        # Do something

    return ("SUCCESS", 200)


def open_browser():
    on_heroku = 'DYNO' in os.environ
    if on_heroku:
        # Do something
    else:
        # Do something


if __name__ == "__main__":
    open_browser()
    app.run(debug=True)

I find the on_heroku = 'DYNO' in os.environ and the checking of the value of on_heroku are written twice in the code.

How can I improve the code (e.g., passing on_heroku as a parameter?) such that the program can still run without problems?


Solution

  • Make it a standalone function:

    def check():
        on_heroku = 'DYNO' in os.environ
        if on_heroku:
            # Do something
        else:
            # Do something
    
    def index():
        check()
    def open_browser():
        check()
    

    Also you could do the environ check within the if statement instead of assigning.

    if 'DYNO' in os.environ:
        ...
    

    Or even just assign it once globally at runtime:

    on_heroku = 'DYNO' in os.environ
    
    # then run the rest of the program