pythonsolid-principlesopen-closed-principle

Open closed principle implementation python


I have case like based on a type send email to different platform (this is sample use case)

So I have done below so far

from abc import ABC, abstractclassmethod
import json

class Email(ABC):
    @abstractclassmethod
    def sendEmail(self):
        pass

class Gmail(ABC):
    def sendEmail(self):
        # some implementation
        return "Sent to gmail"
    
class HotMail(ABC):
    def sendEmail(self):
        # some implementation
        return "Sent to hotmail"


def lambda_handler(event, context):
    info =  json.loads(event['body'])

    mail_platform = info['type'] # this will be gmail or hotmail
    if mail_platform == 'gmail':
        mail = Gmail()
        mail.sendEmail()
    elif mail_platform == 'hotmail':
        mail = HotMail()
        mail.sendEmail()

Problem is whenever there is new email platform (yahoo for example) I have to add another elif in lambda code. Is there better way to handle this?


Solution

  • You can put supported classes inside a dictionary and treat them as any other variable, getting proper class based on a key from dictionary:

    def lambda_handler(event, context):
        info =  json.loads(event['body'])
        types = {'gmail': Gmail, 'hotmail': HotMail}
        mail = types[info['type']]()
        mail.sendEmail()