【发布时间】:2019-06-11 18:45:36
【问题描述】:
最佳实践建议一个方法或函数应该做一件事,并且做好,那么我该如何在以下场景中应用 SRP:
总结:我有一个发送 HTTP Post 请求的 API 包装器,但是为了提供 json,我想允许用户使用多个选项,假设我的函数可以接受以下任何一种:
def function_for_srp(jsonable_data: Union[Entity, Domain, str]):
# Pseudo code (Violation of SRP?)
if jsonable_data is instance of entity or domain:
jsonable_data = json.dumps(jsonable_data)
else do nothing, as its a json encoded string of data already
some_api_wrapper.post_data(jsonable_data)
这个函数根据传递给它的数据类型做很多事情,所以它违反了SRP?我如何以干净的方式克服这个设计问题,理想情况下我的想法是这样的:
def function_for_srp_using_entity(entity: Entity): pass
def function_for_srp_using_domain(domain: Domain): pass
def function_for_srp(json_encoded_data: str): pass
上面是“pythonic”吗? 有没有更好的方法?
# possible alternative?
def function_for_srp(jsonable_data: Union[Entity, Domain, str]):
json = some_other_function(jsonable_data)
some_api_wrapper.post_something(json)
# Is this still a violation?
def some_other_function(jsonable_data: Union[Entity, Domain, str]):
# Figure out the type and return a json encoded string that is suitable
if isinstance of entity/domain, json dump and return
else check if is valid json encoded string, if not make it valid and return it
【问题讨论】:
-
第二种方法有什么问题?
标签: python design-patterns single-responsibility-principle