2

Prehistory: Look at the code below:

 class Adt:
    # I avoided constructor with dependencies 

    def generate_document(self, date_from, date_to):
    try:
        adt_data = self.repository.read_adt_data(date_from, date_to) # **<- adt_data may be null**
        document_body = self.__prepare_document_body(adt_data )
        doc_id = self.__generate_document(document_body)
        return doc_id
    except Exception:
        self.logger.exception("generate_document")
        raise

And below you can see client code:

doc_id = adt.generate_document(date_from,date_to)
email_sender_client.send_document_as_email(doc_id)

Explanation and problem: There is normal business state when we do not have adt_data, so this variable sometimes can be None. Straightforward solution is just to put if..."

adt_data = self.repository.read_adt_data(date_from, date_to)
if not adt_data:
    return None

And corrected client code:

doc_id = adt.generate_document(date_from,date_to)
if doc_id:
   email_sender_client.send_document_as_email(doc_id)

Question: Is there any typical mechanism to avoid such if's? I've read about Null object pattern. Probably repository could return not None, but an object with empty fields? I want to ask experts about possible solutions.

  • Check if https://stackoverflow.com/questions/4978738/is-there-a-python-equivalent-of-the-c-sharp-null-coalescing-operator – Vipul Feb 17 '20 at 14:20
  • Hi Vipul, thanks for comment! That was a good solution for null check operation. I am looking something more than just null check. I want to use some more complex and more general solution to deal with nulls. – Aleksandr Beliavski Feb 17 '20 at 15:02

0 Answers0