Commenting1:50 with Jeremy McLain
Let your code speak for itself, but when necessary, use words.
The method we just wrote was fairly complicated. 0:00 We have multiple for each loops nested inside of a while loop. 0:03 Multiple ifs and multiple return statements. 0:06 We've tried to make this code as self documenting as possible 0:10 by naming things appropriately but sometimes it's best to 0:14 put in a few comments that describe in English, what's happening and why. 0:17 Comments are a two-edged sword, though. 0:22 When they're accurate, they can help make it clear what's happening. 0:24 On the other hand, if we were to change something about this code and 0:28 forget to update the comment to reflect the changes, 0:31 then the comments would no longer be accurate, and 0:34 that can cause more confusion than if there were no comments at all. 0:37 You may have heard the phrase, only when necessary use words. 0:41 It means, let your actions speak for themselves. 0:45 In the case of code, we should try to let our code speak for 0:48 itself as much as possible. 0:51 This means writing self-documenting code that doesn't require a lot of comments. 0:53 However, we need to look at our code from the perspective 0:59 of someone who is not involved in writing it. 1:01 Can they read this code and understand what's happening? 1:04 If not, maybe we should add a few clarifying comments. 1:07 Comments aren't just for those who aren't familiar with the code. 1:12 I can't tell you how many times I've had to work with code that I wrote months or 1:15 years earlier. 1:20 A few well placed comments act as cues to help me remember 1:21 what I was thinking when I wrote the code and remind me why I wrote it that way. 1:25 Writing descriptive, clear code, and comments is an art. 1:30 As with all art forms there are some best practices and some tips and 1:35 tricks that can be learned. 1:39 In the end, it comes down to your own creativity and 1:41 intuition about what's going to help the reader, even if that reader is yourself. 1:44
You need to sign up for Treehouse in order to download course files.Sign up