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.