• MonkeyMan (unregistered) in reply to chrismcb
    chrismcb:
    More Monkeys....:
    bu comments are harmless....
    Actually comments can be VERY harmful, especially if you read and TRUST only the comment. The problem with comments is they tend to get out of sync. If you get a piece of code, what is correct, the comment or the code? I'm not saying comments are bad, and that we shouldn't use them. But comments should be used sparingly. Well written code trumps a bad comment any day.

    The point is, though, that comments provide a REASON... The suggestion (made by Mr B, I think) was that if code NEEDS comments, it's bad, and if a Programmer NEEDS comments, they're incompetent. Comments are used to explain what and why (and better to err on the side of too many) - a competent programmer will look at the comment, look at the code, go "WTF? Something doesn't add up" - and further investigate if there is a problem with sync. Of course this may waste a lot of time if the comment is out of sync, but the whole point here is that by appreciating the need for comments, programmers do not allow the comments to get out of sync. People who think they can do without the comments can ignore them, but well written comments should explain the intention of a piece of code...Not to over-emphasise the point, but what a piece of code does and what the original programmer intended it to do can be two totally different things. By providing a comment, you explain what you set out to achieve in the code below.... Example:

    //loop through i from 1 to 12;
    for(int i=0; i<12; i++)
    <SNIP>
    

    is (obviously), a useless comment - and yes, I know it's going from 0 to 11, but this sort of comment appears often.... whereas

    //iterate through each month
    for(int i=0; i<12; i++)
    

    is slightly more useful (of course getting rid of some magic numbers, and perhaps using a different type of loop would help make this clear too....)

    Suppose (perhaps because people are on holidays) you wanted to skip January (let's say we have a uni that never has students in Jan {I know, I'm clutching at straws a little here}).... Without comments, the code looks like this:

    for(int i=1; i<12; i++)
    

    Someone coming in to maintain could be bewildered at why this loop has 11 cycles....

    //Loop through 1-12
    for (int i=1; i<12; i++)
    

    still doesn't clarify whether there's a problem or not...

    //Iterate over months (except January)
    for(int i=i; i<12; i++)
    

    does a better job - and an even more loquacious comment might actually be reasonable here too - provided it explains the situation better...

    In other words, for a competent programmer maintaining code, comments are harmless - if he (or she) feels they're out of sync with the code, it will at least cause some investigation. Either way, they are free to ignore them if they so desire. As for writing code, I think it is important to always explain what you are doing and why (even if it seems damn obvious). The next person on the project may not be as smart as you - and will almost certainly blame you for their difficulty....

  • commenter (unregistered) in reply to Mr B
    Mr B:
    fred34:
    Indeed, for some incredibly naive coding and general bad design, the documentation is better than most WELL written production code!

    Well written production code doesn't need any comments.

    If your code NEEDS lots of comments, then it NEEDS re-writing. If you NEED comments to understand code, then you NEED to learn how to code.

    Bullshit. What starts out as so-called good code will over time and maintainance cycles mutate into unmaintainable crap. There is little you can do to stop this.

    What comments should explain is why the script was written, why the class exists, why it makes sense to replicate existing library code (badly), why we make dollars and can continue to justify the expense of the arrogant geeks in IT.

    The chances are good that much of your code will outlive you and your current team. Do the guys after you a favour and throw them a bone (it might even be yourself 2 years later).

  • (cs)

    TRWTF is that the whole article shows up in Summary view on the front page. Ooops. (Yes I am aware that this has already been mentioned once. In CAPS, no less.)

  • z (unregistered) in reply to hims
    hims:
    I've seen bank logon pages which force you to enter passwords by selecting from a different dropdown each number or letter, and request forms which force you to enter 12 digit codes by choosing 1-9 from 12 different dropdown menus.

    If I had goggles for my brain and I tried to understand why, they'd still do nothing.

    It's to protect against keylogging malware.

  • I'd rather be sleeping (unregistered)

    Did anybody notice the date Tony B wrote the code? 02/05/2000 is a Saturday in the US.

  • Emu (unregistered) in reply to Voodoo Coder
    Voodoo Coder:
    posit9 > "9"

    Does anyone else see anything just a bit hilarious with that line?

    How many single characters are greater than 9?

    Did the user enter the shorthand for infinity into a date field? Or perhaps he was just checking for Roman Numerals...?

    I thought that at first but if you look then you will see that each number is actually a char (assuming that charAt(n) returns a char, I don't know javascript well enough to assume otherise).

  • yooheath (unregistered) in reply to Mr B
    Mr B:
    Well written production code doesn't need any comments.

    If your code NEEDS lots of comments, then it NEEDS re-writing. If you NEED comments to understand code, then you NEED to learn how to code.

    Your co-workers hate you.

  • (cs) in reply to MonkeyMan
    MonkeyMan:
    As for writing code, I think it is important to always explain what you are doing and why (even if it seems damn obvious). The next person on the project may not be as smart as you - and will almost certainly blame you for their difficulty....

    I am not trying to argue that one shouldn't comment. I am just disagreeing with the idea that comments are harmless.

    Lets say I'm a competent programmer, so I disregard the comment. The original code is:

    //iterate through each month for(int i=0; i<12; i++)

    The spec changed to ignore Jan. So I ignore the comment and change it to:

    //iterate through each month for(int i=1; i<12; i++)

    I quit, and the next person comes along. He is less competent that I sees the comment. Can't figure out why it starts with 1, reasons it is a bug and changes the code. Stupid harmless comment.

    Who knows what would have happened if the code was written: for(month i = Feburary; i <= December; i++)

    Probably skim right over it, maybe wonder why we started the loop in Feb and ignored Jan. It is possible that he changes the loop to start in Jan. But the point is we didn't need to keep the code and a comment in sync.

    The comment should have been something like: // Loop over all the months that contain billable workdays Of course the loop may change in the future and someone may forget to update the comment.

    I mean saying "loop from 0-12" is almost as bad as "iterate each month."

    Yeah it is stupid to just repeat what the code is doing, and is just as stupid to replace the magic numbers in the comment with interesting variable names and NOT update the code with the interesting variable names.

    Comments should be used for a couple of things: A) you've got some gnarly code, explain it in a short sentence. Maybe it is a big mean formula. B) You aren't doing something quite straightforward. Explain why you choose to do it this way.

  • John Muller (unregistered)

    I'm reminding of a few websites I've seen that show the date like '12-15-19108' in Firefox (last I saw was in 2007, from a web design company advertising many decades of combined web site development experiance... and who apparently don't test their sites in Firefox.)

  • Achenar (unregistered)

    Argh... commenting-related debates... I really didn't want to get involved, but just I can't stop myself.

    I swear those who argue for few - or no - comments might have their faith in their own 3lite skillz shattered as a fly-on-the-wall of the poor maintanance programmer looking at the code a few years down the track. I also suspect they seldom (if ever) work on code other than their own.

    To those programmers who may otherwise want to ignore it: effective communication (including commenting) is far, far more important than 3lite coding skillz. And, even if you really are smarter than everyone else, you must still code (and comment) for the lowest common denominator. Moreover, you might just be surprised as to your own difficulties in coming to terms with someone else's uncommented code.

    I also agree with the point that even if the comments are out-of-sync with the code, this is a good thing, since it triggers questioning and investigation. Any programmer who mindlessly changes the '1' back to a '0' in the "iterate from Jan to Dec" example - without asking the customer/client something like "have you been observing any billing-related problems with Janurary invoices?" - should reconsider their career choice.

    On a related point, I'm constantly surprised (and disturbed) about the number of .NET (C# or VB) developers who don't even know about /// (or ''') XML comments for methods and members. Notwithstanding the benefits of auto-generated API doco, these are invaluable in encouraging the documentation of a method's purpose and what exactly the otherwise cryptic parameters are. Not to mention Intellisense integration ...

  • Jim (unregistered) in reply to Will

    Yeah, but $10 per checked month or per worked month ? ^^

  • z f k (unregistered) in reply to rumpelstiltskin
    rumpelstiltskin:
    rohypnol:
    Jok:
    Anyway, Javascript validation is completely useless.
    No, it's not. Client-side validation is as mandatory as server-side validation. You should make your interface as friendly as blah blah blah blah blah... JavaScript validation is useful.

    I do not provide the teeming masses with tools because I want to be "friendly", but rather because it amuses me, much as it amuses me when my parrot pretends to read the newspaper I line his cage with. If the hoi polloi want the knowledge and the wisdom I provide, then they can show their appreciation and obeisance by entering data as I instruct them to. If they are incapable of so doing, they can leave as ignorant as they came.

    A psychologist once tells me "if you treat them as stupids, then they will find convenient to act stupidly".

    If you provide a stupid interface, users stupidly insert data into that, will the data be right or wrong doesn't matter, they don't question themself about it, just insert data.

    (sorry for my poor english)

  • asdfasf (unregistered)

    Javascript reinvent-the-wheel date code is so commonplace because the very old browser's (NS 3, IE 3) date functionality was so buggy and incomplete that it was totally useless.

    I've had to write code like this as well, around 1997.

  • dag (unregistered) in reply to I'd rather be sleeping
    I'd rather be sleeping:
    Did anybody notice the date Tony B wrote the code? 02/05/2000 is a Saturday in the US.

    No it's not, it's a Tuesday. The only non-WTF in the code is that it actually uses DD/MM/YYYY instead of the backwards MM/DD/YYYY (that's only used in the USofA for all I know).

    captche: dolor - ouch!

  • Slicerwizard (unregistered) in reply to MonkeyMan
    MonkeyMan:
    //Iterate over months (except January)
    for(int i=i; i<12; i++)
    
    does a better job
    Whoa, that code and comment are way out of sync.
  • (cs)

    Fast forward to 2007, and we get gluon, er, web2py and the code actually becomes self-documenting and doesn't require a billionth rework of the wheel.

    form=FORM('Date:',
      INPUT(_date='date',requires=IS_DATE()),
      INPUT(_type='submit'))
    
    if form.accepts(request.vars, session):
      response.flash='form accepted'
    elif form.errors:
      response.flash='form has errors'
    

    You can set it up so that the HTML generator will add appropriate validation JavaScript on the fly -- that way the form works with both scripting and non-scripting clients. If this form had an underlying database model, the validation would be performed to automatically enforce whatever the database expects (including type correctness).

    Cheers!

    Disclaimer: I'm just a happy user, that's all.

  • Bruteforce (unregistered) in reply to Mr B
    Mr B:
    fred34:
    Indeed, for some incredibly naive coding and general bad design, the documentation is better than most WELL written production code!

    Well written production code doesn't need any comments.

    If your code NEEDS lots of comments, then it NEEDS re-writing. If you NEED comments to understand code, then you NEED to learn how to code.

    Then I would like you to tell me exactly what this code does without searching for it on the net. It is also a very simple example of this kind of code. The proper way to do this is more complex. And notice, this code even have comments. ;) And the answer I want is not "Render stuff with OGL".

    	struct surface {
    		float vertices[4][3];
    		float matrix[9];
    
    		float s_dist, t_dist;
    	};
    
    	struct cube {
    		struct surface *surfaces[6];
    		float position[3];
    	};
    
    	static void
    	render(struct surface *surf,
    	       float *surf_pos, float *light_pos)
    	{
    		int i;
    		float v[4][3];
    		for(i = 0; i < 4; i++) {
    			surf->vertices[i][0] += surf_pos[0];
    			surf->vertices[i][1] += surf_pos[1];
    			surf->vertices[i][2] += surf_pos[2];
    
    			v[i][0] = (surf->vertices[i][0] - light_pos[0]);
    			v[i][1] = (surf->vertices[i][1] - light_pos[1]);
    			v[i][2] = (surf->vertices[i][2] - light_pos[2]);
    			normalize(v[i]);
    			v[i][0] *= M_INFINITY;
    			v[i][1] *= M_INFINITY;
    			v[i][2] *= M_INFINITY;
    			v[i][0] += light_pos[0];
    			v[i][1] += light_pos[1];
    			v[i][2] += light_pos[2];
    		}
    		
    		/* back cap */
    		glBegin(GL_QUADS);
    			glVertex3fv(v[3]);
    			glVertex3fv(v[2]);
    			glVertex3fv(v[1]);
    			glVertex3fv(v[0]);
    		glEnd();
    
    		/* front cap */
    		glBegin(GL_QUADS);
    			glVertex3fv(surf->vertices[0]);
    			glVertex3fv(surf->vertices[1]);
    			glVertex3fv(surf->vertices[2]);
    			glVertex3fv(surf->vertices[3]);
    		glEnd();
    
    
    		glBegin(GL_QUAD_STRIP);
    		glVertex3fv(surf->vertices[0]);
    		glVertex3fv(v[0]);
    		for(i = 1; i <= 4; i++) {
    			glVertex3fv(surf->vertices[i % 4]);
    			glVertex3fv(v[i % 4]);
    		}
    		glEnd();
    		for(i = 0; i < 4; i++) {
    			surf->vertices[i][0] -= surf_pos[0];
    			surf->vertices[i][1] -= surf_pos[1];
    			surf->vertices[i][2] -= surf_pos[2];
    		}
    	}
    
    
    	static void
    	render_cube(struct cube *c)
    	{
    		int i;
    
    		for(i = 0; i < 6; i++) {
    			glColorMask(GL_FALSE, GL_FALSE, GL_FALSE, GL_FALSE);
    			glDepthMask(GL_FALSE);
    			glEnable(GL_CULL_FACE);
    			glEnable(GL_STENCIL_TEST);
    			glEnable(GL_POLYGON_OFFSET_FILL);
    			glPolygonOffset(0.0f, 100.0f);
    			glCullFace(GL_FRONT);
    			glStencilFunc(GL_ALWAYS, 0x0, 0xff);
    			glStencilOp(GL_KEEP, GL_INCR, GL_KEEP);
    			render(c->surfaces[i], c->position, light_pos);
    			glCullFace(GL_BACK);
    			glStencilFunc(GL_ALWAYS, 0x0, 0xff);
    			glStencilOp(GL_KEEP, GL_DECR, GL_KEEP);
    			render(c->surfaces[i], c->position, light_pos);
    			glDisable(GL_POLYGON_OFFSET_FILL);
    			glDisable(GL_CULL_FACE);
    			glColorMask(GL_TRUE, GL_TRUE, GL_TRUE, GL_TRUE);
    			glDepthMask(GL_TRUE);
    
    			glStencilFunc(GL_NOTEQUAL, 0x0, 0xff);
    			glStencilOp(GL_REPLACE, GL_REPLACE, GL_REPLACE);
    			draw_shadow();
    			glDisable(GL_STENCIL_TEST);
    		}
    	}
    
    
  • (cs) in reply to Bob

    No, I am not exaggerating. I have had to use calendar controls to enter my birth date. I have to click on the "left year" control 35+ times to get to my year, then I have to click up to six times on the "left or right" month to get to my month. Sorry I am so OLD, but this is ridiculous.

    The real WTF is you don't realize horrible interfaces like this exist. So STFU when you find the real WTF.

    Addendum (2008-12-16 03:24): LOL I tried to delete this for a proper reply... sorry.

  • (cs) in reply to Bob
    Bob:
    CodeRage:
    Almost every form that requires a date also requires keyboard entry also (first name, etc), so why do these genius UI people think that it is somehow more friendly to force the user to click on the mouse 30-50 times to pick a birthdate, rather than just type it in?
    Ok, here's the real WTF.

    You're being very very clever and demonstrating an amazing mastery of the fine art of sarcasm, but if these "genius UI people" actually are as awful as you think they are, then what on earth makes you think they'll be any better at handling dates typed in by a user?

    Yes, you're right, a badly designed calendar control isn't better than a badly designed text validator. So? One would assume, if one was smart, that a well designed control would be used.

    Of course, "well designed" and "web 2.0" seem to go together like bicycles and refrigerators, so maybe the real WTF is expecting high quality in the first place.

    (Also, this "30-50 times" nonsense, is, well, a slight exaggeration. Maybe once to say you want to enter a date, a couple of times to pick a year, once for a month, and once for a day. That's 5 clicks. As compared to a mimimum of 6 - 8 keypresses (4 for year, 1 or 2 for month, and 1 or 2 for day) for typing the date in, plus you have to remember what format the website expects, or have some magic code that can tell if 01/02/03 is january the second 2008, or february the third, 2001 by reading the user's mind.

    Because we all know that the real WTF is a website that doesn't demand the user use the exact same date format as god in heaven and the website's designer have agreed on.

    No, I am not exaggerating. I have had to use calendar controls to enter my birth date. I have to click on the "left year" control 35+ times to get to my year, then I have to click up to five times on the "left or right" month to get to my month. Sorry I am so OLD, but this is ridiculous.

    The real WTF is you don't realize horrible interfaces like this exist. So STFU when you think you have found the real WTF.

  • (cs) in reply to Dan
    Dan:
    CodeRage:
    Even worse are US State pickers... having to go through a whole drop-down list when I could just type TWO LETTERS.

    UGH WTF.

    Well I just go and type the two letters. On Windows, in a Combobox (HTML <select> element), opened or not, typing letters will select the first entry your typing matches. Always works for me.

    Maybe I have an outdated browser, but it only reacts to the first letter of the drop down item, and then each subsequent letter goes to the next item with the same first letter. I live in Missouri, so I am well practiced in hitting the "M" key 6-7 times to get to "MO". This is not equivalent to typing "two letters" and getting to the right place. WTF.

  • (cs) in reply to CodeRage

    I see some people still can't spot a wind-up.

    Sorry, I thought it was an obvious one, but hey-ho, we each of us live and learn!

    ;)

  • (cs)

    On the topic of "useless" comments in code, I would like to add my $0.02:

    I've got my IDE setup to show comments in black text on a yellow background. That way, they make it easier to browse thru the code quickly and find the separate actions a code may perform. I know some of my comments are completely obsolete because the code itself is so obvious, the yellow line (I always add spaces to make them 80 characters wide) stands out and quickly directs my eyes to a piece of code that I'm looking for.

    On the topic of date validation: So what if someone enters "40-01-2008" as a date? Convert it to a date object and it'll be "09-02-2008" (in d-m-y format). Perfectly valid. If someone is stupid enough to think that January 40th exists, don't bother teaching them anything different.

  • (cs) in reply to matt
    matt:
    But lazy people do irk me. Heaven forbid you look up a function in the standard library of anything. unless you're paid by the line.
    You have a strange definition of lazy. I'm too lazy to re-invent the wheel, so I always look for a built-in function first.

    And then I go back to browsing the web

  • (cs) in reply to matt
    matt:
    But lazy people do irk me. ...
    Actually, sometimes lazy programmers are good programmers; the lazy programmer will look up the standard function, to avoid having to write it himself. He will automate his testing because he can't be bothered to type all that stuff in again. He will work out ways of getting the computer to do his job for him. This is good, no?

    Actually, the real WTF is that Java substring() function uses parameters startindex and endindex, rather than startindex and length like every single other language on the planet... Oh and month number 0 irks me too.

  • Michael (unregistered) in reply to I'd rather be sleeping
    I'd rather be sleeping:
    Did anybody notice the date Tony B wrote the code? 02/05/2000 is a Saturday in the US.

    Where is it not a Saturday?

  • (cs)

    As we all know, the real problem here is that Javascript has a hugely permissive date-handling logic, that allows dates like 25/01/1975 to be interpreted as 01/02/1977, amongst other horrors. Effectively validating a date in Javascript really isn't as simple as just casting it into a date, because it will attempt to interpret ANY rubbish as a date. I've yet to see one concise code snippet that will effectively validate any possible user-input date.

    Mr B:
    If you NEED comments to understand code, then you NEED to learn how to code.
    On the second main theme of this thread, I agree that you shouldn't *need* comments to understand your code. On the other hand, a three line comment at the top of a 30 line code block can save minutes when you're debugging lengthy methods, or coming back to change code you haven't touched in three months. I regularly curse myself for not including a little one-line "//this section of code prepare the floogle dropdown" when I'm amending stable sites that have about one change every 6 months...
    The Article:
    Thankfully, in her submission Catherine reported that this bit of of code was retired and replaced by a read-only field populated by a date-picker and a two-line if(...) alert(...) vet.
    And finally.. this. Honestly. This isn't the response of a web developer, this is the response of someone who went on an "I can use Visual Studio" course. It's so typical of web design agencies nowadays. They get a graphical tool full of pretty widgets, and just drag and drop their way to "Web 2.0" goodness - death by pretties, leaving their websites completely inaccessible. It makes my blood boil - and that's after I've had my morning coffee!
  • Catherine Palmer (unregistered) in reply to CodeRage

    As the one who passed this code to TDWTF, in my defence I have to say that whilst my solution doesn't meet with much approval, for the sites I create and maintain they are the simplest solution for the users, as most of the time all I'm asking for is a date to be plugged into a SQL query to generate a report for the current month or year, so the field is pre-filled with the current date. As for the comments regarding Javascript, all of our PCs have it on by default and most users don't know how to turn it off (and yes, I do test for it as part of the logging-in/user validation process). I know neither of these are probably ideal, but they work for 99%+ of our users.

    PS. Excuse my ignorance, but what's wrong with a JS alert for validating a field entry?

    captcha = ingenium, the element of ingenuity? (which I know I don't have)

    CP.

  • Real (unregistered) in reply to Bruteforce

    The idea is that code should be self documenting as possible. Using descriptive identifier names and a clean coding style could make up for a lot of comments. If your function doesn't simply "render stuff with OGL" then it should have descriptive function names that tell me exactly what it does. Each function should have one purpose and long functions with several purposes could be broken into smaller functions with descriptive names.

    I'm not familar with OpenGL so I can't comment on the logic of your function, but I assume the code would be read by people who know OpenGL and don't need comments to follow your code. If you comment, it should be to explain why something is done, not how. And in a well written program the structure and organization of the program (as well as documentation like requirement and design documents) could make most of the "why" obvious, so I agree, good code doesn't need comments, and good coders can understand good code without comments. Of course, that only applies to a perfect world where you're a good programmer working with other decent programmers.

    Sometimes you'll be forced to use a tricky hack or an obscure language feature and it's good to comment on it, but something is terribly wrong if that happens often.

  • Catherine Palmer (unregistered) in reply to JimM
    JimM:
    And finally.. this. Honestly. This isn't the response of a web developer, this is the response of someone who went on an "I can use Visual Studio" course. It's so typical of web design agencies nowadays. They get a graphical tool full of pretty widgets, and just drag and drop their way to "Web 2.0" goodness - death by pretties, leaving their websites completely inaccessible. It makes my blood boil - and that's after I've had my morning coffee!

    I don't want to turn this into a flame war, but sorry to disappoint, I've never used Visual Studio; I use Notepad2, which you may think is even worse. Training, what's that? As for accessiblity, I agree in the real world it might be an issue for some people, but here the vast majority of users don't know know that links can be tabbed through on a page, or other things: they want simple buttons and fields and enter data and create reports.

  • (cs) in reply to CodeRage
    CodeRage:
    Date pickers (mouse only) are horrible inefficient compared to using the keyboard. Sites that force you to click dozens or more times to get to the right year, then more clicks to get to the right month, just to pick a date are very unfriendly.

    Click field. Type.

    Works for me, always? If it's "England" you're selecting, type "Eng" and assuming this is the only "Eng" starting thing it'll be selected...

  • synp (unregistered) in reply to Linda
    Linda:
    On the topic of date validation: So what if someone enters "40-01-2008" as a date? Convert it to a date object and it'll be "09-02-2008" (in d-m-y format). Perfectly valid. If someone is stupid enough to think that January 40th exists, don't bother teaching them anything different.

    "40-01-2008" is more often than not the result of someone typing "04-01-2008" too fast. Do you really want to set the date to something unexpected like "09-02-2008" or show him the error of his ways?

    Granted, you won't catch every problem. 12-01-2008 would be just as good as 21-01-2008.

  • Iain Collins (unregistered) in reply to Michael
    Michael:
    Where is it not a Saturday?
    02/05/2000 was a Saturday in the USA but as far as the vast majority of the world is concerned it was a Tuesday.

    Why that is the case, as well as why it's always a good idea to stick to ISO 8601, is left as an exercise for the reader.

  • Peter (unregistered) in reply to Zerbs
    Zerbs:
    Nick J:
    Isn't is about time we decimalised time?
    I think it would cause too much confusion if there were only 10 hours in a day, 10 minutes in a second, 10 seconds in a minute, ect...
    Well, it would certainly confuse me if there were 10 minutes in a second and 10 seconds in a minute.
  • cthulhu (unregistered) in reply to TDD Chauvinist
    TDD Chauvinist:
    The only real WTF is the apparent lack of comprehensive unit tests. The problem with leap years, for example, is only possible because the coder didn't write his tests first.

    In a very real sense, I don't care how gnarly the code is, as long as it's well tested. Why should I have to look inside the date validation code at all? It should be an opaque box to me... One in which I have confidence because it's well tested.

    You should care if you have a deadline and budget.

    Even if you reach a point where all the tests fail and the function works perfectly, the kind of over complex non standard implementation in this article suffers from:

    -more initial bugs -more test failures that must be investigated -bug fixes are more likely to cause further bugs -takes longer for a new developer to pick up -a new developer is more likely to cause bugs

    The effects are: -a lot more time spent on maintenance -development is slower as developers become cautious (or worse don't and cause plenty of regressions that need fixing)

    The cause is the code. If you don't look at the code you might not be able to identify the cause. You might just take for granted that projects take ages and run over budget, that regression bugs spring forth in dozens.

  • (cs) in reply to Iain Collins
    Iain Collins:
    Michael:
    Where is it not a Saturday?
    02/05/2000 was a Saturday in the USA but as far as the vast majority of the world is concerned it was a Tuesday.

    The WTF that is the US handling of dates in a non-progressive manner from smallest unit to largest unit strikes again...

    chrismbc:
    I'm going to say that the problem with leap years, for example, is only possible, because the coder FORGOT about leap years.
    Not to mention that Tony B forgot about leap years whilst writing the code in a leap year, either in the very month that had 29 days in it, or not much later...
  • Thomas (unregistered)

    We could look at Microsoft for date validation done right. Outlook -> Ctrl+2 for the calendar -> Ctrl+g for the Go pop-up. This will accept anything that can be understood as a date, eg. "Christmas", "1 2 2008", "12", "1 2", "today", "2 weeks", "feb 1st" etc. Microsoft even understand that your locale (mine is Denmark) should be used when validating, so "1 2" is interpreted as the next Feb 1st - I guess in the US it would be the next Jan 2nd. Try it out.

    The principle should be: If we (the computer programmer couple) can interpret the input unambiguously we should accept it.

  • More (unregistered) in reply to chrismcb
    chrismcb:
    MonkeyMan:
    As for writing code, I think it is important to always explain what you are doing and why (even if it seems damn obvious). The next person on the project may not be as smart as you - and will almost certainly blame you for their difficulty....

    I am not trying to argue that one shouldn't comment. I am just disagreeing with the idea that comments are harmless.

    Lets say I'm a competent programmer, so I disregard the comment. The original code is:

    //iterate through each month for(int i=0; i<12; i++)

    The spec changed to ignore Jan. So I ignore the comment and change it to:

    //iterate through each month for(int i=1; i<12; i++)

    I quit, and the next person comes along. He is less competent that I sees the comment. Can't figure out why it starts with 1, reasons it is a bug and changes the code. Stupid harmless comment.

    Who knows what would have happened if the code was written: for(month i = Feburary; i <= December; i++)

    Probably skim right over it, maybe wonder why we started the loop in Feb and ignored Jan. It is possible that he changes the loop to start in Jan. But the point is we didn't need to keep the code and a comment in sync.

    The comment should have been something like: // Loop over all the months that contain billable workdays Of course the loop may change in the future and someone may forget to update the comment.

    I mean saying "loop from 0-12" is almost as bad as "iterate each month."

    Yeah it is stupid to just repeat what the code is doing, and is just as stupid to replace the magic numbers in the comment with interesting variable names and NOT update the code with the interesting variable names.

    Comments should be used for a couple of things: A) you've got some gnarly code, explain it in a short sentence. Maybe it is a big mean formula. B) You aren't doing something quite straightforward. Explain why you choose to do it this way.

    I just had to quote this because it's a really good example of why you should try to minimize comments.

    Sure, there might be times when they are needed, but that is less often than most junior developers would think.

  • (cs) in reply to Catherine Palmer
    Catherine Palmer:
    JimM:
    And finally.. this.
    I don't want to turn this into a flame war, but sorry to disappoint, I've never used Visual Studio; I use Notepad2, which you may think is even worse. Training, what's that? As for accessiblity, I agree in the real world it might be an issue for some people, but here the vast majority of users don't know that links can be tabbed through on a page, or other things: they want simple buttons and fields and enter data and create reports.
    If this is a purely internal site then I may be slightly less critical of your choice of solution, but even then it's still NOT good practice to develop inaccesible solutions. If something needs to be accessible outside of your business it needs to be accessible inside your business - or 6 months down the line you could be facing a DDA case when someone with accessibility needs gets employed and finds they can't use the tools they've been given to do their job.

    Of course, without knowing the specifics of either your solution or the business requirement it's a little harsh to make judgements, but the way your solution was described in the article made it sound like you just found some random widget that would select dates and pasted "teh codez" into the page.

    On a quite seperate topic, if this is an internal report-generation tool anyway why is it web based?!? But that's a pet bugbear for another day ;^)

  • Anonymous (unregistered)

    A female web developer. Who works exclusively in plain text. Nobody finds that strange. Just throwing it out there.

  • (cs) in reply to More
    More:
    I just had to quote this because it's a really good example of why you should try to minimize comments.
    You had to quote it why, exactly? So you could repeat someone else's point verbatim then pretend to be clever because you agree with it? Because it makes you feel important if you comment on the internet? Because you think the rest of us can't read and make our own minds up whether we agree with this or not?
    More:
    Sure, there might be times when they are needed, but that is less often than most junior developers would think.
    That woul dbe why they're called junior developers. Personally, I always prefer more comments to less - skipping irrelevant comments is easier than wading through complicated code. As a guide, I reckon that if my comments are more than half the length of the code they are describing I've got too many comments.

    There are exceptions, though - I've written some particularly complex logical comparisons (one in particular - for the suppression of statistics to avoid deductive disclosure - had truely torturous business logic) where the lines of comments have outnumbered the lines of code simply because there was some weird business logic going on that needed spelling out or the code would make no sense at all.

    Comments that relate to only one line should only be made IF that line does something slightly unusual - like starting a loop through an array from 1 instead of 0. You quoted a great example of all round bad programming: a bad initial comment, a change to code without amending / replacing the original bad comment, AND a change to the code base without understanding the code. I mean, seriously, would anyone "just" change a loop initialiser because they thought it didn't agree with the comment? Without investigating the business logic or if the code was currently functioning correct with the unusual loop? Do that on one of my projects and I'll be handing you your arse.

    Bottom line - programming languages cannot be completely self documenting, because they are not natural languages. They can express how things are done, but cannot fully express why they are done like that. So, if you really want to be a programmer: use comments. Or get the hell out of my profession.

  • (cs) in reply to Anonymous
    Anonymous:
    A female web developer. Who works exclusively in plain text. Nobody finds that strange. Just throwing it out there.
    No, I find it perfectly reasonable. One of the best programmers on my CS MSc was female, and worked exclusively in GEdit, compiling and running Java from the command line. She was fun to be around, and pretty hot. God, I miss being at Uni ;^)

    I mean, seriously; Grow up already. It's possible to be a geek and have social skills, and it's possible to be female, devastatingly good looking, and a damn fine programmer to boot. Now quit reinforcing geek sterotypes and go back to your Mom's basement ;^)

  • Steve (unregistered)

    What the hell is your problem today Jim? I know you're basically an intelligent bloke who always has a lot to say in the comments so I really can't imagine why today you feel the need to attack anything that holds an opinion. I suggest you get a nice cup of tea and just chill the fuck out bro. You don't make yourself look any smarter by flinging your toys out your pram; quite the contrary, it makes you look like an angst ridden junior dev with a chip on his shoulder. That's not how I had you pegged until recently but your contributions of late have degenerated into little more than self-absorbed personal attacks. Sorry bro but I think you need to work on your attitude.

  • Anonymous (unregistered) in reply to JimM
    JimM:
    Anonymous:
    A female web developer. Who works exclusively in plain text. Nobody finds that strange. Just throwing it out there.
    No, I find it perfectly reasonable. One of the best programmers on my CS MSc was female, and worked exclusively in GEdit, compiling and running Java from the command line. She was fun to be around, and pretty hot. God, I miss being at Uni ;^)

    I mean, seriously; Grow up already. It's possible to be a geek and have social skills, and it's possible to be female, devastatingly good looking, and a damn fine programmer to boot. Now quit reinforcing geek sterotypes and go back to your Mom's basement ;^)

    There were two females on the CS course that I did back in the day. Two out of about 250. They were both utter shit - one never made it past the first year and the other failed the final (don't know if she re-took because I passed and left). As an aside, they were both pig ugly.

    Go on Jim, take the bait - make my day!

  • Sean (unregistered) in reply to Zerbs

    The real issue is that you have 2 set durations that do not fit within decimal variation of each other. ~365.25 days per year is unfortunately not something we can change.

  • Sean (unregistered) in reply to hims
    hims:
    I've seen bank logon pages which force you to enter passwords by selecting from a different dropdown each number or letter, and request forms which force you to enter 12 digit codes by choosing 1-9 from 12 different dropdown menus.

    If I had goggles for my brain and I tried to understand why, they'd still do nothing.

    HSBCs online banking requires me to use 2 passwords. One is simply typed, the other is entered using an on-screen keyboard. I hate this on two levels: 1 - It takes me too long to do 2 - Anyone who happens to be looking at my screen can trivially see this password being entered

  • cb (unregistered)

    I'm surprised no-one had any kind of regard for this neat out-of-sync comment:

    curmonth ++
    //-- add one dayto curmonth as function produces zero for january --//
    "one day" indeed! Well, actually add me to the list of those clueless on what to say about that. :">

    Also, i can't resist adding that in an out-of-context sort of way,

      if (dday > "28" && mmnth == "02" )
    fails to catch strings like "142" that i believe are not higher than that "28"... Strings are sorted lexicographically AFAIK. :-B

  • Sean (unregistered) in reply to cb
    cb:
    I'm surprised no-one had any kind of regard for this neat out-of-sync comment:
    curmonth ++
    //-- add one dayto curmonth as function produces zero for january --//
    "one day" indeed! Well, actually add me to the list of those clueless on what to say about that. :">

    Also, i can't resist adding that in an out-of-context sort of way,

      if (dday > "28" && mmnth == "02" )
    fails to catch strings like "142" that i believe are not higher than that "28"... Strings are sorted lexicographically AFAIK. :-B

    Actually "142" is already accounted for as not being a possible entry. The code has already eliminated all 3 digit days and all days above 31.

  • STOP IT (unregistered) in reply to TDD Chauvinist
    TDD Chauvinist:
    The only real WTF is the apparent lack of comprehensive unit tests. The problem with leap years, for example, is only possible because the coder didn't write his tests first.
    The worst enemies of TDD are those who claim or suggest that it can replace programming logic skills.
  • John Muller (unregistered) in reply to Iain Collins
    Iain Collins:
    Michael:
    Where is it not a Saturday?
    02/05/2000 was a Saturday in the USA but as far as the vast majority of the world is concerned it was a Tuesday.

    Why that is the case, as well as why it's always a good idea to stick to ISO 8601, is left as an exercise for the reader.

    Yes please. Why anyone would choose any other order for sortable elements than the order they are virtually always sorted in is beyond me.

    Year, Month, Day, Hour, Minute, Second...

  • Pingmaster (unregistered) in reply to virgil
    virgil:
    Not that I want to defend this code, but a read-only field+ datetimepicker can be less user-friendly... sometimes it's much more productive to do data entry by manually keying in the data, rather than moving the mouse around to select the proper value. What I'm saying is that Catherine's solution is not "obviously better", it's just simpler and less bug-prone :)

    generally, I use a date picker along with an editable text field (i usually constrain the input such that it auto-inserts the '/' character in the appropriate place) then attempt to cast it as a date value. if it fails, then it is not a valid date. beyoond that, i can use the casted date value to constrain as necessary. Most of the time, the function to validate is about 10 lines, including the validation output. that way, the users can manually enter the date value if they wish, or if they're of the 'clicky' sort, they can use the picker.

Leave a comment on “Validating a Date with a Sledgehammer”

Log In or post as a guest

Replying to comment #:

« Return to Article