- Feature Articles
- CodeSOD
- Error'd
- Forums
-
Other Articles
- Random Article
- Other Series
- Alex's Soapbox
- Announcements
- Best of…
- Best of Email
- Best of the Sidebar
- Bring Your Own Code
- Coded Smorgasbord
- Mandatory Fun Day
- Off Topic
- Representative Line
- News Roundup
- Editor's Soapbox
- Software on the Rocks
- Souvenir Potpourri
- Sponsor Post
- Tales from the Interview
- The Daily WTF: Live
- Virtudyne
Admin
if(year % 4 == year % 100 == year % 400) leap!
Admin
Admin
Has nobody noticed what happens in uploadtime when secs == 59?
CAPTCHA: smile - yes you might once you notice the above.
Admin
That's very much a premature optimization. If you profiled it in an application, I highly doubt you would find any cases where you would need to go in and optimize that function.
But there's no excuse for laziness anyway, it's far easier to just use the library functions. Why see if the year is divisible by 4, when you can ask another function if the year is a leap year?
Admin
Admin
"I AJAX would kill Flash, though. Flash is just evil, although not 100% evil. "
Well, claiming that a technology is "modern" or "cool" or "evil" is a sure way to make many people who have a clue, realize that you don't.
Admin
I agree, but I would always put unblocked if()'s on one line:
This makes it much less likely that some future modification will add a line in the middle. If it's too long to do that with, it should be in a block anyway.
Actually, I'd be tempted to use a tip I first came across on TheDailyWTF and lay it out like this:
Whatever happened to TheDailyWTF anyway? This site is nearly as good, but...
Captcha: doom. Posting my own code sample on here is asking for it.
Admin
Admin
Admin
"Why bother" to which? Second validation on the server or preliminary validation on the client?
The golden rule of web development is "never trust any incoming data from a browser". Therefore, everything coming in from the browser must be validated on the server. If that's not happening, then shame on the developer. If your "why bother" was for validation on the server side, then shame on you as well.
Preliminary validation on the browser, without making calls to the server, is a very nice-to-have. With this, the user can get instant feedback on obvious errors without a round-trip to the server AND it takes a lot of unnecessary load off the server to boot. It's a win-win.
However, you want to ride that fine line between putting enough validation to keep unnecessary load off the server, but not putting in so much that you expose the same business rules in two different places and creating a maintenance problem. Often, a good middle-ground is at the level of "are all required fields filled out?" and "Are there letters in the number field?" -- things that are relatively agnostic of specific business rules.
Admin
Maybe we could combine them somehow... Say a missile launching dinosaur that runs on Javascript
(quoted from a friend)
Admin
AJAX is really named after a city east of Toronto:
Ajax, Ontario
the acronym came later. That's the REAL WTF.
Admin
And if someone uses/extends/includes your code and they input a historical date, do date math, etc?
Why would you actually go to the effort to do things the wrong way?
Admin
Pray tell, what catastrophic event will spell the end of mankind in the year 3002 ?
Admin
Come on guys...
A directory:
.../leapyears/
populated with files:
1900, 1901, 1902, 1903, 1905, 1906, 1907, 1909, ... 2001, 2002, 2003, 2005, ...
Then we could laugh that it's: a) inverted logic b) all sorts of applicable file-not-found gags
Admin
Admin
I don't think its premature optimization... typically code like this is reused many times in multiple projects. While in your particular project, it might only be ran .01% of the time, another project might use it every time a database transaction is ran, which might be the entire point of the program (thus running a good deal more of the time).
If you think about it in that sense, you realize that the weight of the code's optimization is potentially spread out in parallel over all the projects that include it. Thusly, the effectiveness of one optimization could be more than originally thought.
This is espcially true with javascript, and how it is copied and pasted from website to website on a regular basis.
Besides, I did that optimization instinctually when I went through and tried to write that code... shortcircuiting is a tool that should be used when availble, regardless. Its such a simple bit of tweaking that when applied uniformially, can reduce a large amount of comparitors.
captcha: gotcha, like I just gotcha with a burn.
Admin
Ajax?
Admin
A long time ago (well 4 or 5 years ago...) In a galaxy far, far away... I worked on an intranet app using classic asp and (have to restrain myself when typing) a VB middle tier, as the app was (at the time) fairly simple and XML and XSL(T) was all the rage the asp was just a transform engine: calling the VB tier, getting XML back and transforming it into HTML. As the app grew (scope creep: good old PMs), so the amount of XML that needed to be transformed grew and MSXML n (can't remember the version, thank God) couldn't cope. So, guess what? We got back only the data that was required for initial page display, then as users expanded nodes in our grid, we got the data that was needed for that part of the page and did a partial page update.
If only I'd come up with a fancy TLA or FLA and posted about it at the time: I could be rich...
One million dollars...
Ah well, back to the real world.
May the force be with you...
Admin
Admin
It is totally a premature optimization. A couple of mod operations are nothing compared to a database transaction. This would basically have to run as one of the most expensive operation in a loop millions of times before you would see any gain at all from optimization.
Admin
Not that anyone will read through over 100 comments to get here, but I have to defend my function in actionscript. Granted, it was a little lazy to put an "(s)" at the end of the string, but that wasn't really the point. The point was to show what someone (who is working professionally and making more money than myself) can butcher in 50 lines of javascript and still not have correct output. The actionscript function was to show how you can build a similar function with correct output in 4 lines. If you test the javascript function with some numbers, you'll see what I mean easier than trying to wade through it. And lastly, 3500 was the number of bytes someone arbitrarily decided to could be transferred per second using a 56k connection. Probably the same dude who wrote the first function....
Admin
Good Idea, xept you always do 3 comparisons, also 2001, 2002, 2003 would all be leap years! !=P
close, but no cigar.
personally, except for reverse logic (which some consider bad programming practice, and its harder to read), i think the negative checking is optimal no?
you know, like someone said earlier:
if (year % 4 != 0) return false if (year % 100 != 0) return true if (year % 400 != 0) return false return true
Admin
or better yet like this right, one liner?
return year % 4 != 0 ? false : year % 100 != 0 ? true : year % 400 != 0 ? false : true;
Admin
Admin
This seems to work in C; wouldn't recommend it. :) (^ is exclusive-or.)
leap=!(year%4)^!(year%100)^!(year%400);
Admin
Admin
If you really want to be picky then your algorithm should take into account that the formula for leap years might change in the future and it hasn't always been the same in the past. Probably the best way is to use the date functions of the language to check for Feb29. That way your code is automatically updated with the language if changes are made.
Some people are criticising the use of just a simple mod four check. Of course you would'nt use such a simplification for a reusable function. However in some cases it might be appropriate. For example if you're sanitizing you input for a particular date range anyway, then you might not need to worry. If it was an embedded system like a wrist watch, then I'd probably stick with just the mod four check. Another thing to consider is that generally the more complex your code is the more likely you are to make mistakes. If you mess up the logic then your code might work fine in your tests on this years data, and then corrupt data four years from now. This is simple enough though that I would probably almost always just do it right, because just figuring out whether a simple mod four check might fail would be almost as time consuming as implementing the full algorithm.
Another problem with the WTF example is that it checks for a period. I don't know about how Javascript handles it but in some locales the decimal point isn't a point but rather a comma.
Admin
Agreed.
Coding an incomplete leap year function is very likely a premature optimization. Fire up a profiler AFTER you have an application written and THEN tell us if the leap year function is a performance hit when in actual use.
There are too many benefits to coding it right the first time.
Our job as developers is to create correct code. As far as performance goes, choose algorithms/data structures intelligently, then use a profiler to find out where the actual bottlenecks are.
Rationalizing writing incomplete functions or using code that has known side effects that will "never happen" is just arrogance on display. We don't always know better as developers, even if we think we do.
Admin
Excusible for teenagers my ass. Maybe someone who's just starting out and doesnt know that it's more logical to compare a number to a number using built in functions/properties/operators, etc -- But I'm 17 and would rather choke myself with my wireless mouse cord than code like that
I'm just getting over the negative number one posted a few weeks ago:
if (number.toString().substr(0,1) == '-') { ...
captcha: ewww (yes, this code was)
Admin
I was at a meeting a few weeks ago in which a "user design expert" noted that the UI we were starting to think about would, of course, use Ajax to provide things like right-click menus. Luckily, he was on the other end of an intercontinental phone line, so I wasn't quite able to get my hands around his neck.
You're all wrong. Ajax is my dog. And no, before anyone asks, he cannot learn new tricks ...
Admin
For those worried about a mod four version of the leap year function being reused by uninformed programmers, a simple partial solution is to include a comment that mod four might not work for years not between 1901 and 2099.
The simple mod four algorithm does work for 2000 by the way, so it has a decent almost 200 year range of validity around the present.
Admin
[quote user="RobFreundlich"][quote user="Anon"]Plus there are the people who've started to use AJAX to mean "any webpage with JavaScript on it" which is also annoying.[/quote]
zOMG I'm SICK of that!!! Almost as much as I am about people referring to AJAX as a "technology".
Why is it that people think "super pimp JS" == "AJAX"? Damn corporati and their buzzwords... grumblegrumble
Admin
///
Admin
If this wouls stop with numbers, I'd be happy. Check the E4X (ECMAScript/JavaScript for XML) specification. The goal of the language (providing an easy-to-use XML API) may have been a sucess but some of the people who wrote this apparently couldn't think in anything else than strings either. There are some places where it literally demands that implementations must toString() XML objects, manipulate the string representation and the parse them back in. Good luck integrating that in existing DOM APIS...
Admin
ahhh, grasshopper, javascript already know if is leapyear!
function IsLeapYear(year) { var LastDayinFeb = new Date(year, 3, 0); return (LastDayinFeb.getDate() == 29); }
Admin
or, to be terse,
function IsLeapYear(year){return (new Date(year, 3, 0)).getDate() == 29);}
Admin
thats some pretty bad stuff, JUST LIKE THIS FORUM SOFTWARE
Admin
Yeah, my poor writing skills are the real WTF. I was referring to the client side validation.
You raise a good point about saving server load; hadn't really thought about it that way, but I think in some cases it's doing more than just a "is it filled out".
Range checking on some fields, for example... We changed the possible values from 0 < n < 100 to -1 < n < 100. Somebody forgot to update the validator...
Admin
While I agree that optimizing a leap-year function is an overkill, it would still make more sense to put year%4 test first, as this is (I think) most people would test first (rules first, then exceptions).
Of course, the major WTF here is the solar system itself and/or our insistence on a circular calendar system where the days start over each year.
Admin
Only as many as there are numbers which are divisible by 400.
Admin
So many leap year algorithms, in Java no less, and I only see one mention of
WTF?
Admin
Now we know why there was so much confusion. We were in Java, not Javascript? Wait, do I have that backwards?
Admin
Maybe but those people don't post here ;)
... I hope o_o
Admin
AJAX - when you say hey to your pal named Jax! AJAX!
Really lets call it Web 2.0 instead and then we can all be impressed...
I know let's use that and a database and
yeah, and that page uses black magic to tell what content to load ;)
and, btw the code is ill formatted, but just be glad it had a CrLf at all it doesn't have to...
Admin
AJAX - when you say hey to your pal named Jax! AJAX!
Really lets call it Web 2.0 instead and then we can all be impressed...
I know let's use that and a database and
yeah, and that page uses black magic to tell what content to load ;)
and, btw the code is ill formatted, but just be glad it had a CrLf at all it doesn't have to...
Admin
Do a Google search for "javscript email validation"
First link you get: function echeck(str) {
function ValidateForm(){ var emailID=document.frmSample.txtEmail
}
Yuck. Where's a regex when you need one?
Admin
hah since this was declared "a big wtf" by several others, let me explain what I meant with the word "assuming" in the beginning. If I know I can do that assumption it's adequate, what if there is no big picture.
I can do the correct implementation but if this function was ever required from me I probably would avoid it (unless, of course, it would calculate on other dates than the current). I work embedded, usually on too small targets (i.e. always think optimise for size, for all you windows wankers size is the bytes and the kilobytes and the megabytes, yes applications also occupy those) and that code will be useless long before the next century. Is that a reason good enough for you? This is not a defense for that javascript code (that won't be in embedded) but rather a beration of the know-it-alls crowding this site, trying to excel in their own brillance.
And yeah some would call me lazy too, but let's call it optimised for speed.
Admin
There is optimization then there is OPTIMIZATION.
I agree that it isn't always necessary to spent a ton of time to hand tweak, hand write in assembly, every last bit of code to wring out every last bit of optimization.
BUT when you can do optimization, for pretty much for free. Doesn't reduce the readibility/maintainability of the code. You should do it. Every little bit counts.
Just simply moving the mod 4 check, and to a != and placing it at the top of the function, speeds this code up. Why not do it? Someone coming along latter is going to wonder WTF, will make the change (and you know every change has the potential to break code) It is easy to spot that this is an optimization. Its one a compiler can't make. The code is just as easy to read, and makes just as much sense.
If you guys are the ones writing the software I use, no wonder it is freaking slow.
Admin