Three code-style tips for the budding Ruby Developer
During the last meetup, we had an interesting talk where some of the advanced developers passed on a bunch of great development advice to the beginners. In this post, I wanted to add in one more group of tips for the newer developers.

Other than Kent Beck’s advice to “communicate your intent through your code,” if I had to list only three pieces of advice that would help a newer Ruby Developer write code more like a Rubyist (rather than a Java / C++ / C# developer), I’d suggest the following:

(Note: Please feel free to post a comment if you have any advice to add, or if you disagree with any of this.)

  1. Try to keep your methods short. Following the Single Responsibility Principle helps here.



  2. 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.



  3. 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.

  1. ottawaruby posted this