<?xml version="1.0" encoding="UTF-8"?>
<feed xml:lang="en-US" xmlns="http://www.w3.org/2005/Atom">
  <id>tag:refactormycode.com,2007:users399</id>
  <link type="application/atom+xml" href="http://refactormycode.com/users/399" rel="self"/>
  <title>Casper</title>
  <updated>Sun Jan 13 14:05:43 +0000 2008</updated>
  <entry>
    <id>tag:refactormycode.com,2007:Refactor1509</id>
    <published>2008-01-13T14:05:43+00:00</published>
    <title>[JavaScript] On How to Refactor from a Loop... to no Loops...</title>
    <content type="html">&lt;p&gt;Yes a construction like that gets too complicated for fancy one-liner CSS selecting.
&lt;br /&gt;So you need to do it &amp;quot;manually&amp;quot;. I also found a bug in the selector for the text field so I updated that one. &lt;/p&gt;

&lt;p&gt;Here's the refactored line:&lt;/p&gt;

&lt;pre&gt;
   $$(&amp;quot;.fieldpair&amp;quot;).each(function(fieldpair) {
      if (fieldpair.down(&amp;quot;input:checked&amp;quot;)) {
         var input = fieldpair.down('input:[type=&amp;quot;textfield&amp;quot;]');
         log(&amp;quot;  Adding: &amp;quot; + input.value);
         total += parseInt(input.value);
      }
   });

&lt;/pre&gt;</content>
    <author>
      <name>Casper</name>
      <email>casper.cg@gmail.com</email>
    </author>
    <link type="text/html" href="http://refactormycode.com/codes/199-how-to-refactor-from-a-loop-to-no-loops/refactors/1509" rel="alternate"/>
  </entry>
  <entry>
    <id>tag:refactormycode.com,2007:Refactor1505</id>
    <published>2008-01-13T12:16:52+00:00</published>
    <title>[JavaScript] On How to Refactor from a Loop... to no Loops...</title>
    <content type="html">&lt;p&gt;Change the '+' to '~' and you should be good to go :)&lt;/p&gt;

&lt;p&gt;You can read about CSS3 selectors here:
&lt;br /&gt;&lt;a href="http://www.w3.org/TR/css3-selectors/" target="_blank"&gt;http://www.w3.org/TR/css3-selectors/&lt;/a&gt;
&lt;/p&gt;

&lt;pre&gt;&lt;/pre&gt;</content>
    <author>
      <name>Casper</name>
      <email>casper.cg@gmail.com</email>
    </author>
    <link type="text/html" href="http://refactormycode.com/codes/199-how-to-refactor-from-a-loop-to-no-loops/refactors/1505" rel="alternate"/>
  </entry>
  <entry>
    <id>tag:refactormycode.com,2007:Refactor1473</id>
    <published>2008-01-11T09:51:21+00:00</published>
    <title>[Ruby] On Rails has_many count</title>
    <content type="html">&lt;p&gt;Or..come to think of it. This is a perfect place for an SQL JOIN. Databases love to do these kinds of things. And they do it fast. Here's a good place to read up on joins:&lt;/p&gt;

&lt;p&gt;&lt;a href="http://www.w3schools.com/sql/sql_join.asp" target="_blank"&gt;http://www.w3schools.com/sql/sql_join.asp&lt;/a&gt;&lt;/p&gt;

&lt;p&gt;Solution now becomes:
&lt;/p&gt;

&lt;pre&gt;# Untested since I don't have your database, but it should be 
# something like this:
grouped_count = Messages.count(:conditions =&amp;gt; &amp;quot;user_id = #{current_user.id}&amp;quot;,
                               :joins      =&amp;gt; &amp;quot;join users on sender_id = users.id&amp;quot;,
                               :group      =&amp;gt; &amp;quot;usertype&amp;quot;)


# You will get back an ActiveSupport::OrderedHash
# which you can loop like this:

grouped_count.each do |usertype, count|
  puts &amp;quot;#{userype}: #{count}&amp;quot;
end


