简体   繁体   English

Django接收器最佳做法

[英]Django receivers best practice

I am deciding how I would like to write my receivers. 我正在决定如何编写接收器。 I could do either of the following: 我可以执行以下任一操作:

  1. throw everything for one signal in one receiver 将所有信号一人扔在一个接收器中
  2. separate them intomultiple receivers for one signal for organizational purposes 将它们分成多个接收器,用于组织目的的一个信号

my question is: does it make a difference? 我的问题是: 有什么不同吗? If so, why? 如果是这样,为什么?

Option 1: 选项1:

@receiver(some_signal)
def do_it_all(sender, **kwargs):
    # do something for table 1
    # do something for table 2
    # do something for table 3
    #...

Option 2: 选项2:

@receiver(some_signal)
def do_it_for_one(sender, **kwargs):
    # do something for table 1
@receiver(some_signal)
def do_it_for_two(sender, **kwargs):
    # do something for table 2
@receiver(some_signal)
def do_it_for_three(sender, **kwargs):
    # do something for table 3
#...

Option 1 is clearly more DRY , but option 2 allows for more organization and readability , so they both have things going for them. 选项1显然更干燥 ,但是选项2允许更多的组织和可读性 ,因此它们都适合他们。 But the real question is, does it really matter? 但真正的问题是, 这真的重要吗?

In the end they'll both work. 最后,它们都将起作用。 However, over time, you may find that do_it_all becomes quite big and you'll end up splitting it into multiple functions anyway: 但是,随着时间的流逝,您可能会发现do_it_all变得很大,并且无论如何您最终都会将其拆分为多个函数:

@receiver(some_signal)
def do_it_all(sender, **kwargs):
    do_something_for_table_one(sender, **kwargs)
    do_something_for_table_two(sender, **kwargs)
    do_something_for_table_three(sender, **kwargs)

In that case it's not really different from option two. 在这种情况下,它与选择二并没有什么不同。

So I'd argue that the second approach leads to cleaner code in the end. 因此,我认为第二种方法最终可以使代码更简洁。 It also means you can test each receiver separately. 这也意味着您可以分别测试每个接收器。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM