Skip to content
Advertisement

Using __init__ method to call class main functionality

I needed to encapsulate functions related to single responsibility of parsing and emiting messages to API endpoint so I have created class Emitter.

JavaScript

In order to emit a message I call a short-lived instance of that class with message passed as argument to __init__.

JavaScript

__init__ itself directly runs all necessary methods to parse and emit message. Is it correct to use __init__ to directly run the main responsibility of a class? Or should I use different solution like creating function that first instantiates the class and then calls all the necessary methods?

Advertisement

Answer

It looks like you’re attempting to do the following at once:

  1. initialize a class Emitter with an attribute message
  2. parse the message
  3. emit the message

IMO, a class entity is a good design choice since it allows granular control flow. Given that each step from above is discrete, I’d recommend executing them as such:

JavaScript

You will need to redesign your class to the following:

JavaScript

Also, your parse_message() method could be converted to a validation method, but that’s another subject.

Advertisement