r/rails • u/Renaissir • May 14 '14
Commenting My Code -- Best Practices?
I used to comment extensively when I worked in Java, but have fallen into the bad habit of commenting less in Rails. In Java, I had a standardized way of commenting every class/method/program that I learned from my teachers, but never had the same experience in Ruby/Rails, and my comments have been fairly haphazard.
I'm looking to clean up my practices and fully comment the app I'm working on so that it'll be more legible to other people. My questions to you all:
What are your commenting best practices?
Are there standardized ways of commenting a model, a controller, etc?
How much do you dev-comment your views?
Got any links to excellent commenting?
BONUS: Where does RDoc figure into all of this? Is it a replacement for commenting your methods, classes, etc? How does it fit into your workflow? I guess I'm just not fully understanding it.
1
u/Ronald-Ray-Gun May 15 '14
What I find is that writing comments for standard rails methods seems really redundant.
# Index page
def index
puts "index"
endThe code above looks pretty dumb. But once you start writing methods that do require explanation, it's nice to have a comment structure set.
# Send data and get response for important thing
def custom_method
stuff = params[:stuff].join(', ').downcase
# Use service object
response = MyServiceObject.new.my_method(stuff)
JSON.parse(response)
endIn my opinion, the above method is helped by commenting and you're not leaving it up to the next developer to figure out what it's doing.
So, I like to keep my comments consistent across methods that may or may not need to be explained. This just looks better to me visually. It will also give the next person a good hint that they should follow the same structure. i.e. "there's only comments in some places... I guess I'll just not comment"
1
u/Renaissir May 15 '14
Thank you -- everything you're saying is so obvious and yet I've been fighting it this whole time. I've been oscillating between the comment-nothing-because-this-is-a-solo-project and the obsessively-compulsively-comment-everything-for-posterity ends of the spectrum.
It sounds like I just need to chill out.
95% of my controller and model methods are well-named, and I've broken them up to accomplish discrete tasks. The code reads well and commenting really isn't such a huge issue. I'll go back through, clean up and comment the more complex stuff, and sleep easy.
Cheers to sanity on the internet.
1
u/TheMoonMaster May 15 '14
# Use service objectis a horrible comment in my opinion. No duh you'r e using a service object. Even then the class name is right there which makes it super easy to do a quick grep for the file or class name.Even then, why comment when you could name things better?
def send_stuff_to_thirdparty stuff = params[:stuff].join(', ').downcase service = MyServiceObject.new(stuff).send JSON.parse(service.response) endI named things slightly differently but it's less lines of code, and more context without having to read comments.
1
u/Ronald-Ray-Gun May 16 '14
Yeah, true. Ruby itself is really meant to be human readable like that. i.e. good ruby == less comments. Still, you can only be so descriptive in method names.
2
u/aharpole May 15 '14
I personally will avoid commenting except for exceptional cases (like if my code does something weird to get around a library bug)
In Ruby, it's incredibly easy (and advisable) to write code that does a very good job of expressing its intent. My team are pretty strict about not keeping old commented out code around (it's in source control if you need it later).
I also am quite liberal in using the Git commit messages to discuss reasoning behind why I used a certain approach. That's especially useful if the code the decision applies to spans several files.
I'm fond of Rails's default of putting the HTTP verb and path in the comment preceding the controller action.
If you want to nicely document your app's behavior, that's where your RSpec suite comes in. You can run it with the --documentation flag on and it will print out a nice little outline document describing what your app is supposed to do.
Most of these practices I've adopted from other Rubyists I respect, so I expect they're fairly widely adopted, but ultimately do what works for you, not just what will make you fit in the best.
2
u/csfreestyle May 15 '14
A wise man, and much better programmer, once told me "over time, comments lie." If you're working with a team of developers, and you put a comment on line 9 that documents the logic on line 10, you can count on the contents of line 10 eventually being changed without line 9 being updated to reflect it. Instead, aim to make the comment unnecessary in the first place.
If your methods are concise, properly decoupled, and have logical, communicative names (and variable/argument names to match), I believe that you typically won't need comments at all.
At the risk of making one of those sweeping internet generalizations (the kind I usually mock), TODOs are about the only time I use comments anymore.
TL;DR: You shouldn't need to comment much, because "clean code should read like well-written prose."
3
u/TheMoonMaster May 14 '14
I don't comment my code unless it's for documentation or if it's something that is unavoidably complicated and needs to be explained context wise.
I don't write documentation unless it's for a public facing app.
2
u/stikitodaman May 15 '14
I'm of the same opinion. One should strive for self documenting code. One big thing with this is to name your methods well. If your code is complex enough that you are turning to comments, then that should be a sign to refactor for clarity.
2
u/Arjes May 15 '14
Just to chime in with a +1. If you can't look at it an figure out its purpose. Refactor it.
Specs also help greatly in clearing it up.
1
u/jdickey May 16 '14
I write doc for APIs or for where a new reader of the code might get confused, and I can't think of a clearer way to write the code.
If you're comfortable with Knuth, or even with Sandi Metz, you probably don't write much doc anyway. Your code is in a clear, concise yet literary tone and should need little documentation to be understood by even a decent apprentice-level developer.
1
u/pr0misc May 16 '14
Ruby is pretty idiomatic. If you feel the urge to comment, probably you must split the method :D
http://robots.thoughtbot.com/sandi-metz-rules-for-developers
1
u/WalkerMidwestRanger Jan 09 '24 edited Jan 09 '24
Time marches on and, I think Metz (and Matz) are right but nobody is splitting up shit for nothing, or naming things well without using 30+ characters.
I like to leave my implementation with bare-minimum comments but put any details in the tests. That way, the good to know is in the practical, testing environment, and the must know is in the actual code or the code will raise when given unworkable inputs. Maybe things are different now, but what I've found is that creating a class feels like killing a sacred cow. For Metz, hesitating to create a class (in Ruby) is a ridiculous idea and it is ridiculous but people think that, like, "oh no, a class, in a namespace and all contained and stuff." It's a difficult argument for me to imagine because its so easy in Ruby and so hard in C, by comparison.
The same people never shut up about "Namespacing" but then you just do it and they're upset its just defining a class in another class or module. Are they upset its as free as the air you breathe?
Just today, I made a class to correct a rubocop ABC rule violation in a method. All the stuff that class does was once in a method in the model and didn't really set my alarms off but instead of do the comment the shit out routine, I just made a class to implement that method. I defined it right at the bottom of the model so now its, NobodyCares::DoesThatThing. Inside NobodyCares, its instantiated with DoesThatThing.new(whatever:) and then .run! is called and rubocop didn't complain. Whoever reviews this won't know that's why the class was made, I don't think it matters and I think a class is a fine replacement for a bloated method. Time will tell.
Long story short, people should probably leave more comments. Especially when they speak directly to future programmers. Things need to get done so there is always an opportunity for cruft. There are bad actors who are happy to make everything so difficult they're indispensable. There are also caring, overwhelmed people that can't get enough leverage to turn over a confusing project.
Given all that, I think the idea you should write self-documenting code is a big ask because many places, you'll be told not to leave comments but discouraged from writing small classes.
Some places, you can't even do either.
0
u/th12eat May 14 '14
I'm actually in the same need of advice. I just started work in January at a Ruby/Rails shop and they don't currently use much in the way of documentation.
For what it's worth, the guy I'm learning from told me to devote less time worried about how/when to document my code and more time fully utilizing the convention of Rails (remember, convention over configuration). I was so used to programming and adding js tags above my functions, etc... but, with Ruby/Rails, your program should speak for itself.
Since January, my Ruby/Rails skills have seriously improved. So much so that I've had to redo portions of past code to be more legible (mind you, they were perfectly fine on their own but... they just didn't look right! (It irked me if I couldn't immediately know why I did what I did)). I changed stuff like:
if object.id == 567
<content>
endto
if object.id.eql?(567)
<content>
endIt's a super small difference that, collectively, with the rest of the small nuances of Ruby/Rails, will document for you. It also makes debugging significantly easier.
All that said, I'd still like advice on common documentation/tagging for larger, more complex blocks of Ruby/Rails that I either have to veer from convention or perfect syntax is still hard to read.
6
May 15 '14
Your change is harder to read than what is was previously.
-1
u/th12eat May 15 '14
Not if you use any form of syntax highlighting in your IDE/text editor. The example I gave is causing distraction. It was beside the point. My point was that most people jumping into Ruby/Rails don't know all the more readable functions defined in ActiveRecord already. blank? present? nil? and many more are better ways to program since they read like a sentence as is.
if my_object.blank? <content> endThat's all I was getting at.
0
May 15 '14
[deleted]
0
u/th12eat May 15 '14
What are you referring to? I have no context as to what you are saying I'm false about. I never compared blank to an integer comparison... I was saying ActiveRecord methods such as those are good ways to program. They can be done explicitly or using rails semantics. I don't get why I'm being hounded so heavily for trying to recommend people document by using ActiveRecord methods more. That is literally all I'm trying to say. I just started programming in Rails in Januray. So, if I'm wrong, I'm wrong. But, in this case, you've given me nothing to learn from.
0
May 15 '14
[deleted]
0
u/th12eat May 15 '14
That would be an opinion. I use sublime text and it looks significantly better than plain black and white code blocks on reddit.
2
May 15 '14
No one is saying syntax highlighting is bad, im just saying you look like a fool saying that
@object.eql?(534) is better than @object == 534. Just accept you used a poor example and get off your high horse.
1
u/th12eat May 15 '14
Why do you think I'm on a high horse? I believe I did just say I used a poor example--given the responses.
How do I look like a fool saying that? I gave a trivial example to show what I meant, not that every instance of == in my code should be replaced with .eql?(). I get that there are instance in which it would be harder to read/trivial to use. I personally find it more legible to use methods in plain english like .eql? as opposed to the regex/boolean language required to convey the same thing. Why do I have to be a fool to prefer this? Especially in a topic related to documentation...
I've not called you names or said your opinion is wrong on two perfectly acceptable ways of programming the same thing. Hell, I'm not even going to say that you're on a high horse--but, if you aren't, how am I?
2
May 15 '14
i can't think of any instance where .eql? should ever be used and frankly i'm surprised it exists in the laguage. You are on a high horse because everytime you attempt to concede defeat you come up with some other reason you're wrong.
For example, .eql might not be better, but if you use the awesome syntax highlighting in my amazing sublime text 2, (ooo buzzwords) then it's better because it's written in english. Forget that anyone over the age of 8 can tell what an equal sign means and it's less characters and it's easier to read.
I am irritable because whoever has been teaching you has been doing a disservice where you care so much about your code looking amazing that it won't be functional.
→ More replies (0)1
u/Renaissir May 15 '14
Yeah, I take your point about obeying convention over configuration -- it's actually something that I think I do pretty well. Fingers crossed for accurate self-assessment...
I understand that replacing "==" with ".eq?" wasn't the best example of your other point, but I get what you're saying there, and I've been taking advantage of ActiveRecord's cute methods.
As an aside, one of my favorites is "<array>.include? <object>", because it forces you into the convention of naming your arrays as plurals. Usually it reads better as "<object>.in? <array>" though :-/
0
May 15 '14
[deleted]
-1
u/th12eat May 15 '14
I said that in my comment. This thread was discussing better ways to document your code. One of the suggestions I just got from my boss was to try to fully utilize Rails' lingo more-so than what I was used to to be readable as is (instead of requiring documentation). I just gave a quick example of what I was talking about. Where in my comment did I say they were different in function?
2
u/Renaissir May 15 '14
I think there's been some miscommunication here. What people are objecting to is that ".eq?" and "==" have some specific and important differences in how they compare objects. It definitely gave me headaches when I first started testing.
It's summed up nicely in this StackOverflow answer.
1
u/th12eat May 15 '14
If that's the problem, I'm aware of the differences. In this case, I was just trying to refer to an example of how to change the language. In my example, the two are equal.
0
May 15 '14
[deleted]
1
u/th12eat May 15 '14
I misread your comment the first time around. I thought you said they were equivalent (as in a trivial example). I'm aware of the differences. In the example given, they are actually equivalent. My point was less about the functions usability and more about suggesting OP document by coding more fluidly using ActiveRecords nomenclature.
0
May 15 '14
[deleted]
1
u/th12eat May 15 '14
Man, give me a break. Hah. I mean seriously. I've said now like 3 times that I'm learning. I said in my initial response that I'm looking for help on this too and that this is what I'm currently doing. I'm not 100% literate on Ruby/Rails.
From what I understand, eql? is in fact in ActiveRecord. Am I missing something?
Regardless, the example was purely to show a choice in how to program your code more legibly. As in, "Ruby/Rails contains a significant amount of plain english methods that can be used to better describe what you are doing". I should have apparently just said that or used a snippet from my working code to show what I meant instead of trying to give a minimalized example.
0
May 15 '14
[deleted]
1
u/th12eat May 15 '14
I apologize, but the only feedback I've got from this comment are people picking apart the methods used, why I swapped them out in terms of function, and any other nitpick that is off the thread's topic.
All I wanted to express is that documentation can be done by simply digging into Ruby/Rails pre-defined libs and utilizing their plain english functions.
Your comments in particular questioned whether I knew eql? and == were not the same or that eql? wasn't in ActiveRecord. For my example, this was not pertinent and required me to explain, twice, what I knew about these two functions and why it was unrelated to the purpose of my comment. eql? not being in ActiveRecord was, as I'm seeing it, false. It does appear to be in ActiveRecord.
All of this is to say that I just wasted my time looking up two separate issues you pointed out were wrong--when they were actually right in context. Both of which were unrelated to OP and mine's question. I appreciate the good deed in responding but these were not helpful.
0
3
u/chicagobob May 15 '14
I'm lazy, but when I need to comment, I use the TomDoc approach: http://tomdoc.org