Entries:
Comments:
Posts:

Loading User Information from Channel 9

Something went wrong getting user information from Channel 9

Latest Achievement:

Loading User Information from MSDN

Something went wrong getting user information from MSDN

Visual Studio Achievements

Latest Achievement:

Loading Visual Studio Achievements

Something went wrong getting the Visual Studio Achievements

TWC9: Silverlight 4, SQL Server R2 & Ent Library 5.0 all RTM, Why code comments aren't bad

Download

Right click “Save as…”

This week on Channel 9, Dan and Clint discuss the week's top developer news, including:

Picks of the week

Follow the Discussion

  • rhmrhm

    ORMs are the ultimate leaky abstraction. You get the ability to write neat expressions in the code and have the SQL generated for you and the data returned in CLR objects but if you care about performance you either have to check everything that the ORM does by hand or you need to have abstraction-puncturing knowlege of how it works internally.

  • Vesuviusvesuvius Count Orlock

    @ performance implications of IQueryable

     

    I believe the reason Chris points out, is why WCF RIA services is pretty much implemented solely with IQueryable, to allow the Silverlight client to create an expression tree [or trees] that is executed on the server by the Silverlight client.

  • This comment is in response to your comments on the article about code comments being bad for code clarity. Did you have a chance to read the entire article before the show? I ask because the author does make a comment (admittedly toward the end of the article) about exceptional cases where comments can actually add value.

     

    I think the real problem with comments is that, historically, commenting code was often presented as simply a Good Thing™ to do. Like so many other things, inexperienced programmers tend to accept this advice and apply it in the most obvious (and unhelpful) manner possible.

     

    We need to get the message out there that writing good comments is similar to writing good code in that it takes some effort and usually less is more.

  • Dan FernandezDan

    While it's a good thing that WCF RIA services uses IQueryable, I do agree with RHM that it's a little scary that developers could unintentionally cause a massive perf hit just by using the wrong interface, especially since you tend to find lots of LINQ samples that use IEnumerable<T>.

  • Dan FernandezDan

    Well the author calls out that comments are the exception, not the rule and again, this is my personal opinion, but comments are being demonized as this thing that you shouldn't do except in exceptional cases. I agree with you that succinct comments are useful, but the default answer shouldn't be in removing comments. My main example isn't commenting what the code is doing, but rather why the code is needed.

     

    One example is when you have a corner-case bug, something that only happens in a specific scenario (when an app needs to runs side-by-side, a specific version/language of an OS, etc). Having a comment  that says that the method was added to resolve this particular bug (with a link to the bug #) is very useful, otherwise you're wondering why the method exists if you comment it out and "it works on my machine" and the testers machine, but breaks a customer.  The other big issue I've seen is using legacy code that you can't refactor and comment out.

     

    Either way, I'd love to see someone throw time and effort to see what it would be like walking up to a code base say part of .NET Rotor, add a bug and test to see if having/removing comments makes a meaningful difference between the amount of time it takes to use/understand the code.

     

     

     

  • Bent Rasmussenexoteric stuck in a loop, for a while

    Elegant Code = Code - Comments.

     

    This is a false dichotomy.

     

    I can clearly see the tension between comments and code. More comments obscures code, less comments obscures design insights. The problem is the IDE, not commented or commentless code, it's the ability to seamlessly switch between the two views.

     

    It's rather amazing how often people conflate presentation and representation. It happened with XML microformats, denying XML fidelity for presentational bliss, it's happening here, denying obscuring comments for code elegance - which is indeed desirable.

     

    What I dispise about making comments is commenting the trivial.  It would be nice if the IDE could infer the entire documentation and XML comments for a trivial function (and by the way, showing XML comments not as XML.)

     

    Mind over matter.

  • BasBas It finds lightbulbs.

    Good show. The stuff about IQueryable was very informative. I'm gonna check out some prime suspects first thing this monday to see exactly what kind of SQL query they're generating.

  • BasBas It finds lightbulbs.

    Edit: disregard this entire post. Once again, my attempt at a post is foiled by this forum's amazing one line code blocks. AWESOME.

     

     

    Regarding the comments thing: one of the things I've always learned is to make the code self documenting via clear function names etc. This included wrapping unclear blocks of code into a function with a descriptive name, even if that function was going to get called only once. This adds a tiny bit of overhead, of course, but I always thought it was worth it because it made code so much more readable. After all:

     

     class SomeClass
     { 
    public SomeClass() 
        { 
            Foo = true; 
            Bar = "Bar"; 
            SearchResults results = Search(Bar); 
            // Transmogrify the search results 
            results.Items.Sort(); 
            results.DoSomeMagic(results.Items.Count - 1); 
            SomeEnum x = results.IsMysteriousValue; 
            if (x == SomeEnum.MoreMystery) 
            { 
                   results.Explode(); 
            } 
        } 
       }
    
     

     

    is a lot less clear (or readable) than

    class SomeClass { 
        public SomeConstructor() { 
            // Initialize some properties 
           Foo = true; 
           Bar = "Bar"; 
           // Search for Bar 
           SearchResults results = Search(Bar); 
           results = Transmogrify(results); 
        } 
        private SearchResults Transmogrify(SearchResults results) {
            results.Items.Sort(); 
            results.DoSomeMagic(results.Items.Count - 1); 
            SomeEnum x = results.IsMysteriousValue; 
            if (x == SomeEnum.MoreMystery) { 
                  results.Explode(); 
             } 
         } 
    }
    

     

    even if you have to transmogrify only once, wrapping that stuff into a descriptive function makes it a lot more readabe than just a comment above the block of mystery code.

     

    However, since we've had regions, I've been more prone to just wrapping these complicated blocks of code into a descriptive region rather than a separate function. That way, I can just look at the collapsed region and see instantly what it does. Also, no function call overhead.

     

    What does everybody else think? Is the code better documented via regions or by wrapping complicated blocks in their own function?

  • Dan FernandezDan

    I would personally push things like Transmogrify into their own function in a couple of scenarios - you know you're only going to do one thing in that chunk of code (it's atomic), if it's a good candidate for reuse in other parts of your code, if the function it lives inside is big then it's a good choice for refactoring, if you know it could change (ex: switch 3rd party Transmogrify vendors) or be optimized in the future. I'm not worried about the function call overhead for performance as there's likely other things that you can do to optimize your performance before you optimize that.

     

    The one nice thing about keeping it all together is that code with a lot of functions can be "jumpy", where you're potentially going 3-4 levels deep multiple times to understand exactly what each method call is doing (and the methods that the method call can do). Plus in this example, the total lines of code is tiny so I don't think anyone would complain about having that function inline.

  • Bent Rasmussenexoteric stuck in a loop, for a while

    I like to keep functions small, self-explanatory and pure. This is prescribed by LINQ which of course makes heavy use of pure extension methods. Pure and simple extension methods are composable and reasonable. As in Search(Bar).Transmogrify() - or assuming Bar is implicitly converted to SearchQuery then Bar.Search().Transmogrify() - or arbitrarily transformed as in Bar.[Tx]().Search().[Tx]().Transmogrify().[Tx](). Invariant where possible, variant when necessary.

  • Not true, beautiful code = code + comments. In proper places it can help visualize important portions of the code easily, that would be otherwise impossible without.

  • Mike SampsonSampy And I come back to you now - at the turn of the tide

    I don't write comments pretty much ever. When I TDD (which I do for everything these days), I don't need them. What I was thinking and what I meant for the code to do is much better expressed through good names, solid patterns, and great tests. I can even read the tests sequentially and watch the class evolve. Ditch those comments and up your code reading skills! It makes you a much better developer.

  • Clint RutkasClint I'm a "developer"

    I've had to deal with code where the comments are literally explaining every line of code.  I'm with Dan and Sampy.  Explain edge cases, TDD, and PLEASE explain what the regex should be doing.

     

    Comments in code is a flame war much like the proper place to put a curley bracket in c#. 

    if(foo) {
    or

    if(foo)
    {
     // bar 
    }

     

    And we all know the bottom way is correct Smiley

  • Of course, documenting every single line is silly, but not documenting the code at all is too. And we are not talking about hello world applications or useless chunks of code used for demo purposes.

  • Bent Rasmussenexoteric stuck in a loop, for a while

    Yes, the point - as written - was: comments are not evil, over-commenting or under-commenting is, but you should be able to toggle comments on and off at the function, namespace or file level.

     

    There's no point in commenting the trivial but that's also what you have to do in practice, especially if you are making a library, which can be annoying and feel like a waste of time.

     

    Other times it feels like a pleasure even if the documentation far exceeds the implementation size (albeit one that does not involve much thought - so the end result is nice but getting there is mindless work).

     

    As an example, some binary domain-specific operators (LINQ and otherwise)

     

    /// <summary> /// Logical xor (⊕). /// </summary> /// <remarks> /// 0 ⊕ 0 = 0 /// 0 ⊕ 1 = 1 /// 1 ⊕ 0 = 1 /// 1 ⊕ 1 = 0 /// </remarks> /// <param name="value1">The first bit.</param> /// <param name="value2">The Second bit.</param>
     /// <returns>The xor bit.</returns> [Pure] public static bool Xor(this bool value1, bool value2) { return value1 != value2; } 

     

    /// <summary> /// Logical xor (exclusive-or) all elements (⊕). /// </summary> /// <remarks> /// ⊕ (a, b, c) = a ⊕ (b ⊕ c) /// </remarks> /// <param name="source">The source bit sequence.</param> /// <returns>The xor bit.</returns>
     [Pure] public static bool Xor(this IEnumerable<bool> source) { Contract.Requires(source != null); Contract.Requires(source.Any()); return source.Aggregate(Xor); } 

     

    [nice  "return"-alternative for the LINQ operator: IEnumerable<bool> where Count() = 1]

     

    The comments are extremely more verbose than the implementation but nice and useful.

     

    One more example, the implication operator, which is very useful in contracts albeit simple - but much more readable in its application than its expansion, in my oppinion

     

    /// <summary> /// Does the first value imply the second value? /// </summary> /// <param name="iff">The first bit.</param> /// <param name="then">The second bit.</param> /// <returns>¬iff ∨ then</returns> [Pure] public static bool
     Implies(this bool iff, bool then) { return !iff || then; } 

     

    I like the comments but would also like an easy way to hide them when skimming code.

     

    Well, your mileage may vary.

  • BasBas It finds lightbulbs.

    I thought it was a shame that VS2010 didn't provide something for this. The XML is overly verbose, you basically only want to see it when editing the comment block and not when reading it. It would've been cool if the IDE turned these blocks of /// comments into a single line of intellisense-style information. Then it could expand to the text view when you click on it, or something.

     

    Come to think of it, now that the IDE is all XAML, it might be possible to change the way these blocks are presented?

  • Bent Rasmussenexoteric stuck in a loop, for a while

    Yes, I'm very much looking forward to much more compact and interactive presentations of the source code made possible with the new WPF based editor in VS 2010.

     

    Appropos: I've always been on the side of Anders Hejlsberg when it comes to XML literals but one aspect of them that is a bit interesting is that you could have one underlying syntax for both <metadata>, //comments, [attribute]s and <expressions>x</expressions> but I think the people on the cutting edge of the DSL space work at Intentional Software with Charles Simonyi.

  • MinhMinh WOOH!  WOOH!

    Speaking of elegance, couldn't you just make a "pop-out" link for your player so we can move it to whichever monitor we want, then maximize it there? I have a feeling a function that requires a "security" prompt won't let me do that.

  • Did you gentlemen say SQL Server R2 RTM'd?  I am unable to find it on TechNet or MSDN.  The CTPs are posted, but not the RTM.

  • Dan FernandezDan

    It's a bit confusing, but to quote Mary Jo Foley (who has the best explanation)

     

    MSDN and TechNet subscribers will be able to download R2 Data Center, Enterprise, Standard, Workgroup and Developer (in English only) as of May 3. Volume licensing downloads will be available in 11 languages starting May 3. The trial bits are available as of April 21.

     

    You can download SQL Server Express R2 now from here -  http://www.microsoft.com/express/Downloads/#SQL_Server_2008_R2_Express_Downloads

     

    The trial is also available to download

    http://www.microsoft.com/sqlserver/2008/en/us/R2Downloads.aspx#none

     

  • John Sonmezjsonmez John Sonmez

    Hi Dan,

     

    So I have to disagree with you about my post on http://elegantcode.com about eliminating comments.  I think you have missed the point of the post.

     

    I fully understand that many people "don't believe in comments" and write bad horrible to understand code, because their belief stems from laziness as opposed to the desire to write good code.  There is a MAJOR difference between this viewpoint or reason for not writing comments vs the reason I am advocating.

     

    I went through some examples in my post which showed how writing self-documenting code eliminates comments and make the code more clearly understandable.

     

    There are instances where comments are going to be needed.  Which I also state in my post, (regex explanations for example).

     

    In general though, I am pretty confident the guidance I am giving out is 100% correct, and I am pretty convinced that I can prove this to be true to you.

     

    So, I challenge you.  Give me some piece of code that is heavily commented to explain what is going on.  I will refactor it to make it at least as readable, and most likely better by eliminating comments and replacing them with self-documenting code.

     

    Let your viewers decide if it is clearer or not.  If they say it is not clearer, I will admit defeat.

     

    By the way you might like this post: http://elegantcode.com/2010/05/01/say-no-to-null/">http://elegantcode.com/2010/05/01/say-no-to-null/

    http://elegantcode.com/2010/05/01/say-no-to-null/">

    http://elegantcode.com/2010/05/01/say-no-to-null/">

    http://elegantcode.com/2010/05/01/say-no-to-null/">

    http://elegantcode.com/2010/05/01/say-no-to-null/">

Remove this comment

Remove this thread

close

Comments Closed

Comments have been closed since this content was published more than 30 days ago, but if you'd like to continue the conversation, please create a new thread in our Forums,
or Contact Us and let us know.