When to use Modules / Concerns?

An article, posted about one year ago filed in ruby, rails, ruby on rails, service, architecture, when to use & modules.

Whenever your model gets too heavy?

The easiest way to clean up your classes might be to create smaller, more concise methods. The next easiest way of tiding up your models is moving stuff to modules (whether they are ‘Concerns’ or not). Modules can then be included in the final classes. It will lead to a crowded list of methods exposed on these classes, for which alternative solutions exist (Presenters, Decorators), but if you shield off private methods nicely and have a consistent way of naming things, I wouldn’t be too concerned about that. Note that having many modules used in only a single class might be a code smell: perhaps you’re trying to do too much with that single class.

Concerns or Modules?

When you’re using Rails, you can make use of Concerns. They offer a few advantages over traditional modules, so use it whenever you’re bothering recreating the same behaviour using plain old ruby Modules. I prefer consistency, so if you’ve adopted Concerns, use concerns everywhere.

Why not use modules (or concerns)?

Well, Richard Schneeman wrote an interesting article on this: “When to be concerned about concerns” And the tl;dr: when you are extracting logic from classes to a concern (or module), you may make it harder to read and debug the code, and worse: code might interact between modules. So something to bear in mind. The alternative: Extract it into smaller classes.

Op de hoogte blijven?

Maandelijks maak ik een selectie artikelen en zorg ik voor wat extra context bij de meer technische stukken. Schrijf je hieronder in:

Mailfrequentie = 1x per maand. Je privacy wordt serieus genomen: de mailinglijst bestaat alleen op onze servers.