hate these ads?, log in or register to hide them
Page 2 of 121 FirstFirst 123451252102 ... LastLast
Results 21 to 40 of 2407

Thread: <xml><thread isTerrible="true" isUnderstandable="false" /></xml> - Coding help thread

  1. #21
    dpidcoe's Avatar
    Join Date
    June 29, 2011
    Location
    San diego
    Posts
    4,908
    Quote Originally Posted by MortyM View Post
    You shouldn't need comments in the first place. If your code needs explaining than that is a clear indiction that you should rewrite it to be more clear and understandable.
    No, you shouldn't need giant blocks of comments explaining in detail what's happening, but it's very hard to go wrong with a one-liner that's tacked on to the backside of a semicolon.

  2. #22
    Ophichius's Avatar
    Join Date
    December 15, 2011
    Location
    Hedonistic Imperative
    Posts
    5,218
    Quote Originally Posted by MortyM View Post
    Comments in general cause more harm than good.
    I can't tell you how many time I've looked at a piece of code where the comments say something completely different than what the code actually does. Usually because the code has been refactored but the comments haven't. It just ends up making the whole thing harder to understand.

    You shouldn't need comments in the first place. If your code needs explaining than that is a clear indiction that you should rewrite it to be more clear and understandable. Use good class, method, and variable names and don't do a million things in a single method, then you really shouldn't ever need to comment anything.
    And you're the sort of programmer I hate.

    Shitty comments are wasted disk space, true. Comments like dpidcoe's good example are the sort of thing that needs to be beaten into every programmer's skull, yours included.

    Comments exist to explain -why- your code is doing something. -What- the code is doing should be self-explanatory via good style.

    -O
    I thought what I'd do was, I'd pretend I was one of those Thukkers, that way I wouldn't have to have any goddamn stupid useless conversations with anybody.
    Failing the Voight-Kampff test, one tortoise at a time.

  3. #23

    Join Date
    April 9, 2011
    Posts
    337
    Quote Originally Posted by dpidcoe View Post
    Quote Originally Posted by MortyM View Post
    You shouldn't need comments in the first place. If your code needs explaining than that is a clear indiction that you should rewrite it to be more clear and understandable.
    No, you shouldn't need giant blocks of comments explaining in detail what's happening, but it's very hard to go wrong with a one-liner that's tacked on to the backside of a semicolon.
    It makes the code less readable, and it introduces extra work and opportunities for mistakes when refactoring. Which just creates more confusion: what if the comments no longer match what the code does?

    And again, either the comments are superfluous or your statements are too complex.

    The comments in your good code example would be good for a tutorial/example, but they would be against to coding standards of all the places I've worked, and never get passed peer reviews.

    Edit:
    Also, you better have a damn good reason for using a 1-indexed array, and if you do so you might want to put it into the variable name. Because now you have the comment at that specific location, but you want to have that knowledge put in your face every time you use the array, the comment doesn't help you with that at all. Or are you going to put that comment in every place you use the array? That would give you a million comments to maintain, and equally many opportunities for comments to not correctly describe what the code does.

    Furthermore, 64+1 gives you 'A' not 'a', so was the mistake in your comment or in your code? If you had just put alphabet[i] = 'a'+i;, the code would have been much clearer, the comment completely redundant, and you wouldn't have had the opportunity for the mismatch (and wouldn't have created a possible bug).
    Last edited by MortyM; April 13 2013 at 12:08:18 PM.

  4. #24
    dpidcoe's Avatar
    Join Date
    June 29, 2011
    Location
    San diego
    Posts
    4,908
    Quote Originally Posted by MortyM View Post
    hurr durr
    It was an off the cuff example thought up in less time than it took to type. Also, 'a' +1 is going to give you 'b' through '['. Now your code is wrong and no one knows wtf you were even trying to do with that for loop (we're assuming that whoever is reading it is stupid enough to believe what the comments say instead of the code, right?).

    And again, the comments aren't to say what the code does, the code always has the final say in what the code does, and anyone who trusts the comments over what the code says is a moron. The point of saying "//64+1 = 'a'" isn't to tell you that it's setting the value to 'a', it's to explain in the fewest words possible that the addition is happening to give a character value.

  5. #25

    Join Date
    April 9, 2011
    Posts
    337
    Quote Originally Posted by dpidcoe View Post
    Quote Originally Posted by MortyM View Post
    hurr durr
    It was an off the cuff example thought up in less time than it took to type. Also, 'a' +1 is going to give you 'b' through '['. Now your code is wrong and no one knows wtf you were even trying to do with that for loop (we're assuming that whoever is reading it is stupid enough to believe what the comments say instead of the code, right?).

    And again, the comments aren't to say what the code does, the code always has the final say in what the code does, and anyone who trusts the comments over what the code says is a moron. The point of saying "//64+1 = 'a'" isn't to tell you that it's setting the value to 'a', it's to explain in the fewest words possible that the addition is happening to give a character value.
    If you want to make completely explicit what the for loop is trying to do, then put it in a method named 'FillAlphabet()'. The point about the alphabet array being 1-indexed and having a size of 26 is that these properties are not local to this snippet, and therefore the information should not be local either. Comments are not good for that at all, and in fact they hurt because they give you an excuse for doing it this way.

    The char cast is there to show you are taking a char value out of an int, you don't need a comment for that. So the comment doesn't add any information, just miss-information ('a' instead of 'A').

    But we seem to be somewhat in agreement. You indeed can not trust the comments. Which is exactly my point. If you can't trust it and have to look at the code anyway, then it just takes up space and creates confusion. That ends up hurting for no particular good, while you can just as easy make what you are trying to do explicit in the code itself.
    Last edited by MortyM; April 14 2013 at 10:11:53 AM.

  6. #26
    dpidcoe's Avatar
    Join Date
    June 29, 2011
    Location
    San diego
    Posts
    4,908
    Quote Originally Posted by MortyM View Post
    The char cast is there to show you are taking a char value out of an int, you don't need a comment for that. So the comment doesn't add any information, just miss-information ('a' instead of 'A').
    That's a valid observation if this were a real program, however you're getting hung up on the details of some random code that was typed to show an example of commenting, not of coding. For that matter, the language isn't even specified. So for all we know it doesn't support casting characters like that.

    Quote Originally Posted by MortyM View Post
    But we seem to be somewhat in agreement. You indeed can not trust the comments. Which is exactly my point. If you can't trust it and have to look at the code anyway, then it just takes up space and creates confusion. That ends up hurting for no particular good.
    You're missing the point entirely. The comment isn't saying what the line of code is doing, it's explaining why it's there. The //64+1 = 'a' part isn't there to tell you that the array is being loaded up with the character 'a', it's there to explain that the for loop is intended to fill an array with incrementing values corresponding to chars. The actual values being used don't matter, and the comment would remain relivant if that was an array of size 10 storing values 0 through 9. It's just there to obviously show that the array is being stuffed with chars so you don't need to sit there thinking "wtf is this for loop filling up an array with values starting at some arbitrary number".

  7. #27

    Join Date
    April 9, 2011
    Posts
    337
    I'm not getting hung up on your example. I'm just using it to show some problems inherent in comments. The example is not special and is actually fairly typical in that you'll find these same issues (and much much worse) in pretty much any real world application.

    The //64+1 = 'a' comment being there just to show your taking a char (and being equally valid for 0-9) is just plain confusing. My point is that you can make it just as explicit through the code itself, without the confusion. (Regardless of the language, there are a million different ways you can do it. For instance in a weak or dynamic typed language you could use an intermediate variable named 'letter', 'number', or 'char'.)

  8. #28
    Donor
    Join Date
    April 11, 2011
    Location
    The Netherlands
    Posts
    1,027
    You don't need comments, if you do, select stuff that's in need of a comment, extract into a method and give the method a name that explains what it does.
    Of course, comments like the good example above can happen, but you rarely need them because code is normally understandable from it's own context.

  9. #29
    Lana Torrin's Avatar
    Join Date
    April 13, 2011
    Location
    Bonding around
    Posts
    17,947
    Bad coders gona bad comment too non shocker.

    Tapaderpin
    Quote Originally Posted by lubica
    And her name was Limul Azgoden, a lowly peasant girl.

  10. #30
    dpidcoe's Avatar
    Join Date
    June 29, 2011
    Location
    San diego
    Posts
    4,908
    Quote Originally Posted by Lana Torrin View Post
    Bad coders gona bad comment too non shocker.
    Which brings up another reason for leaving comments: they act as a sort of validity check for the code that was written. If you come across comments that don't match the code, you know that either the person wasn't paying attention when they wrote the comment, didn't know what they were doing when they wrote the code, or you're not understanding the code. Either of those 3 indicators are a good reason to doublecheck what you just read and make changes as necessary.

  11. #31
    Donor Aea's Avatar
    Join Date
    April 13, 2011
    Location
    Colorado
    Posts
    13,910
    Contrarians gonna contrary.

  12. #32

    Join Date
    May 31, 2011
    Posts
    3,286
    Quote Originally Posted by Ophichius View Post
    Comments exist to explain -why- your code is doing something. -What- the code is doing should be self-explanatory via good style.
    And this is why I personally find it hard to write meaningful comments. It the time I'm writing that piece of code, it is so absolutely easy, clear and obvious why I do what I do, that I always feel adding a comment there is equivalent of writing
    Code:
    i = i +1 ' Increase i by one
    Of course, later on it isn't so obvious any more and I often scratch my head over older code of mine.

  13. #33
    Qwert's Avatar
    Join Date
    April 10, 2011
    Location
    Elsewhere
    Posts
    1,827
    Quote Originally Posted by I Legionnaire View Post
    Any easy way to call Pi in C++ that doesn't rely on a specific compiler?
    Or am I better off just defining a constant as 3.1415 etc etc
    http://stackoverflow.com/questions/1...-constant-in-c

    TL;DR is if you aren't using Boost, the only guaranteed way to do it is

    Code:
    const double PI = 3.141592653589793238462;

  14. #34
    Ophichius's Avatar
    Join Date
    December 15, 2011
    Location
    Hedonistic Imperative
    Posts
    5,218
    Quote Originally Posted by Hel OWeen View Post
    Quote Originally Posted by Ophichius View Post
    Comments exist to explain -why- your code is doing something. -What- the code is doing should be self-explanatory via good style.
    And this is why I personally find it hard to write meaningful comments. It the time I'm writing that piece of code, it is so absolutely easy, clear and obvious why I do what I do, that I always feel adding a comment there is equivalent of writing
    Code:
    i = i +1 ' Increase i by one
    Of course, later on it isn't so obvious any more and I often scratch my head over older code of mine.
    The problem is that your example is describing what the code does. Practicing good commenting is an art unto itself. If i is something specific, say a color value for a pixel, '// We increment this until it overflows so the colors loop through the whole spectrum' That explains why the code does what it does. That said, if it really is bloody obvious, you shouldn't have to comment it. Generally you want to comment the tricky bits. This approach also has the advantage of not requiring you to comment terrifying hacks and fucking magic. Can you imagine trying to explain what fast inverse square root does, vs just saying 'This is a bit of magic, but it returns the inverse square root of the input.'

    -O
    I thought what I'd do was, I'd pretend I was one of those Thukkers, that way I wouldn't have to have any goddamn stupid useless conversations with anybody.
    Failing the Voight-Kampff test, one tortoise at a time.

  15. #35

    Join Date
    April 14, 2011
    Posts
    5,525
    Quote Originally Posted by Ophichius View Post
    The problem is that your example is describing what the code does. Practicing good commenting is an art unto itself. If i is something specific, say a color value for a pixel, '// We increment this until it overflows so the colors loop through the whole spectrum' That explains why the code does what it does. That said, if it really is bloody obvious, you shouldn't have to comment it. Generally you want to comment the tricky bits. This approach also has the advantage of not requiring you to comment terrifying hacks and fucking magic. Can you imagine trying to explain what fast inverse square root does, vs just saying 'This is a bit of magic, but it returns the inverse square root of the input.'

    -O
    ohgodthis. it's a lot easier to do in practice if you (and I know this is heresy in some circles) actually engineer your code as per the processes you were taught in uni - the comments explaining what each block does should already exist prior to you writing the block and it should just be a matter of copying+pasting the stuff you produced in the design/elaboration phases.

  16. #36
    Frug's Avatar
    Join Date
    April 10, 2011
    Location
    Canada
    Posts
    13,070
    Most of my comments are insulting the last person vomit all over the project.

    Things like "// Why use the email and phone number when we could use their userID? Nobody knows!" or when I'm more depressed about it, just "// sigh"

    Sometimes I have to open it up a year later and it makes me smile a sad smile. I wish the coders in india knew that comments were for more than signing your name on changes you make.

    Quote Originally Posted by Loire
    I'm too stupid to say anything that deserves being in your magnificent signature.

  17. #37

    Join Date
    April 9, 2011
    Posts
    337
    Quote Originally Posted by Frug View Post
    Most of my comments are insulting the last person vomit all over the project.

    Things like "// Why use the email and phone number when we could use their userID? Nobody knows!" or when I'm more depressed about it, just "// sigh"
    Those are the best. Finding those left by your coworkers at least reminds you that you're not alone in your frustrations.

  18. #38
    Donor
    Join Date
    April 11, 2011
    Location
    The Netherlands
    Posts
    1,027
    Real life example, which IMO doesn't need more documentation than the test and the code + method names / javadocs.
    It's a servlet 2.5 hack for httpOnly cookies. Ugh, java...

    Test/documentation:
    Code:
    package org.hippoecm.site.filters;
    
    import org.apache.commons.lang.StringUtils;
    import org.junit.Test;
    import org.mockito.ArgumentCaptor;
    
    import javax.servlet.FilterChain;
    import javax.servlet.ServletException;
    import javax.servlet.ServletRequest;
    import javax.servlet.ServletResponse;
    import javax.servlet.http.Cookie;
    import javax.servlet.http.HttpServletRequest;
    import javax.servlet.http.HttpServletResponse;
    import java.io.IOException;
    
    import static org.junit.Assert.assertFalse;
    import static org.junit.Assert.assertTrue;
    import static org.mockito.Mockito.*;
    
    /**
     * @author Wouter Danes
     */
    public class RewriteAllCookiesToHttpOnlyFilterTest {
    
        private Cookie cookie = new Cookie("Test", "Cookie \"Time\"");
        private HttpServletResponse response = mock(HttpServletResponse.class);
        private HttpServletRequest request = mock(HttpServletRequest.class);
        private FilterChain chain = createChainThatAddsTheCookie();
        private RewriteAllCookiesToHttpOnlyFilter filter = new RewriteAllCookiesToHttpOnlyFilter();
    
        @Test
        public void testThatResponseAddCookieIsNeverCalledOnTheWrappedResponseAndAHeaderIsAdded() throws Exception {
    
            filter.doFilter(request, response, chain);
    
            verify(response, never()).addCookie(any(Cookie.class));
            verify(response, times(1)).addHeader(eq("Set-Cookie"), contains("Test=\"Cookie \\\"Time\\\"\""));
    
        }
    
        @Test
        public void testThatSetCookieHeaderIncludesHttpOnly() throws Exception {
    
            filter.doFilter(request, response, chain);
    
            verify(response, atLeastOnce()).addHeader(eq("Set-Cookie"), contains("; HttpOnly"));
    
        }
    
        @Test
        public void testThatAllCookieAttributesAreSetInTheHeader() throws Exception {
    
            cookie.setMaxAge(3600);
            cookie.setPath("/");
            cookie.setSecure(true);
            cookie.setComment("Comment");
            cookie.setDomain("www.rijksoverheid.nl");
            cookie.setVersion(1);
    
            filter.doFilter(request, response, chain);
            ArgumentCaptor<String> captor = ArgumentCaptor.forClass(String.class);
            verify(response, times(1)).addHeader(eq("Set-Cookie"), captor.capture());
    
            String headerValue = captor.getValue();
    
            assertTrue(headerValue.contains("; Max-Age=3600"));
            assertTrue(headerValue.contains("; Path=/"));
            assertTrue(headerValue.contains("; Secure"));
            assertTrue(headerValue.contains("; Comment=Comment"));
            assertTrue(headerValue.contains("; Domain=www.rijksoverheid.nl"));
            assertTrue(headerValue.contains("; Version=1"));
    
            String[] headerElements = headerValue.split(";");
            assertTrue(headerElements[0].trim().matches("^.+=.+$"));
            for (int i = 1 ; i < headerElements.length ; i++) {
                if (StringUtils.isNotBlank(headerElements[i])) {
                    assertTrue(headerElements[i].trim().matches("^.+=.+$") || !headerElements[i].contains("="));
                }
            }
    
        }
    
        @Test
        public void testThatMaxAgeAndExpiresAreNotSetWhenMaxAgeIsNotSet() throws Exception {
    
            cookie.setPath("/");
            cookie.setSecure(true);
    
            filter.doFilter(request, response, chain);
            ArgumentCaptor<String> captor = ArgumentCaptor.forClass(String.class);
            verify(response, times(1)).addHeader(eq("Set-Cookie"), captor.capture());
    
            String headerValue = captor.getValue();
    
            assertFalse(headerValue.contains("Max-Age="));
            assertFalse(headerValue.contains("Expires="));
    
        }
    
        private FilterChain createChainThatAddsTheCookie() {
            return new FilterChain() {
                @Override
                public void doFilter(ServletRequest request, ServletResponse response) throws IOException, ServletException {
                    HttpServletResponse.class.cast(response).addCookie(cookie);
                }
            };
        }
    }
    Implementation:
    Code:
    package org.hippoecm.site.filters;
    
    import org.apache.commons.lang.StringUtils;
    import org.springframework.web.filter.OncePerRequestFilter;
    
    import javax.servlet.FilterChain;
    import javax.servlet.ServletException;
    import javax.servlet.http.Cookie;
    import javax.servlet.http.HttpServletRequest;
    import javax.servlet.http.HttpServletResponse;
    import javax.servlet.http.HttpServletResponseWrapper;
    import java.io.IOException;
    import java.text.SimpleDateFormat;
    import java.util.Calendar;
    import java.util.Locale;
    import java.util.TimeZone;
    
    /**
     * This is a servlet filter that rewrites all cookies on the Response to HttpOnly cookies.
     * This filter should be executed first in the chain. It'll wrap the Response object and intercept calls to the
     * addCookie() method.
     *
     * @author Wouter Danes
     */
    public class RewriteAllCookiesToHttpOnlyFilter extends OncePerRequestFilter {
    
        @Override
        protected void doFilterInternal(HttpServletRequest request, HttpServletResponse response, FilterChain filterChain)
                throws ServletException, IOException {
    
            HttpOnlyCookieResponseWrapper responseWrapper = new HttpOnlyCookieResponseWrapper(response);
            filterChain.doFilter(request, responseWrapper);
    
        }
    
        private static final class HttpOnlyCookieResponseWrapper extends HttpServletResponseWrapper {
    
            public final SimpleDateFormat COOKIE_EXPIRES_DATE_FORMAT;
    
    
            public HttpOnlyCookieResponseWrapper(HttpServletResponse response) {
                super(response);
    
                COOKIE_EXPIRES_DATE_FORMAT = new SimpleDateFormat("EEE, dd-MMM-yyyy HH:mm:ss zzz", Locale.US);
                COOKIE_EXPIRES_DATE_FORMAT.setTimeZone(TimeZone.getTimeZone("GMT"));
            }
    
            /**
             * Because servlet 2.5 doesn't have setHttpOnly, we override the addCookie method to manually set a http header
             * instead of actually adding a cookie to the underlying request.
             *
             * @param cookie the Cookie to add to the response. This will always end up being an HttpOnly cookie.
             */
            @Override
            public void addCookie(Cookie cookie) {
                StringBuilder sb = new StringBuilder();
                String name = cookie.getName();
                String value = cookie.getValue().replaceAll("\"", "\\\\\"");
                sb.append(name).append("=\"").append(value).append("\" ; HttpOnly");
                if (cookie.getSecure()) {
                    sb.append("; Secure");
                }
                String domain = cookie.getDomain();
                if (StringUtils.isNotBlank(domain)) {
                    sb.append("; Domain=").append(domain);
                }
                if (cookie.getMaxAge() >= 0) {
                    setMaxAgeAndExpires(cookie, sb);
                }
                String path = cookie.getPath();
                if (StringUtils.isNotBlank(path)) {
                    sb.append("; Path=").append(path);
                }
                String comment = cookie.getComment();
                if (StringUtils.isNotBlank(comment)) {
                    sb.append("; Comment=").append(comment);
                }
                sb.append("; Version=1");
                addHeader("Set-Cookie", sb.toString());
            }
    
            private void setMaxAgeAndExpires(Cookie cookie, StringBuilder sb) {
                sb.append("; Max-Age=").append(cookie.getMaxAge());
                Calendar expires = Calendar.getInstance();
                expires.add(Calendar.SECOND, cookie.getMaxAge());
                expires.setTimeZone(TimeZone.getTimeZone("GMT"));
                String formattedExpires = COOKIE_EXPIRES_DATE_FORMAT.format(expires.getTime());
                sb.append("; Expires=").append(formattedExpires);
            }
    
        }
    
    }

  19. #39
    Frug's Avatar
    Join Date
    April 10, 2011
    Location
    Canada
    Posts
    13,070
    StupidAnnoyinglyLongVariableNameThatCouldBeShorter ButIThoughtIWasCleverToSelfDocumentThis gayvar = new StupidAnnoyinglyLongVariableNameThatCouldBeShorter ButIThoughtIWasCleverToSelfDocumentThis.ActuallyTh isMethodReturnsTheProperObjectThatAlsoHasAnEvenLon gerName();

    I've seen that too. It's pretty awful.

    Man the forums are forcing word breaks and adding spaces to my glory.

    Quote Originally Posted by Loire
    I'm too stupid to say anything that deserves being in your magnificent signature.

  20. #40
    Donor
    Join Date
    April 11, 2011
    Location
    The Netherlands
    Posts
    1,027
    They are method names though.

Bookmarks

Bookmarks

Posting Permissions

  • You may not post new threads
  • You may not post replies
  • You may not post attachments
  • You may not edit your posts
  •