Eloquent code needs no comment
Yesterday, I was reviewing the following code :
class Invoice::ResellerJob < ApplicationJob def perform # Do nothing if we are not the first of the month return unless Date.today.day == 1 # Generate monthly invoices User.billed_monthly.each do |user| # ... end # Do nothing if we are not on the first day of the year return unless Date.today.month == 1 # Generate yearly invoices User.billed_yearly.each do |user| # ... end end end
Comments are often a tell that the code could be more explicit. Every time I write a comment, I refactor my code to be understandable without it. Furthermore, it requires to read all the lines of code to understand what this class does. Here is a version that should be more eloquent:
class Invoice::ResellerJob < ApplicationJob def perform bill_monthly bill_yearly end def bill_monthly return if Date.today.day != 1 User.billed_monthly.each do |user| # ... end end def bill_yearly return if Date.today.month != 1 || Date.today.day != 1 User.billed_yearly.each do |user| # ... end end end
Reading the 2nd version is quicker because you only have to scan the method names to understand what it does. Moreover, the return conditions are evident thanks to the method names above. Write the code the way you would like to read it in the future ;-)
If you like this article, you might also like my Ruby on Rails monitoring service.