HiveBrain v1.2.0
Get Started
← Back to all entries
patternpythonMinor

Refactoring huge if..elif in __init__ how?

Submitted by: @import:stackexchange-codereview··
0
Viewed 0 times
refactoring__init__elifhugehow

Problem

I have this huge __init__ method which I want to clean up even more after watching Clean Coders videos (content of Clean Code book by Robert Cecil Martin).

How could I get refactor the gigantic if..elif block in a nice, readable way? Or should I leave it as it is? Do you find it readable?

```
@total_ordering
class Range:
"""Parses a poker range (str) into tuple of Combos (or Hands)."""

def __init__(self, range=''):
self._pairs = set()
self._suiteds = set()
self._offsuits = set()

for token, value in _RegexRangeLexer(range):
if token == 'ALL':
for card in itertools.combinations('AKQJT98765432', 2):
self._add_offsuit(card)
self._add_suited(card)
for rank in 'AKQJT98765432':
self._add_pair(rank)

# full range, no need to parse any more token
break

elif token == 'PAIR':
self._add_pair(value)

elif token == 'PAIR_PLUS':
smallest = Rank(value)
for rank in (rank.value for rank in Rank if rank >= smallest):
self._add_pair(rank)

elif token == 'PAIR_MINUS':
biggest = Rank(value)
for rank in (rank.value for rank in Rank if rank = smallest)

for rank1 in first_ranks:
second_ranks = (rank for rank in Rank if rank < rank1)
for rank2 in second_ranks:
if token != 'X_OFFSUIT_PLUS':
self._add_suited(rank1.value + rank2.value)
if token != 'X_SUITED_PLUS':
self._add_offsuit(rank1.value + rank2.value)

elif token in ('X_MINUS', 'X_SUITED_MINUS', 'X_OFFSUIT_MINUS'):
biggest = Rank(value)
first_ranks = (rank for rank in Rank if rank <= biggest)

for rank1 in

Solution

Typically massive if elifs are equivalent to a switch statement. Python doesn't have switch statements and instead relies on dicts.

I would have a dictionary of str: function, which would break up the huge method and avoid the huge if elifs.

As an aside, many of these blocks are very closely related, often only the list in the for loop is different (xxx_plus and xxx_minus). It would be nice if that could be factored out into a single method, with an arg to say how the list should be created.

Context

StackExchange Code Review Q#60814, answer score: 3

Revisions (0)

No revisions yet.