lundi 17 février 2020

Python, Deal with nulls

Prehistory: This question is not about python, it is about architecture. See at the code below:

 class Adt:
    # here is constructor with dependencies like repository, doc_gen client etc., i just avoid it

    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 is client for that 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) # **<- adt_data may be null**
if not adt_data:
    return None

And then i must correct client like this:

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

Question: Is there any known mechanism how 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.

Aucun commentaire:

Enregistrer un commentaire