&lt;/pre&gt;</content>
    <author>
      <name>Casper</name>
      <email>casper.cg@gmail.com</email>
    </author>
    <link type="text/html" href="http://refactormycode.com/codes/209-rails-has_many-count/refactors/1473" rel="alternate"/>
  </entry>
  <entry>
    <id>tag:refactormycode.com,2007:Refactor1471</id>
    <published>2008-01-11T08:59:48+00:00</published>
    <title>[Ruby] On Rails has_many count</title>
    <content type="html">&lt;p&gt;Not going to comment on the Rails parts (you should move more code into the Model, and have less in your view). Just the &amp;quot;rubyism&amp;quot; part. &lt;/p&gt;

&lt;p&gt;Since you have all the cross references in your models you should be able to access all messages for a user by saying user.messages, and access senders of messages by doing message.sender.&lt;/p&gt;

&lt;p&gt;Then we group the usertype counters into a hash, so we don't have to hard-code all that stuff and the code stays flexible and &amp;quot;adapts&amp;quot; when you add new user types.
&lt;/p&gt;

&lt;pre&gt;# Get all messages for the current user
messages_for_user = current_user.messages

# Initialize our hash where we store the counters
message_type_counters = Hash.new

# Loop through the messages
messages_for_user.each do |msg|
  
  # Grab the usertype of the sender
  usertype = msg.sender.usertype

  # Make sure the hash element is initialized
  message_type_counters[usertype] ||= 0

  # Add to the counter
  message_type_counters[usertype] += 1

end

# Display the results
message_type_counters.each do |usertype, count|
  puts &amp;quot;#{usertype}: #{count}&amp;quot;
end

&lt;/pre&gt;</content>
    <author>
      <name>Casper</name>
      <email>casper.cg@gmail.com</email>
    </author>
    <link type="text/html" href="http://refactormycode.com/codes/209-rails-has_many-count/refactors/1471" rel="alternate"/>
  </entry>
  <entry>
    <id>tag:refactormycode.com,2007:Refactor1447</id>
    <published>2008-01-09T20:22:53+00:00</published>
    <title>[JavaScript] On How to Refactor from a Loop... to no Loops...</title>
    <content type="html">&lt;p&gt;
Jermaine you are welcome. For Prototype it's best just to read the API docs:
&lt;br /&gt;&lt;a href="http://www.prototypejs.org/api/" target="_blank"&gt;http://www.prototypejs.org/api/&lt;/a&gt;&lt;/p&gt;

&lt;p&gt;They are pretty good, and contain some decent examples. Usually when there's something I can't figure out how to do, and I can't find it in the API docs, I search with google &amp;quot;prototype javascript &amp;lt;the thing I want to do&amp;gt;&amp;quot;. You will find some good snippets and examples that way. Just keep at it and it will get easier with a little time and experience :) Good luck.&lt;/p&gt;

&lt;p&gt;&lt;/p&gt;

&lt;pre&gt;&lt;/pre&gt;</content>
    <author>
      <name>Casper</name>
      <email>casper.cg@gmail.com</email>
    </author>
    <link type="text/html" href="http://refactormycode.com/codes/199-how-to-refactor-from-a-loop-to-no-loops/refactors/1447" rel="alternate"/>
  </entry>
  <entry>
    <id>tag:refactormycode.com,2007:Refactor1443</id>
    <published>2008-01-09T14:18:08+00:00</published>
    <title>[JavaScript] On How to Refactor from a Loop... to no Loops...</title>
    <content type="html">&lt;p&gt;You have a couple of bugs. First IDs always need to be unique in your HTML code. Now you've named them all &amp;quot;unique_line&amp;quot;. That's invalid HTML. You need to name them &amp;quot;unique_line_1/2/3/4&amp;quot; in case that's the way you want to do it.&lt;/p&gt;

&lt;p&gt;Second..onclick=&amp;quot;remove_line&amp;quot;..remove_line will be called with the element that triggered the event as an argument. From there you could traverse up the DOM to find your fieldpair and remove it. No need for unique ID's.&lt;/p&gt;

&lt;p&gt;Third. If you're practicing UJS then you've been naughty and added an onclick event in the HTML for your &amp;quot;Add a new line&amp;quot; link. That's not UJS :) UJS means no Javascript among your HTML code.&lt;/p&gt;

&lt;p&gt;Now..I fiddled a little with the code and added some fancy schmancy Scriptaculuos effects to it also to make the adding and removing of lines appear smooth and &amp;quot;hey that's neat&amp;quot; web 2.0-ish.&lt;/p&gt;

