Random thoughts on code errors after teaching two different languages in one semester

When I was a bit younger we used to play a game called Pitfall where you would guide your player across various obstacles, including chomping alligators, deadly quicksand, and rushing rivers. In programming there are also pitfalls, and they may not be as bad as an alligator pit, but they will consume your time and leave you drained at the end of the day.

Software errors will always happen, it comes down to how quickly you can identify them and correct them that make all the difference. Those that argue that code should be written error free the first time have obviously not written much code. We can all agree that production code should be error free, but to achieve error free code means you will have to identify and eliminate errors.

I wanted to share a few thoughts on how to cut down on errors in your code.

Use proper indentation, and formatting. This is almost never taught in class, and most of the books that I have seen even contain code that runs and is compact but is not really easy to read.  It’s important to write all your code as if you are going to spend the rest of your career maintaining it.

This sounds great but how can I implement it? Let’s take a look at some code.

I like to use a tab for each block of code. Look at the difference between block a and block b.

A

Ext.override(Ext.form.Radio, {
        setValue : function(v) {
            if (typeof v == 'boolean') {
                Ext.form.Radio.superclass.setValue.call(this, v);
            } else if (this.rendered) {
                var els = this.getCheckEl().select('input[name=' + this.el.dom.name + ']');
                els.each(function(el){
                    if (el.dom.value == v) {
                        Ext.getCmp(el.dom.id).setValue(true);
                    } else {
                        Ext.getCmp(el.dom.id).setValue(false);
                    }
                }, this);
            }
            return this;
        }
    });

B

Ext.override(Ext.form.Radio, { setValue : function(v) {
if (typeof v == 'boolean') {
Ext.form.Radio.superclass.setValue.call(this, v);
} else if (this.rendered) {
var els = this.getCheckEl().select('input[name=' + this.el.dom.name + ']');
els.each(function(el){
if (el.dom.value == v) {Ext.getCmp(el.dom.id).setValue(true);
 } else {Ext.getCmp(el.dom.id).setValue(false);
}}, this);}
return this;
} });

Hard to believe that’s the same code right? Now imagine this throughout a file containing a thousand, ten thousand, hundreds of thousands of lines of code.

Use curly braces even when you don’t have to. Wait won’t that bloat my code? I’ve been taught that I should keep things as compact as possible what’s up with this. Let me explain in code:

A

if (condition1)
{
    if (condition2)
    {
        statement1;
    } else {
        statement2;
    }
}

B

if (condition1)
if (condition2)
statement1;
else statement2;

To the compiler, both pieces of code above will achieve the same result; however, the top block is far easier to read for us humans. Which code would you like to maintain.

Don’t use variable names that have no meaning – remember comments in the code should not be used to explain what your variables are, let their names tell all. This rule needs no code explanation, just stay away from one letter variables like a, b, or c and try to spell them out like

A

        double    a;
        double    b;
a = (b - 32) * 0.555555556

 

B

 

        double    celsius;
        double    fahrenheit;
celsius = (fahrenheit - 32) * 0.555555556

Bet you didn’t know that example A did until you got a look at B, right.

Test often and test early. How many lines do you write before you stop and see if what you have compiles. Do you write test cases for all your functions when you code them and actually test them before connecting them to the user interface? This helps you tackle bugs close to the source without wading through hundreds of lines of code.

If your IDE does not have a nice auto save feature like Jet Brain’s WebStorm, then please remember to save early and save often. There is nothing more frustrating than losing hours of good code.

Nobody ever wanted an app that ran slower, keep that in mind and optimize, optimize, optimize. You can use tools like Page Speed, or Chrome’s Developer Tools to get your JavaScript on track. In addition Google and Yahoo have written detailed articles that are essentially a lessons learned document

Tough coding decisions we all have to make at one time or another

One thing is for certain it’s not a perfect world, and there are imperfect solutions out there that make for a perfect user experience if you know what I mean.

Recently, I’ve had to tackle some rather esoteric IE bugs that happen only on that platform. The error in question this time comes from the extjs package and not the browser so what you get in a production environment running ext-all.js in both 4.x and 3.4 is an error in the ext-all.js javascript file.

Of course, the first thing you want to do is switch to ext-all-debug.js and check what line throws the error. You find out that it happens right around line 2921 in the setStyle function. The code is below with one addition, a try … catch block that will alert the property that the error occurred on.

setStyle : function(prop, value){
            var tmp, style;
           // alert(value);
            if (typeof prop != 'object') {
                tmp = {};
                tmp[prop] = value;
                prop = tmp;
            }
            for (style in prop) {
                value = prop[style];
	try{
					 
	style == 'opacity' ?  this.setOpacity(value) : this.dom.style[chkCache(style)] = value;
	} catch(err){
	/*// alert(value);
	   for (x in prop){
		alert('error Thrown' + x + '  -- ' ); 
		}
	   alert(err.name + ' - ' + err.number + ' - ' + err.description );*/
		return true;
	  }
            }		
            return this;
        }

Given that the error occurred in the setStyle function my first inclination was to go back through every style, and bodyStyle config option in the app and make sure that the css was correct. Next I went ahead and looked at any padding config options and corrected anything that seemed amiss. I knew approximately where the error was occurring due to the loop below but that proved little help. Once again using firebug was out of the question as this only happened on IE8/9.

