Light Mode
Dark Mode
How to refactor to not use cascading returns?

This has been a problem I've had in other projects, and I'm wondering if anyone can give me feedback on how to design/refactor this code so that it doesn't rely on a structure like this?

def checkio(game_result):
winner = verticalWinner(game_result)
if (winner != "."):
    return winner

winner = horizontalWinner(game_result)
if (winner != "."):
    return winner

winner = diagonalWinner(game_result)
if (winner != "."):
    return winner

return "D"

def horizontalWinner(game_result):
    for row in game_result:
        if (row[0] == row[1] == row[2] != '.'):
            return row[0]
    return "."

def verticalWinner(game_result):
    for i in range(3):
        if (game_result[0][i] == game_result[1][i] == game_result[2][i] != '.'):
            return game_result[0][i]
    return "."

def diagonalWinner(game_result):
    winner = diagonalSW(game_result)
    if (winner != "."):
        return winner

    winner = diagonalNW(game_result)
    if (winner != "."):
        return winner

    return "."

def diagonalSW(game_result):
    if (game_result[2][0] == game_result[1][1] == game_result[0][2] != '.'):
        return game_result[2][0]
    return "."

def diagonalNW(game_result):
    if (game_result[0][0] == game_result[1][1] == game_result[2][2] != '.'):
        return game_result[0][0]
    return "."
Created: Aug. 14, 2015, 3:38 a.m.
Updated: Feb. 8, 2016, 3:33 a.m.
1
12
User avatar
resilience