-1

It is a simple code, what I am looking for is to learn the best practices that I can implement, when trying to refactor the show method, to a method that is closed to modifications. so that in the future if they ask me to enter a new card with a value of type chain, it is not necessary to modify this method.

class Card:
def __init__(self, suit, value):
    self.suit = suit
    self.value = value

def show(self):
    if self.value == 1:
        value = "Ace"
    elif self.value == 11:
        value = "Jack"
    elif self.value == 12:
        value = "Queen"
    elif self.value == 13:
        value = "King"
    else:
        value = self.value

    return f'{value} of {self.suit}'

2 Answers2

0

For me the code looks ok, but if you like, you could use a dictionary:

value = {1: "Ace", 11: "Jack", 12: "Queen", 13: "King"}.get(self.value,self.value)
Stef
  • 28,728
  • 2
  • 24
  • 52
  • but I would have to enter to modify the show method. – kmiiloberrio-dev Jul 10 '19 at 20:29
  • 1
    then the only way I see is to move the dictionary to the `__init__` method, but I don't see any real advantage in it (i.e. self.values = { ... } in `__init__` and then `value = self.values.get(self.value,self.value)` in `show` – Stef Jul 10 '19 at 20:32
0

You can emulate a switch-case statement with a dictionary:

def show(self):
    value = {
        1: 'Ace', 11: 'Jack',
        12: 'Queen', 13: 'King'
    }.get(self.value, self.value)

    return f'{value} of {self.suit}'

What’s happening here is that we are creating a mapping of card numerical value to card name. Immediately after creation of this object, we use the dict.get method to try and retrieve the corresponding name based on self.value. The second argument is a fallback to ensure if the lookup fails, we use the current value.

N Chauhan
  • 3,407
  • 2
  • 7
  • 21