BusinessRx Community

Dedicated to the advancement of software, technology and the people who devote their lives to it.

Welcome to BusinessRx Community Sign in | Join | Help
in Search

BusinessRx Reading List

These blog entries are written by industry experts and leaders. We consider this content to be a good read for any software developer or web technologist.

What’s Wrong With This Code? (#21)

This version of WWWTC is dedicated to closures. We can use closures and functional programming in general to create elegant, succinct solutions, but sometimes we can also create subtle bugs. 

Exhibit A. The C# developer who wrote this code expected DoSomething to be invoked with the values 0 through 9, but something is terribly wrong.

for (int counter = 0; counter < 10; counter++)
{
    ThreadPool.QueueUserWorkItem(
        state => DoSomething(counter)
    );
}

What’s the problem?

Bonus Round

A JavaScript developer is working with the following markup.

<div class="header">
    <div class="detail">Detail 1 …</div>
</div>
<div class="header">
    <div class="detail">Detail 2 …</div>
</div>
<!-- and so on-->

When the user clicks inside a detail section, the developer wants to change the background color of all the other header sections. Thinking of one way to achieve this behavior, the developer first tests the jQuery not method.

$(function() {
    $(".header").each(function() {
        alert($(".header").not(this).length);
        return false;
    });
});

This code correctly alerts the user once and displays the total number of headers – 1.Emboldened with this proof of concept, the developer puts in the required CSS manipulation and embeds the code into a click event handler.

$(function() {
    $(".header").each(function() {
        $(".detail", this).click(function() {                    
            $(".header").not(this).css("background-color", "red");
        });
    });
});    

Suddenly, things aren’t working and every header section turns red. What went wrong?

Published Tuesday, January 27, 2009 5:30 AM by OdeToCode Blogs

Comment Notification

If you would like to receive an email when updates are made to this post, please register here

Subscribe to this post's comments using RSS

Comments

No Comments

Leave a Comment

(required) 
(optional)
(required) 
Submit

This Blog

Syndication

Powered by Community Server, by Telligent Systems
'