首页 > 解决方案 > 避免空值检查的架构解决方案

问题描述

史前史: 看下面的代码:

 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

在下面你可以看到客户端代码:

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

解释及问题:当我们没有adt_data时,业务状态是正常的,所以这个变量有时可以是None。直截了当的解决方案就是如果……”

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

并更正了客户端代码:

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

问题: 是否有任何典型的机制来避免这种if's?我读过关于 Null 对象模式的信息。可能存储库可能不会返回 None,而是返回一个带有空字段的对象?我想请教专家可能的解决方案。

标签: pythondesign-patternsarchitecture

解决方案


推荐阅读