&lt;p&gt;Google for Scriptaculous to find their package. Download it, extract it, and put all the files from the &amp;quot;lib&amp;quot; directory of the package into a directory you name &amp;quot;scriptaculous&amp;quot; that sits in the same directory where you have your &amp;quot;prototype.js&amp;quot; file. That way you can load the scriptaculous stuff in your HTML code by including scriptaculous/scriptaculous.js, as I've done in the example below.&lt;/p&gt;

&lt;p&gt;If you don't want the scriptaculous effects just remove it from my code and remove the &amp;quot;Effect.*&amp;quot; code lines. Also note that I add the new fieldpair as &amp;quot;display: none&amp;quot;, so that the scriptaculous effect can later reveal it. If you remove the effects also remember to remove that style. Otherwise the new fieldpair line will never show up.&lt;/p&gt;

&lt;p&gt;Here's the code:
&lt;/p&gt;

&lt;pre&gt;## Javascript [javascript]

// Nice to have for debugging purposes if you don't happen
// to have Firefox + Firebug installed.
function log(s) { 
   $(&amp;quot;log&amp;quot;).insert(s + &amp;quot;\n&amp;quot;)
}

// Our main calculation function
function calculate() {
   log(&amp;quot;calculate()&amp;quot;);
   var total = 0;
   
   // For each fieldpair that has a child with a checked input
   // we get the sibling with a text input and add that value
   // to the total. jQuery does all the tricky element traversals
   // for us.

   $$(&amp;quot;.fieldpair input:checked + input:text&amp;quot;).each(function(elem) {
      log(&amp;quot;  Adding: &amp;quot; + elem.value);
      total += parseInt(elem.value);
   });

   // Show the result
   $(&amp;quot;result&amp;quot;).update(&amp;quot;The total is: &amp;quot; + total);
}

function add_line() {
   // insert() inserts at bottom by default
   $(&amp;quot;calculation_area&amp;quot;).insert(
     '&amp;lt;div class=&amp;quot;fieldpair&amp;quot; style=&amp;quot;display: none&amp;quot;&amp;gt;' +
     '  &amp;lt;input type=&amp;quot;checkbox&amp;quot;/&amp;gt;' +
     '  &amp;lt;input type=&amp;quot;textfield&amp;quot; value=&amp;quot;10&amp;quot;/&amp;gt;' +
     '  &amp;lt;a href=&amp;quot;#&amp;quot;&amp;gt;Remove&amp;lt;/a&amp;gt;' +
     '&amp;lt;/div&amp;gt;' 
   );

   // Since we just inserted the element as the last
   // element of the calculation_area div it's easy
   // to grab it like this:
   var fieldpair = $(&amp;quot;calculation_area&amp;quot;).childElements().last();
   
   // Now we can use CSS selectors to select the other
   // elements inside the new fieldpair div, and add
   // the event observers we want.
   fieldpair.down(&amp;quot;input:checkbox&amp;quot;).observe('click', calculate);
   fieldpair.down(&amp;quot;input:text&amp;quot;).observe('keyup', calculate);
   fieldpair.down(&amp;quot;a&amp;quot;).observe('click', remove_line);

   // Scriptaculous effect
   Effect.BlindDown(fieldpair, { duration: 0.4 });
}

function remove_line(event) {
   // Prototype always calls observers with the
   // event as argument. From there we can grab the
   // element that triggered the event, and from there
   // we use a CSS selector to find the first parent
   // element (up-element) that matches the &amp;quot;.fieldpair&amp;quot;
   // div. And then we remove it from the DOM. Easy :)
   var fieldpair = event.element().up(&amp;quot;.fieldpair&amp;quot;);

   // Scriptaculuos effect
   Effect.BlindUp(fieldpair, { 
      duration: 0.4,
      afterFinish: function() {
         // Remove the element from the DOM
         fieldpair.remove();

         // Recalculate our result since the box might
         // have been checked.
         calculate();
      }
   });

   // If you don't want the effects just delete the
   // Effect stuff above and uncomment the lines below:
   // 
   // fieldpair.remove();
   // calculate();
}

