- Try to keep your methods short. Following the Single Responsibility Principle helps here.
- Use descriptive variable, method, and parameter names (this goes back to “communicating your intent”).
So, favour method names like calculate_taxes over do_calcs, and variable names like subtotal over value or x.
- You can create self-documenting code by replacing complex logic/statements with a well-named method call.
So, instead of:
stripped_html = data.gsub(/<\/?[^>]*>/, ”)
You can use:
stripped_html = remove_html_tags(data)
It may not be the best example, but here’s the point: even though you’re assigning to a pretty descriptive variable name (stripped_html), replacing the regex with a descriptive method name makes the line read almost like a comment. This helps you resist the urge to comment the regex. :)
Also, as a bonus, even if you didn’t give your variable a descriptive name, the descriptive method call still makes the line quite clear:
data = remove_html_tags(data)
See? The data variable doesn’t mean much here since it’s out of context, but the method call still gives you a pretty good idea of what’s going on, and even what sort of data is in the variable.
Of course, you’re still communicating your intent with a well-named variable and the regex, but the second and third ways are more clear, in my humble opinion at least.
But don’t go crazy with this one, you don’t have to replace every somewhat complex operation with a method call. Use your judgement.
Anyway, those are just some thoughts, I hope they help someone. I believe I got most or all of this from reading Russ Olsen’s Eloquent Ruby. Highly recommended.
Have any other tips or advice? Feel free to post it in the comments. It would be great to collect a bunch of this stuff and turn it into a blog post.