Now you’ve reached the point where you decide to do the unthinkable, change the ext-all file itself to add a throw – catch around the style equals statement. Why?

  • In my case this was the last app to run 3.4 so modifying this would not impact any of the other apps that were running.
  • I had researched the extjs forums and all indications were that this was a bug in this version and since updates for 3.4 are probably not going to happen I had to act fast to resolve this issue.
  • Now onto a new challenge finding the needle in the haystack that is the minified extjs javascript file!
    I have a screen shot that shows the code after it has been changed below for your reference. To find the point where you have to change the code fire up your IDE and search for the following line:

    	G=="opacity"?this.setOpacity(H):this.dom.style[v(G)]=H
     

    Replace it with this:

    try{G=="opacity"?this.setOpacity(H):this.dom.style[v(G)]=H}catch(err){return true}}return this} 
    

    Here’s the code around it for reference:

    Some cold fusion cfqueryparam / extjs form field tips for xtype numberfield

    If you code in cold fusion you should be using cfqueryparam when you are inputting data into your back end database, that’s a given as it is pretty effective against sql injection hacks, but when you do this you run the risk of throwing errors that you never worried about previously. The two most common problems are maxlength violations, and null value errors in numeric fields, to handle these two issues in your Extjs project I suggest the following approach:

    Client Side Considerations:

    Always use the xtype:numberfield, or the Ext.form.field.Number input control.

    Make sure that you set a valid minValue, or it will default to negative infinity, and you may also need to set a maxValue if you do not want the user to enter a number greater than the ceiling on the data type.

    Remember that decimals are allowed by default, so if you want to store the input in an integer field make sure you set allowDecimals to false.
    Decide if this is a required field, if so set allowBlank to false to make sure that the user enters a number before submitting the field.

    Server Side Considerations:

    When you always want a value in the database field (for example a price or quantity field) — Always use cold fusion’s val() function around your input variables as it will convert the numeric characters at the beginning of a string to a number, but, will replace the value with a zero if there are leading characters, meaning the end result is you will always get a valid number in your number field. See the code below.

    UPDATE  some_table
    SET 
    some_currency_value  = <cfqueryparam cfsqltype="cf_sql_float"		value="#val(some_user_input_data)#"	/>
    

    In the example above if some_user_input_data was set to XYZ6563 then the code above would set the value zero. If the numbers were in front of the letters then the letters would be removed and the value entered into database would be 6563 and XYZ would be left off.

    When you may actually want a null in the database field – If you do not want to use the val() function but still want to prevent invalid data input from causing cold fusion errors on the back end of your application you can use the IsValid() function coupled with the null attribute in cfqueryparam and ensure that your invalid values insert a null into the field.

    Here’s how and why.

    UPDATE  some_table
    SET 
    some_int_value  = <cfqueryparam cfsqltype="cf_sql_integer" 	
    value="# some_user_input_data #"
     null="#not IsValid('integer', some_user_input_data)#"  />
    

    The null attribute is looking for a yes or a no, a 1 or a 0 to tell it to ignore the value in the value field and just put the NULL into the database using not in front will reverse the 1 or zero that the Isvalid function returns thus telling cold fusion to place a NULL in the database when the value passed was not a valid integer. You can take a look at more features of the IsValid function here.

    There you have it, some tips on keeping your number field values in place and ensuring that the integrity of your back end data stays sound.

    A look at Javascript and how benchmarks deter good programming practices

    This is a great video that shows the consequences of benchmarking something without knowing exactly what to benchmark, and I agree completely with the Java assessment. More to come later ..

    Everything you need to know about web standards and design in 3 minutes!

    I am working on updating some slides for an upcoming HTML course and stumbled across this brilliant video that explains everything you need to know in about three minutes, including why you need to use a standards based approach to design.

    Here’s the lyrics

    Your site design is the first thing people see
    it should be reflective of you and the industry
    easy to look at with a nice navigation
    when you can’t find what you want it causes frustration
    a clear Call to action to increase the temptation
    use appealing graphics they create motivation
    if you have animation
    use with moderation
    cause search engines can’t index the information
    display the logos of all your associations
    highlight your contact info that’s an obligation
    create a clean design you can use some decoration
    but to try to prevent any client hesitation
    every page that they click should provide and explanation
    should be easy to understand like having a conversation
    when you design the style go ahead and use your imagination
    but make sure you use correct color combinations
    do some investigation, look at other organizations
    but don’t duplicate or you might face a litigation
    design done, congratulations but it’s time to start construction
    follow these instructions when you move into production
    your photoshop functions then slice that design
    do your layout with divs make sure that it’s aligned
    please don’t use tables even though they work fine
    when it come to indexing they give searches a hard time
    make it easy for the spiders to crawl what you provide
    remove font type, font color and font size
    no background colors, keep your coding real neat,
    tag your look and feel on a separate style sheet
    better results with xml and css
    now you making progress, a lil closer to success
    describe your doctype so the browser can relate
    make sure you do it great or it won’t validate
    check in all browsers, I do it directly
    gotta make sure that it renders correctly
    some use IE, some others use Flock
    some use AOL, I use Firefox
    title everything including links and images
    don’t use italics, use emphasis
    don’t use bold, please use strong
    if you use bold that’s old and wrong
    when you use CSS, you page will load quicker
    client satisfied like they eating on a snicker
    they stuck on your page like you made it with a sticker
    and then they convert now that’s the real kicker
    make you a lil richer, your site a lil slicker
    design and code right man I hope you get the picture
    what I’m telling you is true man it should be a scripture
    if it’s built right you’ll be the pick of the litter
    everyone will want to follow you like twitter
    competition will get bitter and you’ll shine like glitter
    if you trying to grow your company will get bigger
    design and code right man can you get with it