// This is called when the document DOM has 
// been fully loaded by the browser.
Event.observe(window, 'load', function() {
   log(&amp;quot;Our output log&amp;quot;);
   log(&amp;quot;==============&amp;quot;);
   log(&amp;quot;ready()&amp;quot;);

   // Do the initial calculation. Some fields might be pre-checked.
   calculate();
   
   // Attach event handlers for click event on checkboxes
   $$(&amp;quot;.fieldpair input:checkbox&amp;quot;).each(function(elem) {
      elem.observe('click', calculate);
   });
   
   // Attach event handlers for keyup event on text fields
   $$(&amp;quot;.fieldpair input:text&amp;quot;).each(function(elem) {
      elem.observe('keyup', calculate);
   });

   // Attach click handler to the add button
   $(&amp;quot;add_button&amp;quot;).observe('click', add_line);
});

## HTML [html]

&amp;lt;script type=&amp;quot;text/javascript&amp;quot; src=&amp;quot;prototype.js&amp;quot;&amp;gt;&amp;lt;/script&amp;gt;
&amp;lt;script type=&amp;quot;text/javascript&amp;quot; src=&amp;quot;scriptaculous/scriptaculous.js&amp;quot;&amp;gt;&amp;lt;/script&amp;gt;

&amp;lt;div id=&amp;quot;calculation_area&amp;quot;&amp;gt;

&amp;lt;div class=&amp;quot;fieldpair&amp;quot;&amp;gt;
  &amp;lt;input type=&amp;quot;checkbox&amp;quot; checked=&amp;quot;1&amp;quot;/&amp;gt;
  &amp;lt;input type=&amp;quot;textfield&amp;quot; value=&amp;quot;10&amp;quot; /&amp;gt;
&amp;lt;/div&amp;gt;

&amp;lt;div class=&amp;quot;fieldpair&amp;quot;&amp;gt;
  &amp;lt;input type=&amp;quot;checkbox&amp;quot; /&amp;gt;
  &amp;lt;input type=&amp;quot;textfield&amp;quot; value=&amp;quot;20&amp;quot; /&amp;gt;
&amp;lt;/div&amp;gt;

&amp;lt;div class=&amp;quot;fieldpair&amp;quot;&amp;gt;
  &amp;lt;input type=&amp;quot;checkbox&amp;quot; /&amp;gt;
  &amp;lt;input type=&amp;quot;textfield&amp;quot; value=&amp;quot;30&amp;quot; /&amp;gt;
&amp;lt;/div&amp;gt;

&amp;lt;/div&amp;gt;

&amp;lt;button id=&amp;quot;add_button&amp;quot;&amp;gt;Add a new line&amp;lt;/button&amp;gt;

&amp;lt;p id=&amp;quot;result&amp;quot;&amp;gt;
&amp;lt;/p&amp;gt;

&amp;lt;pre id=&amp;quot;log&amp;quot;&amp;gt;
&amp;lt;/pre&amp;gt;



&lt;/pre&gt;</content>
    <author>
      <name>Casper</name>
      <email>casper.cg@gmail.com</email>
    </author>
    <link type="text/html" href="http://refactormycode.com/codes/199-how-to-refactor-from-a-loop-to-no-loops/refactors/1443" rel="alternate"/>
  </entry>
  <entry>
    <id>tag:refactormycode.com,2007:Refactor1327</id>
    <published>2008-01-02T00:19:39+00:00</published>
    <title>[JavaScript] On How to Refactor from a Loop... to no Loops...</title>
    <content type="html">&lt;p&gt;There was a semicolon missing in the first edit I posted. Maybe you copied that version? I tested the code over here on Firefox with Prototype 1.6. Recopy the code and try putting an alert() statement on line 28 before the first log() call to see if the window load event is getting triggered. Then keep putting alert statements further down to see how far it gets. The missing semicolon was in the log() method, so that probably killed it before.&lt;/p&gt;

&lt;p&gt;Oh and just to double check..remember if you were using the jQuery version - do not load jQuery at the same time you load Prototype. The are not compatible. So remove the &amp;lt;script&amp;gt; tag that loads jQuery before you try it with Prototype. 
&lt;/p&gt;

