J. Wood
J. Wood

Reputation: 11

OOP: Using conditional statement while initializing a class

This question geared toward OOP best practices.

Background:

I've created a set of scripts that are either automatically triggered by cronjobs or are constantly running in the background to collect data in real time. In the past, I've used Python's smtplib to send myself notifications when errors occur or a job is successfully completed. Recently, I migrated these programs to the Google Cloud platform which by default blocks popular SMTP ports. To get around this I used linux's mail command to continue sending myself the reports.

Originally, my hacky solution was to have two separate modules for sending alerts that were initiated based on an argument I passed to the main script.

Ex:

$ python mycode.py my_arg

if sys.argv[1] == 'my_arg':
    mailer = Class1()
else:
    mailer = Class2()

I want to improve upon this and create a module that automatically handles this without the added code. The question I have is whether it is "proper" to include a conditional statement while initializing the class to handle the situation.

Ex:

Class Alert(object):
    def __init__(self, sys.platform, other_args):

         # Google Cloud Platform
         if sys.platform == "linux":
              #instantiate Class1 variables and methods

         #local copy
         else:
              #instantiate Class2 variables and methods

My gut instinct says this is wrong but I'm not sure what the proper approach would be.

I'm mostly interested in answers regarding how to create OO classes/modules that handle environmental dependencies to provide the same service. In my case, a blocked port requires a different set of code altogether.

Edit: After some suggestions here are my favorite readings on this topic.

http://python-3-patterns-idioms-test.readthedocs.io/en/latest/Factory.html

Upvotes: 1

Views: 2191

Answers (2)

Franz
Franz

Reputation: 11553

This seems like a wonderful use-case for a factory class, which encapsulates the conditional, and always returns an instance of one of N classes, all of which implement the same interface, so that the rest of your code can use it without caring about the concrete class being used.

Upvotes: 1

bharat nc
bharat nc

Reputation: 127

This is a way to do it. But I would rather use something like creating a dynamic class instance. To do that, you could have only one class instead of selecting from two different classes. The class would then take some arguments and return the result depending the on the arguments provided. There are quite some examples out there and I'm sure you can use them in your use-case. Try searching for how to create a dynamic class in python.

Upvotes: 0

Related Questions