While developing some functionality, sometimes we take shortcuts to finish it on scheduled delivery time. We give less time on code standards and more on functionality. But with code growth we have perfect opportunity to clean our code and follow the standards. Refactoring is the practice to improve our coding style without changing the external functionality. Refactoring code can also boost performance sometimes. A good coding practice helps others to understand the functionality easily. Practicing it improves your code writing over time.
Proper code indentation makes it easy to understand. Too much nested code can be difficult to understand if not properly indented. Two spaces per indentation level is the Ruby community standard.
We can also put short comments wherever necessary. A short comment with a method can explain the functionality. Too many comments increases the file size.
One of the most important principles in ROR is convention over configuration. The more we follow the convention, less changes are required to run over application properly. Naming of variables, classes, methods should be as per guidelines. Class and Modules have camelcase style (ex: UserReview). Variable and methods name should be self explanatory. Long name can be written in snake case. date_of_birth is a valid long variable name.
Breaking long method:
Long methods increases complexity and are very hard to debug. As per standards one method should have single responsibility. Long methods can be extracted out into multiple methods. It makes it easily to understand the flow and reduces complexity. Also debugging short methods is quite easy.
Class provides abstraction to the code. One class should handle one responsibility. Long classes can be split into multiple classes. We can use inheritance wherever necessary. Also code can be separated in modules which can be mixed in multiple classes.
Module prevents name collision and provide mixin functionality. Modules can be used to separate functionalities. Fat code from model can also be extracted out in concerns.
Proper use of partials can also reduce the code duplicity. DRY (dont repeat yourself) principle tells not to repeat code. In new and edit form we can use same partial.
Fat model skinny controller:
Controllers are meant to handle requests, so the controllers should have less code. Business logic should be kept in models. We can also use rails concern to extract out heavy load from classes.
Views are meant to present data. Logic should not be kept in views(ex: database queries). We can use helper modules to deal with the logic or use presenters.
In our next tutorial we will learn using persenters and decorators pattern.