初期的簡單資料,日後可能會出現對它的多種操作,這時替換它們成為一個新類別。
乍看之下可能不必要也沒什麼,但對程式的基礎影響可能超乎想像。

Replace Primitive with Object

# Before
email = "john.doe@example.com"
if "@example.com" in email:
    print("Email is from example.com")

# After
class Email:
    def __init__(self, address):
        self.address = address

    def is_from_domain(self, domain):
        return domain in self.address

email = Email("john.doe@example.com")
if email.is_from_domain("@example.com"):
    print("Email is from example.com")