Have you ever considered about using class inheritance or modules while coding? So, when do we decide to use inheritance instead of module?
Coding design is just about arranging code in our application. Hence, we have so many ways to arrange our code. Normally, we put a bunch of code into class. We move the methods to private area though. The amount of code is still there, no less.
If you face that situation, it’s time to export your code to somewhere outside of this class. There are two ways to do that:
- Export code to new class. We put them to the existing class or creating a new one.
- Dependencies.
- Inheritances.
- Export code to module.
In order to export code to other classes. They might be the separate classes or the ones which inherited this class. We make it basing on the logical relations among of them, the assets they will share to each other. We would try to follow DRY pattern.
We choose to export code to modules if these methods are independent. We can understand that they are the groups of methods. Hence, module name is group name. And these groups can be mixed into any classes. These methods can be mixed into any objects. Thus, we allow different classes to play a common role using a single set of code.
When we plug a module to an object, there will be an automatic delegation. However, we need to be noticed that we couldn’t mix methods messily. We need to do it carefully basing on the single responsibility pattern. The logic of code should be clear, independent and reusable. At first glance, when we look at our code through the name of classes, modules and methods, we know exactly what they do, which responsibility they take.
In ruby, the methods of the last included module are encountered first in lookup path. We notice this to know the impact of code when we include or extend code.
There are a ton of patterns and antipattern which will help us to arrange our coder better.
To recap, whenever objects that play a common role, we let them share behavior via module.