&lt;pre&gt;&lt;/pre&gt;</content>
    <author>
      <name>Casper</name>
      <email>casper.cg@gmail.com</email>
    </author>
    <link type="text/html" href="http://refactormycode.com/codes/199-how-to-refactor-from-a-loop-to-no-loops/refactors/1327" rel="alternate"/>
  </entry>
  <entry>
    <id>tag:refactormycode.com,2007:Refactor1325</id>
    <published>2008-01-01T22:03:47+00:00</published>
    <title>[JavaScript] On How to Refactor from a Loop... to no Loops...</title>
    <content type="html">&lt;p&gt;Hi. The Prototype code is similar to jQuery. Method names are a little different and Prototype uses $$() as a CSS selector and $() as an element id selector, so we have to update those. Also in Prototype you loop arrays manually (with function(element) { ... }) most of the time, so we update for that too. Here's the Prototype version. Enjoy :)&lt;/p&gt;

&lt;p&gt;&lt;/p&gt;

&lt;pre&gt;## Javascript Prototype version [javascript_+_prototype]

// Nice to have for debugging purposes if you don't happen
// to have Firefox + Firebug installed.
function log(s) { 
   $(&amp;quot;log&amp;quot;).insert(s + &amp;quot;\n&amp;quot;);
}

// Our main calculation function
function calculate() {
   log(&amp;quot;calculate()&amp;quot;);
   var total = 0;
   
   // For each fieldpair that has a child with a checked input
   // we get the sibling with a text input and add that value
   // to the total. 

   $$(&amp;quot;.fieldpair input:checked + input:text&amp;quot;).each(function(elem) {
      log(&amp;quot;  Adding: &amp;quot; + elem.value);
      total += parseInt(elem.value);
   });

   // Show the result
   $(&amp;quot;result&amp;quot;).update(&amp;quot;The total is: &amp;quot; + total);
}

// This is called when the document DOM has 
// been fully loaded by the browser.
Event.observe(window, 'load', function() {
   log(&amp;quot;Our output log&amp;quot;);
   log(&amp;quot;==============&amp;quot;);
   log(&amp;quot;ready()&amp;quot;);

   // Do the initial calculation. Some fields might be pre-checked.
   calculate();
   
   // Attach event handlers for click event on checkboxes
   $$(&amp;quot;.fieldpair input:checkbox&amp;quot;).each(function(elem) {
      elem.observe('click', calculate);
   });
   
   // Attach event handlers for keyup event on text fields
   $$(&amp;quot;.fieldpair input:text&amp;quot;).each(function(elem) {
      elem.observe('keyup', calculate);
   });
});

&lt;/pre&gt;</content>
    <author>
      <name>Casper</name>
      <email>casper.cg@gmail.com</email>
    </author>
    <link type="text/html" href="http://refactormycode.com/codes/199-how-to-refactor-from-a-loop-to-no-loops/refactors/1325" rel="alternate"/>
  </entry>
  <entry>
    <id>tag:refactormycode.com,2007:Refactor1313</id>
    <published>2008-01-01T09:41:40+00:00</published>
    <title>[JavaScript] On How to Refactor from a Loop... to no Loops...</title>
    <content type="html">&lt;p&gt;I like to do these kinds of things using Unobtrusive Javascript (UJS). UJS is a way to keep the code logic of your page completelty separate from the presentation (the HTML). The idea with UJS is like CSS is for page styling. CSS allows you to keep the styling information neatly separate from the HTML code. The same with UJS. It keeps the Javascript separate so it does not clutter the HTML. Your pages become easier to read, modify and maintain.&lt;/p&gt;

&lt;p&gt;UJS is possible because you can instruct the browser to start your Javascript code once the browser has finished completley loading the page. That way you can layer your functionality onto the page very neatly after the browser has finished loading all HTML.&lt;/p&gt;

&lt;p&gt;In addition to using UJS it is highly recommended to use some sort of Javascript library to make all those cumbersom loops and findElementById() trickery go away.&lt;/p&gt;

&lt;p&gt;Here I'm using jQuery, but Prototype for example will work just as well. &lt;/p&gt;

&lt;p&gt;About the loop. I wouldn't try to get rid of looping. It's easy to get your calculations out of sync if you do not loop over all the checkbox/input-field pairs in one go. Looping guarantees you don't need extra magic code to double check that you really did calculate everything correctly.&lt;/p&gt;

