Pros and cons of using callbacks for domain logic in Rails

前端 未结 6 568
春和景丽
春和景丽 2021-01-30 04:50

What do you see as the pros and cons of using callbacks for domain logic? (I\'m talking in the context of Rails and/or Ruby projects.)

To start the discussion, I wanted

6条回答
  •  抹茶落季
    2021-01-30 05:02

    I really like using callbacks for small classes. I find it makes a class very readable, e.g. something like

    before_save :ensure_values_are_calculated_correctly
    before_save :down_case_titles
    before_save :update_cache
    

    It is immediately clear what is happening.

    I even find this testable; I can test that the methods themselves work, and I can test each callback separately.

    I strongly believe that callbacks in a class should only be used for aspects that belong to the class. If you want to trigger events on save, e.g. sending a mail if an object is in a certain state, or logging, I would use an Observer. This respects the single responsibility principle.

    Callbacks

    The advantage of callbacks:

    • everything is in one place, so that makes it easy
    • very readable code

    The disadvantage of callbacks:

    • since everything is one place, it is easy to break the single responsibility principle
    • could make for heavy classes
    • what happens if one callback fails? does it still follow the chain? Hint: make sure your callbacks never fail, or otherwise set the state of the model to invalid.

    Observers

    The advantage of Observers

    • very clean code, you could make several observers for the same class, each doing a different thing
    • execution of observers is not coupled

    The disadvantage of observers

    • at first it could be weird how behaviour is triggered (look in the observer!)

    Conclusion

    So in short:

    • use callbacks for the simple, model-related stuff (calculated values, default values, validations)
    • use observers for more cross-cutting behaviour (e.g. sending mail, propagating state, ...)

    And as always: all advice has to be taken with a grain of salt. But in my experience Observers scale really well (and are also little known).

    Hope this helps.

提交回复
热议问题