python - 避免空值检查的架构解决方案
问题描述
史前史: 看下面的代码:
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,而是返回一个带有空字段的对象?我想请教专家可能的解决方案。
解决方案
推荐阅读
- javascript - 增加数组内对象的计数
- python - Python tkinter - 克隆根窗口属性并将它们应用于顶级窗口
- magento - 表单未在 magento 1.9.0.1 上提交,提交时出现 404 错误页面
- regex - 如何连接具有相同名称开头的文件?
- javascript - 如何实现循环额外条件
- asp.net-mvc-4 - mvc5中年龄之间的数据收集
- javascript - 将标头作为参数传递给 javascript 发布请求 (react-native)
- laravel - Laravel:将异常从 try/catch 块传递给处理程序
- python - 在 Python 3.7 中进行 Web 抓取时出现 HTTP 404 错误
- django - 使 STATIC_ROOT 依赖于域