&lt;p&gt;The idea with the implementation below is that it's completely dynamic. If you want to add a new set of checkbox/input-field pairs you just insert it into the page as a div with a class of &amp;quot;fieldpair&amp;quot;. The code will automatically adapt and include the new field pair into the calculations.&lt;/p&gt;

&lt;p&gt;Here we go. First the HTML, and then the jQuery code.&lt;/p&gt;

&lt;p&gt;&lt;/p&gt;

&lt;pre&gt;## The HTML part [html]

&amp;lt;!-- Load jQuery --&amp;gt;
&amp;lt;script type=&amp;quot;text/javascript&amp;quot; 
        src=&amp;quot;http://jqueryjs.googlecode.com/files/jquery-1.2.1.js&amp;quot;&amp;gt;&amp;lt;/script&amp;gt;

&amp;lt;script type=&amp;quot;text/javascript&amp;quot;&amp;gt;
  &amp;lt;!-- Insert the Javascript code from below here --&amp;gt;
&amp;lt;/script&amp;gt;

&amp;lt;!-- Some fieldpairs. Insert as many as you like --&amp;gt;
&amp;lt;div class=&amp;quot;fieldpair&amp;quot;&amp;gt;
  &amp;lt;input type=&amp;quot;checkbox&amp;quot; checked=&amp;quot;1&amp;quot;/&amp;gt;
  &amp;lt;input type=&amp;quot;textfield&amp;quot; value=&amp;quot;10&amp;quot; /&amp;gt;
&amp;lt;/div&amp;gt;

&amp;lt;div class=&amp;quot;fieldpair&amp;quot;&amp;gt;
  &amp;lt;input type=&amp;quot;checkbox&amp;quot; /&amp;gt;
  &amp;lt;input type=&amp;quot;textfield&amp;quot; value=&amp;quot;20&amp;quot; /&amp;gt;
&amp;lt;/div&amp;gt;

&amp;lt;div class=&amp;quot;fieldpair&amp;quot;&amp;gt;
  &amp;lt;input type=&amp;quot;checkbox&amp;quot; /&amp;gt;
  &amp;lt;input type=&amp;quot;textfield&amp;quot; value=&amp;quot;30&amp;quot; /&amp;gt;
&amp;lt;/div&amp;gt;

&amp;lt;!-- Result goes here --&amp;gt;
&amp;lt;p id=&amp;quot;result&amp;quot;&amp;gt;
&amp;lt;/p&amp;gt;

&amp;lt;!-- This we just use for our debugging --&amp;gt;
&amp;lt;pre id=&amp;quot;log&amp;quot;&amp;gt;
&amp;lt;/pre&amp;gt;


## The jQuery Javascript code [jquery_javascript]

