ruby on rails - Is that a proper way to refactor ActiveRecord fat models? -
if example i've activerecord model:
app/models/order.rb
class order < activerecord::base # model logic end require "lib/someclass.rb"
lib/somelass.rb
class order before_save :something # more logic here end
is way refactor/extract logic model? or maybe use concern class, service class or else?
like told me long time ago:
code refactoring not matter of randomly moving code around.
in example doing: moving code file
why bad?
by moving code around this, making original class more complicated since logic randomly split several other classes. of course looks better, less code in 1 file visually better that's all.
prefer composition inheritance. using mixins asking "cleaning" messy room dumping clutter 6 separate junk drawers , slamming them shut. sure, looks cleaner @ surface, junk drawers make harder identify , implement decompositions , extractions necessary clarify domain model.
what should then?
you should ask yourself:
- which code goes , part of new class / module ?
- where makes sense extract code somewhere else ?
- do have piece of code shared across application ?
- can extract recurrent patterns in code base ?
extract service object
i reach service objects when action meets 1 or more of these criteria:
- the action complex
- the action reaches across multiple models
- the action interacts external service
- the action not core concern of underlying model
- there multiple ways of performing action
extract form objects
when multiple model can updated a single form submission, might want create form object.
this enable put form logic (name conventions, validations , on) 1 place.
extract query objects
you should extract complex sql/nosql queries own class. each query object responsible returning result set based on criterias / business rules.
extract presenters / decorators
extract views logic presenters. model should not deal specific views logic. moreover, enable use presenter in multiple views.
thanks this blog post me putting these together.
Comments
Post a Comment