CodeSOD: Three Links

Brian's hired a contractor to tackle a challenging technical problem: they wanted to display three links in three table cells. Now, you or I might just write that as HTML. But if we did that, we'd lose the opportunity to do this in JavaScript. Plus think of all that repetition- you'll be outputting a <td></td> tag pair three times. That's just wasteful.

No, what we need is some elegant JavaScript solution that solves this problem without any unnecessary repetition.

for(i = 0; i < 3; i++) { link += '<tr>'; link += '<td class=\'CopyRightInfo\' style=\'text-align: left; cursor: pointer; color: #000000;\'>'; if(i == 0) { link += '<a href=\'#\' onclick=\'javascript:window.open(\"https://www.somesite.com/");\' >Login</a>'; } else if(i == 1) { link +='<a href=\'/Address/Configure.aspx\' >Configure</a>'; } else if(i == 2) { link +='<a href=\'#\' onclick=\'javascript:window.open(\"https://signup.someothersite.com/\");\'>Sign Up</a>'; } link += '</td>'; link += '<tr>'; }

Here we employ the For-Case antipattern to write a loop where we do something different on each iteration. That's a classic WTF, but here it's elevated through how unnecessary all of this really is. Plus we get the bonuses of style overrides, and the number of escaped quotes- but inconsistently and needlessly so. Take a look at the i == 0 branch- the double quote doesn't need to be escaped, and one time it isn't.

Suffice to say, this contractor's code wasn't used, and neither was that contractor after this.

[Advertisement] Otter - Provision your servers automatically without ever needing to log-in to a command prompt. Get started today!

This post originally appeared on The Daily WTF.

Leave a Reply

Your email address will not be published. Required fields are marked *