// Nice to have for debugging purposes if you don't happen
// to have Firefox + Firebug installed.
function log(s) { 
   $(&amp;quot;#log&amp;quot;).append(s + &amp;quot;\n&amp;quot;); 
}

// Our main calculation function
function calculate() {
   log(&amp;quot;calculate()&amp;quot;);
   var total = 0;
   
   // This is the loop that selects our fieldpairs. It's nice and
   // neat with jQuery element selectors.
   // 
   // For each fieldpair that has a child with a checked input
   // we get the sibling with a text input and add that value
   // to the total. jQuery does all the tricky element traversals
   // for us.

   $(&amp;quot;.fieldpair&amp;quot;).children(&amp;quot;input:checked&amp;quot;).siblings(&amp;quot;input:text&amp;quot;).each(function() {
      log(&amp;quot;  Adding: &amp;quot; + this.value);
      total += parseInt(this.value);
   });

   // Show the result
   $(&amp;quot;#result&amp;quot;).text(&amp;quot;The total is: &amp;quot; + total);
}

// This is called when the document DOM has been fully loaded by the browser.
$(document).ready(function() {
   // Here we go...start 'er up...
   log(&amp;quot;Our output log&amp;quot;);
   log(&amp;quot;==============&amp;quot;);
   log(&amp;quot;ready()&amp;quot;);

   // Do the initial calculation. Some fields might be pre-checked.
   calculate();
   
   // Attach event handlers for click event on checkboxes
   $(&amp;quot;.fieldpair&amp;quot;).children(&amp;quot;input:checkbox&amp;quot;).click(calculate);
   
   // Attach event handlers for keyup event on text fields
   $(&amp;quot;.fieldpair&amp;quot;).children(&amp;quot;input:text&amp;quot;).keyup(calculate);
});

&lt;/pre&gt;</content>
    <author>
      <name>Casper</name>
      <email>casper.cg@gmail.com</email>
    </author>
    <link type="text/html" href="http://refactormycode.com/codes/199-how-to-refactor-from-a-loop-to-no-loops/refactors/1313" rel="alternate"/>
  </entry>
  <entry>
    <id>tag:refactormycode.com,2007:Refactor1033</id>
    <published>2007-12-07T19:35:52+00:00</published>
    <title>[PHP] On Output div block with PHP conditional statement</title>
    <content type="html">&lt;p&gt;You have a missing close brace &amp;quot;}&amp;quot; before the else statement.&lt;/p&gt;

&lt;p&gt;Also when you have a lot of HTML code it's easier not to &amp;quot;echo&amp;quot; it, just type it out outside the PHP block instead, and keep the PHP code inside the &amp;lt;? ?&amp;gt; blocks. See below alternative 1.&lt;/p&gt;

&lt;p&gt;Or..if you have a big block of text you can use what's called the heredoc operator. This will let you type in quotes and any text until the end of the heredoc. See alternative 2. Not as &amp;quot;clean&amp;quot; as alternative 1 perhaps, but demonstrates the heredoc operator.&lt;/p&gt;

&lt;p&gt;&lt;/p&gt;

&lt;pre&gt;## Alternative 1: HTML code outside the PHP blocks [php]

&amp;lt;?php if (the_ID() == 8) { ?&amp;gt;
  &amp;lt;div id=&amp;quot;menu_show&amp;quot; class=&amp;quot;slideshow&amp;quot;&amp;gt;
    &amp;lt;img src=&amp;quot;...&amp;quot; /&amp;gt;
  &amp;lt;/div&amp;gt;
&amp;lt;?php } else { ?&amp;gt;
  &amp;lt;div class=&amp;quot;header&amp;quot;&amp;gt;&amp;lt;/div&amp;gt;
&amp;lt;?php } ?&amp;gt;

## Alternative 2: HTML code with echo + heredoc operator [php]

&amp;lt;?php if (the_ID() == 8) {
  echo &amp;lt;&amp;lt;&amp;lt;EOL  // &amp;lt;- We use the heredoc operator. Notice 3 times '&amp;lt;'
    &amp;lt;div id=&amp;quot;menu_show&amp;quot; class=&amp;quot;...&amp;quot;&amp;gt;
      ...
    &amp;lt;/div&amp;gt;
EOL;  // End the heredoc block. Has to be the first characters on the line,
      // so don't indent it.
} else {
  echo &amp;quot;&amp;lt;div class=\&amp;quot;header\&amp;quot;&amp;gt;&amp;lt;/div&amp;gt;&amp;quot;;
}
?&amp;gt;
&lt;/pre&gt;</content>
    <author>
      <name>Casper</name>
      <email>casper.cg@gmail.com</email>
    </author>
    <link type="text/html" href="http://refactormycode.com/codes/175-output-div-block-with-php-conditional-statement/refactors/1033" rel="alternate"/>
  </entry>
  <entry>
    <id>tag:refactormycode.com,2007:Refactor1030</id>
    <published>2007-12-07T16:54:02+00:00</published>
    <title>[JavaScript] On Javascript threading</title>
    <content type="html">&lt;p&gt;Like BK said you have global variables all over the place and this breaks the code. You have to think about what happens when your methods are called concurrently. For example &amp;quot;console&amp;quot; will be overwritten by the latest call, since it's a global variable.&lt;/p&gt;

&lt;p&gt;But, the number 1 rule of coding is don't reinvent the wheel. XMLHTTPRequests have been done a million times before, and there are very good libraries that wrap this stuff into much easier packages. For example the solution by using the excellent jQuery library:&lt;/p&gt;

&lt;p&gt;&lt;/p&gt;

&lt;pre&gt;## Html snippet [html]

&amp;lt;!-- Import jQuery --&amp;gt;
&amp;lt;script src=&amp;quot;http://jquery.com/src/jquery-latest.js&amp;quot; type=&amp;quot;text/javascript&amp;quot;&amp;gt;&amp;lt;/script&amp;gt;  

&amp;lt;div id=&amp;quot;ping_div_live&amp;quot;&amp;gt;&amp;lt;/div&amp;gt;
&amp;lt;div id=&amp;quot;ping_div_standby&amp;quot;&amp;gt;&amp;lt;/div&amp;gt;

## Javascript part [javascript]

// Untested code, but hopefully you get the idea
function startup() {
  ping('live',    10000);
  ping('standby', 10000);
  // ...
}

function ping(hostname, interval) {
  setInterval(function() { do_ajax_ping(hostname); }, interval);
}

function do_ajax_ping(hostname) {
  // Using the jQuery AJAX method here, makes this easy
  $.ajax({
      type: &amp;quot;GET&amp;quot;,
      url: &amp;quot;../php/ping_sys2.php?target=&amp;quot; + hostname,
      processData: false,

      // Using a closure to be called on success here
      success: function(data) {  
        // jQuery DOM manipulation. Again..easier like this.
        $(&amp;quot;#ping_div_&amp;quot; + hostname).append(&amp;quot;&amp;lt;div&amp;gt;&amp;quot; + data + &amp;quot;&amp;lt;/div&amp;gt;&amp;quot;);
      }
   });
}

&lt;/pre&gt;</content>
    <author>
      <name>Casper</name>
      <email>casper.cg@gmail.com</email>
    </author>
    <link type="text/html" href="http://refactormycode.com/codes/172-javascript-threading/refactors/1030" rel="alternate"/>
  </entry>
  <entry>
    <id>tag:refactormycode.com,2007:Refactor1019</id>
    <published>2007-12-06T23:15:54+00:00</published>
    <title>[C] On Socket read line in C</title>
    <content type="html">&lt;p&gt;Several comments.&lt;/p&gt;

&lt;p&gt;1: What do you do with the string that is returned from the socket? In many cases when you use sockets you process some data or commands that you receive, and then discard the string you read. If you do something similar here it's innefficient and unnecessary to every time realloc a new string in memory for every call to your function.&lt;/p&gt;

&lt;p&gt;Look at how standard C-library read functions are coded (read() or fgets() for example). In most cases it's the callee's responsibility to preallocate the string. Since in most cases the callee (i.e. you) will know what the maximum line length or string length that is about to be read is.&lt;/p&gt;

&lt;p&gt;It's much more efficient, and less memory fragmenting, to code it that way, and less error prone. You preallocate one buffer. Say char my_buffer[MAX_LINE_LENGTH]. This you then give to your method:&lt;/p&gt;

&lt;p&gt;while (i_want_to_read_some_stuff) {
&lt;br /&gt;  socket_read_line(sock, my_buffer, MAX_LINE_LENGHT);
&lt;br /&gt;  /* process the data you received... */
&lt;br /&gt;}&lt;/p&gt;

&lt;p&gt;2: If you're reading lines anyway you can convert the socket description into a standard C FILE stream and use fgets() instead: FILE *socket_stream_in = fdopen(sock, &amp;quot;r&amp;quot;); fgets(my_buffer, MAX_LINE_LENGTH, socket_stream_in); Why reinvent the wheel? :)&lt;/p&gt;

&lt;p&gt;3: The line cr = (ch == '\r' ? 1 : 0); can be refactored as simply cr = (ch == '\r'); I would use a more descriptive variable name though. I like those to make the code more readable. So rename it to something like int got_cr = 0; got_cr = (ch == '\r'); But I'm kind of nitpicky on these..but it still makes if statements read more fluently: if (got_cr) { ...do stuff... }..&lt;/p&gt;

&lt;p&gt;&lt;/p&gt;

&lt;pre&gt;&lt;/pre&gt;</content>
    <author>
      <name>Casper</name>
      <email>casper.cg@gmail.com</email>
    </author>
    <link type="text/html" href="http://refactormycode.com/codes/174-socket-read-line-in-c/refactors/1019" rel="alternate"/>
  </entry>
</feed>
