Pages

Thursday, December 22, 2011

ColdFusion Quickie: Setting A Boolean Value As A Result Of EvaluatingBooleans

There are many times when we come across a situation where we need to set a boolean value based on the value of other booleans.



Thats a lot of code for a simple statement. A better way is to use a ternary operator.



Better but still a bit more code than is actually necessary. In these cases where we are checking more than one variable for truthiness to set another variable to true we can just evaluate the result of concatenating the booleans together.



When concatenating booleans together the result is only true if all the values are true. One thing to be aware of is if you try to use the addition operator (+) instead and the value is true, you'll actually end up with an integer result instead of a true boolean. This may be good enough in some cases since any number other than 0 in ColdFusion is true anyway.

Wednesday, November 30, 2011

Setting Tab Preferences for ColdFusion Files in SublimeText 2 on OSX

Ever since I started using Indy's ColdFusion SublimeText 2 Bundle on OSX I've had issues with Sublime ignoring my "User File Settings" for tab behavior.  I like to keep my tabs as tabs and not have them be spaces, and no matter what I added to my user file settings tabs were being interpreted as two spaces.

The only way I was able to override this behavior is to open a .cfm file and gointo Preferneces -> File Settings  - More -> Syntax Specific - User and add the following JSON string:

 {"tab_size": 4, "translate_tabs_to_spaces": false}

Lastly save the file by going to File -> Save As and make sure its saved as:

/Users/username/Library/Sublime Text 2/Packages/User/ColdFusion.sublime-settings

According to the SublimeText Documentation (http://www.sublimetext.com/docs/2/indentation.html) the order preferences are applied is:
  1. Packages/Default/Base File.sublime-settings
  2. Packages/Default/Base File (<platform>).sublime-settings
  3. Packages/User/Base File.sublime-settings
  4. Packages/<syntax>/<syntax>.sublime-settings
  5. Packages/User/<syntax>.sublime-settings
Since the Packages/User/.sublime-settings file is processed last hence will override any other settings.  The strange thing was that I could not find any tab preferences stored in any of the other 4 files that were processed before the language specific ones.   

Monday, November 28, 2011

Catch Me On the Latest CFHour Podcast.

I was extremely honored and humbled to be asked to appear on the CFHour podcast to talk about the ColdFusion Koans project.  You can listen to it here: http://www.cfhour.com/post.cfm/show-123-coldfusion-koans-with-ryan-anklam.

Thursday, November 10, 2011

Watch Me on BoltTalks Talking About the ColdFusion Koans

Yesterday I had the privilege of being on Tim Cunningham's BoltTalks to talk about the ColdFusion Koans project. BoltTalks are a quick ~15 minute video interviews that are perfect for those of use who suffer from ADD.   Head on over to http://cfmumbojumbo.com/cf/index.cfm/bolttalks/coldfusion-koans-with-ryan-anklam/ and check it out and let me know how I did.

Thursday, November 3, 2011

Screencast: Getting Started With The ColdFusion Koans

I put together this little screencast that will walk you through getting started with the Koans project.  If you haven't read my introductory post yet, read about it here. As you'll see its extremely easy, and its pretty fun too, especially if this is your first journey into unit testing.

Unable to display content. Adobe Flash is required.

As always, if after watching this and working on the Koans you have some good ideas for some additional tests to add to the project please send me a pull request on GitHub.  If you are really limited on time and just want to share your idea you can always go to the README.md page, click on the "Edit" link, and add your ideas to the "Suggested Topics" section.

Tuesday, October 25, 2011

Introducing the ColdFusion Koans - Learn ColdFusion Through Unit Tests

What are the ColdFusion Koans?

The ColdFusion Koans project is intended to teach ColdFusion syntax, techniques, structure, and tips and tricks through unit tests.  Even if you are a seasoned ColdFusion developer the Koans can be a fun exercise to keep your skills sharpened.  The Koans concept is nothing new, in fact, the Ruby Koans project is quite mature.  Recently other languages, such as JavaScript, have also implement the technique.

What is great about the Koans concept is that not only do they teach the language but they also help promote a culture of unit testing.  By teaching the language through a series of unit tests developers will hopefully develop good habits early into their ColdFusion programming careers.  In a recent blog entry, I called out the community to help promote better practices in the ColdFusion community.  This project is my attempt at doing something to help.   

How Do They Work?

**If you don't want to read all this you can watch a short screencast (4 min) here.**

Getting started is simple. First and foremost you must have a development environment running ColdFusion 9 or newer (if anyone has a Railo or OpenBD server running and would like to test the Koans on them I'd love to hear if the project works on those servers as well).  Once you have your development environment setup the next step is to download the Koans from GitHub at https://github.com/bittersweetryan/ColdFusion-Koans and copy the unzipped ColdFusion-Koans folder into your webroot.  **Note, even if you have already mxunit installed its important to use the one that is packaged with the Koans project as it will run the test suites in the proper order.  This custom mxunit does require the ability to create Java objects!**  Once the Koans are in your webroot the next step is to open your browser and goto http://localhost/ColdFusion-Koans (this is assuming you are running a local development environment).  If you are using a remote ColdFusion development environment then you'll want to go to http://yoururl/ColdFusion-Koans.  

When you first load the Koans page all of the unit tests will fail.  Your job is to go into the Koans/About___.cfc files and make those tests pass.  This is typically done by filling in a value in a unit test assertion.  For example, in the following test is in the AboutAsserts.cfc file:



In this case you'd replace the "__" with "Foo" in the assertEquals() function.

In some cases you'll have to modify some code in the function itself to make the test pass.  If you see an assertEquals() statement without a blank value ("__") that typically means that you'll have to modify some code in order to make the test pass.  I've tried to add comments in the code to help you along the way.

Please Contribute!

I strongly urge anyone who has an idea for a test to please fork the Koans project, add your tests, and send me a pull request.  I'd like to see some more intermediate to advanced concepts introduced so if you have an idea please don't hesitate to add it!  The Ruby Koans project has been so successful because it has had a lot of community involvement.  I've even seen a number of Ruby user groups devote talks on working through the Koans.  

Thursday, October 20, 2011

New Project, GitHub News Filter Chrome Extension


I've added my Open Source project, GitHub News Filter, to the Chrome web store. It can be found at: https://chrome.google.com/webstore/detail/gnaclennljjalbkgjefenghpnehakdel

This extension adds a small toolbar to the bottom of a you GitHub dashboard that will allow them to filter news items by category.  This extension is especially useful if you follow active projects that have many comments and issues opened.  I decided to create it for myself since I follow a lot of pojects on GitHub and I wanted a way to only see news items that pertained to code.

The source code can be found at: https://github.com/bittersweetryan/GitHub-News-Filter Feel free to fork it, download it, and send me pull requests.

Screenshots:



*Updated* Screencast: Power ColdFusion Editing With Sublime Text 2

Previously I screencasted about using  E TextEditor for ColdFusion coding and at the time I was trying to determine a winner between that and Sublime Text 2.  The more time I spent in Sublime and the more I learned how to use its features it became the clear winner.  Coding in Sublime is fun.

If you don't have SublimeText 2 yet I suggest you download and install the latest dev build from: http://www.sublimetext.com/dev.  The dev build will give you updates every few days.  After Sublime is installed you'll need to download the and install the ColdFusion Bundle and Snippets.  I use Andy Jarrett's CFTextMate bundles at: http://cftextmate.andyjarrett.co.uk/, but there are other options.  Indy Nagpal's ColdFusion SubLime Text 2 project looks to be another good one: https://github.com/indynagpal/coldfusion-sublime-text-2.  The install process is quite easy, just copy the bundles into a folder in your "Packages" directory.  On a windows machine this directory is located at %AppData%/Sublime Text2/Packages.

Let me show you a few reasons why I love this editor so much.
**Note: Justin Carter brought to my attention that I was using auto-complete all wrong in this video. It works great if you type a few characters then do ctrl+space. For instance in a cfscript block type in arr+ sublime will give you a list of matching functions. Once you hit enter it will fill out the rest of the function for you with its arguments.**

Unable to display content. Adobe Flash is required.

Now lets take a quick look at creating your own snippets.

Unable to display content. Adobe Flash is required.

Other Resources

Charlie Griefer has a good post about Sublime over on his blog at:  http://charlie.griefer.com/blog/2011/10/19/sublime-text-2/

Nettuts has a great tutorial on "Sublime Tips and Tricks" at http://net.tutsplus.com/tutorials/tools-and-tips/sublime-text-2-tips-and-tricks/

Lastly the narvenblog has a good list of favorite Sublime Text 2 shortcuts: http://www.narvenblog.com/2011/09/20/sublime-text-2-shortcuts/

Thursday, October 13, 2011

Using the JavaScript "this" Keyword In 3 Common Patterns

I'm not breaking any ground here, everything in this post has been discussed before. However, I like to write about things I want to understand better hence the main reason for this post. In this post I'll take a deeper look at using the "this" keyword in three common patterns: Object Literals, Modules aka IIFE's (sometimes called self executing anonymous functions), and Constructor functions. This acts a little differently in all three of these scenarios and I've spent some time on jsfiddle playing with each.

Object Literals

First lets take a look the most straight forward pattern (I know it's not really a pattern but its still a way some developers use to organize their code): the object literal.  In the object literal "this" points to the object's properties, in fact, you have to use "this" to refer to any of the objects.  One important thing to note here is that nested functions DO NOT have access to the objects "this" scope.  Look at the sayHello function in the code below, notice that there is an inner "helper" function.  Trying to access "this" within it would refer to the window object and not the person object.  In order to provide access to "this" a common workaround is to create another variable that points to "this".  Here I'll call it "self".

//this and objects
var person = {
    firstName: "Ryan",

    lastName: "Anklam",

    getFullName: function() {
        //inside an object we need to point to this to access its properties
        var firstName = "Yoko"; //this var is local to the function so, but 'this' still outputs Ryan
        return this.firstName + ' ' + this.lastName;
    },
    
    sayHello : function(){
        var self= this;  
        var inner = function(){
            //this inner function doesn't have privlaged access to the object's vars.  "this" in here actually refers to the "window" object
            return self.getFullName() + " says hello";
        };
       
       return inner(); 
    }
};

http://jsfiddle.net/bittersweetryan/wewY4/

IIFE's / Modules
In the module pattern things get interesting since the context of "this" is really the "window" context,  however, one of the common ways to provide public members to an IIFE is to return an object with public functions.  As we discussed before there is a "this" scope within the object literal. Since everything is nicely encapsulated in the IIFE the object can directly access it's parent function's variables.

var person = (function(){
    var firstName = "Gregg";
    var lastName = "Jennings";
    
    return{
        getFirstName : function(){
            return firstName + ' ' + lastName;
        },
        
        sayHello : function(){
            return this.getFirstName() + " says hello";
        }
    };
})();

One interesting twist that I first saw on Ben Nadal's blog post "Decoding Morse Code With JavaScript" was to use the call() method when invoking the IIFE and passing in a new object for the context of this. What I really like about this approach is that we don't have to return a new object literal, we can just return "this" to provide public access to methods that are assigned to the "this" scope.

var person = (function(){
    //these are private still
    var firstName = "Aaron";
    var lastName = "Rodgers";
    
    //this will be made public by returning this (see the end of the person function to see where this is coming from
    this.getFirstName = function(){
            return firstName + ' ' + lastName;
    };
        
    this.sayHello = function(){
            return this.getFirstName() + " says hello";
    };
              
    return this;
}).call({});  //sweet! we can set this in an IIFE by passing in a blank object literal using the call method

http://jsfiddle.net/bittersweetryan/qzkzy/

Constructor Functions

When dealing with Constructor functions you should be very careful. The "this" context will ONLY exist after a new instance of the constructor is created using the new keyword. Once the new keyword is used to create a new object only functions that are assigned to the "this" context will be made public. In the example below the sayHello function will only be available after the new keyword is used to create a new instance of the function.

//this and a prototype
function Person(){
    var firstName = "Chales";
    var lastName = "Woodson";
    
    //private within Person object
    function getFullName(){
        return firstName + ' ' + lastName;       
    };
    
    //public function that returns the firstName and lastName
    this.sayHello = function(){
        return getFullName() + " says hi";
    }
};

//this will throw an error since it tries to access a property in the this scope which isn't defined without using new
//console.log(Person.sayHello());

var newPerson = new Person();
console.log(newPerson.sayHello());

http://jsfiddle.net/bittersweetryan/45ceQ/

Friday, September 30, 2011

New StackExchange Site: CodeReview

I'm really excited about the newest site that StackExchange has released as a beta: CodeReview (http://codereview.stackexchange.com/). The premise of this new site is to post code you're working on and get feedback from other developers. The best part is that its a StackExchagne site so you know that the best answers will naturally rise to the top and bad answers will get down voted so you don't need to be overly concerned about getting poor advise.

Being a developer at a smaller company means that I don't get to have my code looked at as often as I would like to and this website could be an excellent resource developers just like myself. I know that sometimes its hard for developers to share your code and hear any feedback that isn't glowing but I really believe that most of what a good developers knows is knowledge that has been passed to them from another developer. So far this site doesn't look like its getting much traffic yet so I hope that if you read this and are excited about this new site you'll also help spread the word. I'd especially love to see a lot of you ColdFusion developers on there sharing code and commenting on others.

Screencast: Using E Texteditor To Write ColdFusion Code

Lately on twitter there has been a lot of talk about using text editors like SublimeText 2 and E Texteditor for windows to write your ColdFusion code.  I've been using them a lot in the last few months so I thought I'd put together a quick screencast to show you how to use them (in this case E) to quickly produce ColdFusion code and how to customize the ColdFusion bundles for the way you code.

This particular screencast was done in E, however much of it applies to Sublime Text 2 as well, its just that its not quite as user friendly.  Where E has a nice bundle editor built in Sublime will make you browse to the "Packages folder" (you can get there through the interface by going to "Preferences -> Browse Packages" and find the tag's .tmSnippet file and manually open it in Sublime Text.

You'll defiantly want to make sure that you view this in the "full screen" mode by clicking on the icon in the lower right corner of the player.

Unable to display content. Adobe Flash is required.

Monday, September 26, 2011

Serialize Your CFC's Getters Into JavaScript Objects With CF PB&J

This weekend I worked on a little project called CF PB&J that will serialize a CFC's getters and their output into a well-encapsulated JavaScript object.  It's meant to be lightweight and work seamless with your JavaScript  while not cluttering up your global by having to create a  bunch of global variables to store your dynamic data.  You can find the project up on github at https://github.com/bittersweetryan/CF-PB-J.

Lets take a look at a quick example of how it works.  First lets create an Account object (note that there would typically be setter methods for these functions as well but they are left out for brevity's sake):

<cfcomponent hint="Test very simple cfc for searalization to javascript">
	<cfscript>
		variables.accountNumber = 0;
		variables.accountName = "";
		variables.productArray = [];
		variables.insuredProducts = {};
		
		
		variables.PBJ = "";
	</cfscript>
	
	<cffunction name="init" returntype="Account" access="public" output="false" hint="" >
		<cfscript>
//create the PBJ object and pass in a reference to this
			variables.PBJ = createObject("PBJ").init(this);
			return this;
		</cfscript>
	</cffunction>
	
	<cffunction name="getAccountNumber" returntype="numeric" access="public" output="false" hint="" >
		<cfscript>
			return variables.accountNumber; 
		</cfscript>
	</cffunction>
	
	<cffunction name="getAccountName" returntype="String" access="public" output="false" hint="" >
		<cfscript>
			return variables.accountName; 
		</cfscript>
	</cffunction>
	
	<cffunction name="toJS" returntype="String" access="public" output="false" hint="Proxy to the PBJ toJS method" >
		<cfscript>
			return variables.PBJ.toJS();
		</cfscript>
	</cffunction>
	
	<cffunction name="getProductArray" returntype="Array" access="public" output="false" hint="" >
		<cfscript>
			return variables.productArray;
		</cfscript>
	</cffunction>


	<cffunction name="getInsuredProducts" returntype="Struct" access="public" output="false" hint="" >
		<cfscript>
			return variables.insuredProducts;
		</cfscript>
	</cffunction>
	
</cfcomponent>

If you look closely at the Init method you'll see that a PBJ object is created and initalized and the "this" reference is passed to it.  This tells PB&J to inspect the current object for its "getter" methods defined by the naming convention getXXX.  PB&J will look for all getter methods that return strings, numbers, arrays, and structures.  This object also defines a proxy function called "toJS"that calls the PBJ.toJS() method.  When this method is invoked it will run all of your object's getter methods, save the return data, and output JavaScript that is a mirror of your object with its getter methods and its data.  Lets take a look at an example of this in action.  First lets create an instance of the account object and set some of its data:

account = createObject("Account").init();
	
account.setAccountNumber(12345);
account.setAccountName("Ryan ""Pretty Boy"" Anklam");

Now in our .cfm page we output the value of  #account.toJS()#  in the header to produce our JavaScript representation of our object:

< script type = "text/javascript" charset = "utf-8" >
var Account = (function() {
    var accountName = "Ryan \"Pretty Boy\" Anklam";
    var productArray = [];
    var insuredProducts = {};
    var accountNumber = 12345;
    return {
        getAccountName: function() {
            return accountName;
        },
        getProductArray: function() {
            return productArray;
        },
        getInsuredProducts: function() {
            return insuredProducts;
        },
        getAccountNumber: function() {
            return accountNumber;
        }
    };
})(); 
< /script>

Looking at the JavaScript you'll see that CF PB&J created a few private variables and returned public methods to return that data.   It's meant to be a "read-only" representation of the internal state of your object.  PB&J will also work on calculated fields as it just invokes your getter methods and saves its output.

Now in any of your scripts you can access the object's data by calling the JavaScript object's getter methods:

< script type = "text/javascript" charset = "utf-8" >
     Account.getAccountName();
     Account.getAccountNumber();
< /script>

Friday, September 16, 2011

Do the ColdFusion Community Members Need to Become Jerks?

Forgive me about the over-dramatic title of this post, however there is some truth into it.  The reason Ruby and Rails has such a good reputation for producing good code is that the community won't accept anything less.  A Rails project is expected to have a comprehensive test suite and well crafted code.  If it doesn't and the developer tries to release a poorly engineered project to the community its a given that the developer will hear about it.  Nothing less is accepted.

As ColdFusion developers I think we tend to be a bit more forgiving of poorly crafted code as to not discourage anyone from using the language, or we just aren't as outspoken as other communities.  I think by these things we are doing the entire community a disservice.  We need to push for well-crafted, professional applications.  It starts in the open source world, however we need to be able to push this mentality into private development as well.

From what I've seen a large percentage of the open source ColdFusion projects are well written and well tested, however its in the private development where "professional" development practices are lacking.  This is where the root of the poor perception of ColdFusion exists.  Every time a developer from another language opens a poorly CF written app, that's one more developer that forms a poor opinion of ColdFusion.  Even though we all know that that ColdFusion isn't to blame for a poorly written application, we are to blame for accepting poor development practices.

I think if we speak loudly enough about poor practices via twitter, blogs, in conferences, and when reviewing others code we can start to shift the perception of ColdFusion code to a respectable level.  We don't necessarily need to become "jerks", however we do need to be more outspoken when we see poor coding practices being implemented in projects.  If we as ColdFusion developers clean up our code we can do more one thing to clean up the perception of ColdFusion.

Wednesday, September 14, 2011

I'll be presenting "JavaScript Fundamentals For ColdFusion Developers" Tomorrow

Level Up your JavaScript skills with me tomorrow at 11:00 AM CST on the ColdFusion online meetup: http://www.meetup.com/coldfusionmeetup/events/32356622/.  I'll be presenting on the fundamentals of JavaScript from a ColdFusion developers perspective.  A lot of the code samples in the presentation will have ColdFusion syntax side-by-side with JavaScript syntax so you can relate the concepts with a language you are already familiar with.  I'll be covering a lot of material in this session including:

  • Variables
  • Operators 
  • Functions
  • Objects
  • This 
If you are interested in JavaScript but never really took the time to learn it, of you've only done programming in your favorite JavaScript framework you should come check it out and see whats behind one of the fastest growing languages around today.   According to GitHub JavaScript is their most popular language with 20% of all their projects being JavaScript related.  

Wednesday, August 10, 2011

Learn JavaScript completely On the Cloud With the JavaScript Koans and Cloud9 IDE

Lately I've been investing a lot of time into learning JavaScript and one of the neatest things I've come across is the JavaScript Koans project.  If you haven't heard of Koans before the basic concept is to learn a programming language through the act completing unit tests in that language.   The most popular implementation of this concept is the Ruby Koans project (http://rubykoans.com/).  Liam McLennan took this concept and ported it over to JavaScript and his implementation can be found over on github (https://github.com/liammclennan/JavaScript-Koans).

When you pair this repository with the Cloud9 IDE you can work on them completely on the cloud without having to download a single piece of code locally.  Cloud9 (http://cloud9ide.com/) is an completely online and very richly featured IDE.  One of the great things about Cloud 9 is that it can access your github repositories and clone them into its environment for you to edit.  Cloud9 also provides you with a interactive console with git installed so you can push the changes back into your repository. The console will even give you intellisence on the git commands as shown to the right!

Assuming you already have a github account the first step is to fork a copy of the JavaScript Koans repository.  Once you have a forked copy of the Koans head over to the Cloud9 website and log into your dashboard.  Your dashboard will have a "Add On Services" section that will allow you to connect Cloud9 with your github account and pull in your public repositories.  One thing I've noticed is that if you've added a new repository since you last connected with github you'll have to connect to github again for Cloud9 to pull in the newly created repository.   Once the repository is pulled into Cloud9 next you'll have to select the project from the github menu and click on the "Clone to Edit" in order to be able to edit the files.

Once your github repository is cloned it will show up as a new project in the Projects area.  First click on the Koans project and click on the "Start Editing" button which will open up the project in a new tab.   Once your koans project is open double click on the "jskoans.htm" file to open it up in the editor.  The editor will detect that this is a HTML file and a "preview" icon will appear in the editor.  Click on this button to run the Koans.  When you do the jskoans.htm file will open in a new tab and run the koans unit tests, which will fail on the first test like so:



Whats important to note here is which file the error occurred on. The Koans are organized by topics, and each topic will have its own JavaScript file with qUnit tests that pertain to that topic.  Find that file that caused the error in the editor and open it.  You'll now see all the qUnit tests for that file.  Below you'll see the code from the first topic which is a brief overview of assertions.


Inside the assertion code there will always be two underscores "__" that denote an area where you are to fill in a value to make the test pass.  As you go through the exersizes save the unit test file and refresh the jskoans.htm preview page and you'll start to fill the page with passed tests.  The test runner will stop at the first failed test it finds. As more and more of the tests pass the page will begin to fill up with passed tests as shown in the image to the right.

Whats great about the koans is that its an open source project so community members can add more tests and actively improve the tests that are there, which are very good right now.  Some of the topics covered are: arrays, reflection, prototypical inheritance, objects, and functions and closures. Going through these you'll get to learn JavaScript the best way, by writing JavaScript.




Monday, August 8, 2011

The ColdFusion Geeks Fantasy Football League Needs Two More Teams!

This is the second year of the ColdFusion Geeks league (http://football.fantasysports.yahoo.com/f1/256516), and I've decided to expand it to 12 teams instead of 10.  I'm looking to fill those two spots with ColdFusion lovers who also love to play fantasy football. The winner is promised everlasting glory and lifelong bragging rights within the community.  

This is a free league all that I ask is you play till the end, even if you are 0 and 12 in week 13.  If you are interested you can send me a message on twitter or use the contact form of this blog.

Monday, August 1, 2011

How I Got Started In ColdFusion

The year was 1997.  Puff Daddy's "I'll Be Missing You" and Hanson's "Mmm Bop" ruled the airwaves and I was a skinny 19 year old stuck in an Architectural Technician program that I had zero passion for.  One day while sitting in the Milwaukee Area Technical College computer lab researching the Empire State Building I inadvertently right clicked on a web page trying to copy some text and noticed this option called "View Source" in the menu.  Being the inquisitive type that I am I decided to click on it to see what it did.  Notepad opened up and with it opened a whole new world to me.

At first I wasn't sure what all of these and
things meant but I was able to quickly develop a hypothesis in my head.  Within minutes I created a geocities account and was busy writing "Ryan's Awesome Car Picture Page" which featured a bunch of pictures of cars I found browsing the net.  Tables with a border size of 10 were a common site on this page.  My mind quickly jumped to the prospect of writing my Empire State Building paper as a website.  Architecture had become fun again, or at least writing a webpage about architecture was.  The page featured a repeating green marble background, white text, and some images of greek-style columns, was littered with markup errors, but was I ever proud of it.  I couldn't believe how much fun I had creating it either.  Grown up I was always interested in computers, but the only thing I had ever done with them was load games off a floppy disk and occasionally browse Prodigy.

I'll never forget the look on my professors face when I handed in my paper that had just one line on it: http://www.geocities.com/.... The very next day he pulled me into his office and told me that one of his former students was starting a company creating websites and that I should get in contact with her.  I'm a huge procrastinator, but this was one opportunity that I immediately jumped on.  The very next day I had an interview scheduled.  Apparently that interview went well because a week later I was busy scanning images out of an Oldsmobile car brochure for a car dealership website.

Fast forward a few months and a few static websites later.  The company I was working for, IDL Solutions, had been maintaining the Wisconsin Lottery website.  This was by far their most important client and they weren't about to let some greenhorn loose on it, however the owners were leaving town on vacation and I was called upon to enter the winning numbers for the lottery that night.  Tony, the companies co-owner and author of the lottery website sat me down and began to walk me through the process of updating numbers.  I immediately noticed that the pages he was showing me all ended in .cfm instead of the .html or .html links I was used to.  When I asked him about it he told me of this magical product by a company called Allaire called ColdFusion.  He continued to tell me how easy it made creating database driven websites and showed me some of the source code behind the lottery website.  I couldn't believe what I was seeing.  Up until this point all I had ever heard of was this language called CGI to create dynamic web pages.  CGI was way above my head at the time so ColdFusion seemed like one of the greatest things ever to me.  

It wasn't long before I had the "Ryan's World Tour" webpage up.  It was basically a very early implementation of a blog.  Every time I'd go out and party I'd write up a short story of the nights shenanigans and post it on the website and allowed my friends to comment on the stories.  I couldn't believe how much fun I was writing this website, I was hooked.   After the semester was over I stopped taking Architecture classes and switched all of my classes to computer classes.  For the next 4 years I worked with exclusively with ColdFusion doing pretty basic stuff: event sign up forms, parsing CSV files, and creating job websites...pretty much the same thing everybody was doing in the late 90's.

It wasn't until 2003 and the Macromedia MAX event in Utah that my eyes were opened to a whole new programming paradigm and I started taking my development seriously.  ColdFusion MX 6 had just come out and a lot of the ColdFusion sessions were on this new construct in the language called ColdFusion Components.  A particular session by Simon Horwith changed the way I looked at writing applications forever.  He showed us how, using CFC's, ColdFusion could be written using an object-oriented approach.  This was the first time I felt like I could become a "legitimate" programmer doing ColdFusion.  From that day on I haven't stopped trying to learn how to craft my applications better.

This is the point where I can say that I REALLY got started working with ColdFusion.  I stopped writing procedural spaghetti code and started to write reusable maintainable code.  I also started challenging myself to learn new things.  The more I learned the more I realized that I didn't know as much as I thought I knew.
To this day, that pattern continues.  Everyday I learn something new which makes me realized exactly how much I don't know.  This is a message that I try to pass on to ColdFusion developers that I talk to that seem to be in a rut.   It's so easy to be satisfied with what you know and keep the status quo.  It's easy to write code the same way you've always written code.  Its easy to follow the developers before you and do exactly what they did. In contrast it's hard to always feel like you have a mountain of things to learn.  It's hard to look at the code you wrote two months ago and want to rewrite every single line because you can't believe you were so stupid back then.

This is also what makes being a programmer so dam fun.  I'm never bored and I love the fact that there's always something new and exciting to learn.  ColdFusion started me down this path and for that I'll always remain a loyal ColdFusion programmer.  Of course I'll continue learn new languages along the way but when the rubber meets the road and I know I have to get a project done, ColdFusion is always the language I'll fall back to because I know it can do the job and do it well.

Monday, July 25, 2011

Technical Podcasts That'll Make You A Better Developer

I have a rather lengthy drive to work each day (~1 hour each way) while listening to the nonsensical ramblings of my local sports radio one day it hit me like a ton of bricks: why was I listening to this dribble when I could be spending this time making myself a better developer.  Thus began my search for some good technical podcasts to fill up my iPhone with.

I'm primarily a ColdFusion/Java developer and you'll see that none of these focus on either of those.  I'm a big believer that no matter what language you primarily use there are tons of things to learn from other languages.   I've used many things I've learned from listening to these in my day to day development.

While this list is far from complete its based on what I've discovered so far.  If you have a favorite podcast that you think I missed please comment and let me know.  I'm always looking for more good ones to listen to.

Software Engineering Radio (http://www.se-radio.net/)
I don't recommend listening to this one before you've had your coffee.  This podcast can be quite dry at times but it is packed with excellent technical information.  If you can get past the sometimes monotone delivery there is a lot to be learned from every episode.  The topics covered here cover an extremely wide range of topics, I'd highly suggest looking through all their back episodes for topics that may be interesting to you.

Herding Code (http://herdingcode.com/)
Herding code is a .NET focused podcast that contains mostly interviews with other developers.  The guests on Herding Code are usually top notch, and I frequently find myself going to the show notes on the website and researching a lot of the topics that come up.  The hosts are also extremely knowledgeable and usually ask their guests great thought provoking questions.  The topics discussed cover both open source and Microsoft specific topics which is a bonus in my book.

Pragmatic Podcast (http://pragprog.com/podcasts)
This podcast is another interview style podcast from the publishers of the Pragmatic Bookshelf books.  This podcast is a great change of pace from the strictly programming related podcasts I usually listen to.  Most of the time the interviews are for development specific topics, but I find the real gems are the ones that don't focus on development.  For instance, Andy Hunt's chat on Pragmatic Wetwear (http://pragprog.com/podcasts/show/13) or Chad Fowler's chat on "The Passionate Programmer (http://pragprog.com/podcasts/show/26) were some of the best overall podcasts I've listened to.

Polymorphic Podcast (http://polymorphicpodcast.com/)
The Polymorphic Podcast is another .NET focused podcast.  The host, Craig, does an excellent job of talking about things at an architectural level that will benefit developers from any language.  This podcast also does a good job at providing its listeners with enough high level programming best practices and techniques that its worth listening to even if you are not a .NET developer.

On Software (http://www.informit.com/podcasts/channel.aspx?c=dadf92ca-3bdc-484e-9cd8-cbfe0cfc0de6)
This is a short video podcast that covers a very wide variety of topics.   From JavaScript to Rails to Ubuntu this podcast covers it all.  The episodes are all on the shortish side ~10 minutes or so and since they are video podcasts I don't recommend listening to them on your commute, but they are great for watching while you are eating your lunch.

Pluralcast formarly Elegant Code (http://www.pluralsight-training.net/microsoft/pluralcast/default.aspx)
Admittedly I haven't listened to nearly as many episodes of this one as the others, however, the ones I've listened to have had excellent technical content.  Again, its another .NET podcast but David does an excellent job in breaking down the technical aspects of what he's talking about and seems very detail oriented which helps when explaining something in an audio format.

Railscasts (http://railscasts.com/)
This Ruby-On-Rails specific videocast may be unmatched in its technical content. Like the prior sentence implies, this is another video cast that is a great watch during your lunch hour.   Even if you never have any intention to write a line of Ruby you'll be hard pressed not to take some of the ideas Ryan presents and try to implement them in your day to day development.  Ryan also does an excellent job preparing for his shows and the delivery of the content is second to none on this list.

The Changelog Show (http://thechangelog.com/)
This is the latest podcast I've started to listen to.  Wynn Netherland and Adam Stacoviak host this weekly show that focuses on Open Source projects and culture.  Each week features an Open Source developer talking about their project and the open source landscape.  This podcast does have a pretty Ruby-ish feel to it as both of the hosts are Ruby developers and most of the interviewees (at least through the episodes I've listened to but I still have about 12 to go before I'm current) have a Ruby background.  Regardless I find this show informative and entertaining and I almost always find myself watching at least one project or developer on GitHub after the show.

News Based Podcasts
While learning new things is always one of the more important things a developer can do its also important to stay up on the current news and trends.  While the following podcasts don't give you the amount of technical information as the ones I mentioned above these focus on keeping you up to date on their platforms of focus.  While I downloaded every episode of the others the ones below I usually only download the latest shows so I can hear whats new and exciting.

The Java Possee (http://javaposse.com/) does a great job at keeping me up to date on what the Java community is doing (this podcast does also have a fair share of great technical information but It's just not on the level of the others). The JavaScript show (http://javascriptshow.com/) is a newer show which is brought to you by the same hosts as The Ruby Show (http://rubyshow.com/) and is formatted the exact same way where the hosts just go over a list of technology specific news and projects.  Both of these do a superb job in giving you the latest and greatest news as well as point out projects that are doing exciting things.  These shows are nice because they give you their content in a direct and concise format and leave it up to you to get further details.

For jQuery you can't go wrong with The Official jQuery Podcast (http://podcast.jquery.com/).  I also wish I could speak intelligently on the yayQuery Podcast (http://yayquery.com/) becuase it seems like it will be full of excellent information as well. I do have episodes 0 - 22 queued up in my play list bug I just haven't gotten around to listening to them yet.  Once I do I'll update this entry with more information.

While this list doesn't cover all of the podcasts I listen to regularly, it does cover the ones I tend to glean the most information from.  Like I mentioned earlier, if there are others you know of that you think deserve mention in this post please leave me a comment and I'll give them a listen, and I'll try to keep this post up to date as I discover more good podcasts.

Monday, July 18, 2011

Mocking Java Objects In ColdFusion Unit Tests

I've been working on a project lately that has a few CFC's that rely heavily on a java object for much of their functionality.  This was making my unit tests act more like functional tests since I was using the return values from the Java object to make my assertions.  This didn't feel very good to me so I went to StackOverflow for some help. Edward Smith (Edward if you are reading this and would like me to link to something other than your stack overflow profile send me a comment and I'll update it) knocked it out of the park with his answer.  I used what he said to implement the solution that this post is based off of.   He mentioned that his company had used the Java mocking framework Mockito to mock Java objects in their ColdFusion unit tests.  Brilliant!  I already use Mockito for all of my Java unit tests, I just had never put it together that I could actually use it in my ColdFusion unit tests as well.

The first step in implementing this approach is to download the mockito jar file from http://www.mockito.org.  For my implementation I'm using Mark Mandel's excellent JavaLoader project to create instances of java objects so I copy the jar into a lib folder in my application's root folder.  Another approach would be to add the .jar file right to my ColdFusion server's instance, however I don't have any experience with this approach so I stuck with what I knew.  This article on the Adobe blogs by Christian Cantrell might help you out if you'd rather use this approach.

Now that I have the .jar file in my project its time to make them available to my mxunit test. To do this I need to make them available to my test by loading them using JavaLoader and then to create an instance of the Mockto object so I can start mocking the Java objects.  Its important to note that when using the JavaLoader approach you must also inititalize the .jar file of the object you mocking and ALL of the dependencies.  Once the JavaLoader object is initialized with all of .jar files our objects need we need to create an instance of the mockito class for our test to use:


The next step is to create our mock Java objects.  Since the component I'm trying to test is more or less a ColdFusion implementation of the java object I decided to recreate the mock before every test so I knew I was working with a clean copy of the mock.  This means that I placed my mock code in my unit test's "setUp" method like so:


The syntax for creating a mock object in Mockito is pretty simple:  variables.mockito.mock(variables.classLoader.create("com.sudios714.cfevernote.CFEvernote").init("123","S1","232","sandbox.evernote.com","mock").getClass()); Here I am calling the "mock" method on my Mockito object.  The first parameter to the mock method is a Java class.  In order to get a class I'm  using the JavaLoader object's create method to create a new instance of a Java class and calling the getClass() method on that class to get the actual Java class to pass into Mockito.  The last step is to inject it into my component. Now we have a working mock object injected into my component lets take a look at a test that puts my mock to use:


There are a few important things to note here.  First is that the data that I'm creating for my mock is using a native Java object, in this case java.util.ArrayList.  Since this is a part of the core Java language I don't need to use the JavaLoader to create an object for this data type.   The next step is to do the actual mocking behavior.  The statement variables.mockito.when(mockCFEvernote.listNotebooks(12)).thenReturn(retArray); is telling Mockito WHEN the listNotebooks method is called with a parameter of 12 to RETURN retArray which is the java.util.ArrayList object we created above.

Mockito can also be used to verify behavior, however this comes with a large caveat.  Even if the verify statement is surrounded a try/catch statement (at least in my Win64/IIS7/CF9/Java 6 environment) if the verify statement fails, meaning that the method was not called with the expected parameter, the server will throw a 500 error.  If the behavior verifies OK the test will run as expected.  Knowing this if you'd still like to verify some behavior it can be accomplished by writing a verify statement like so: variables.mockito.verify(mockCFEvernote).listNotebooks(12); Here we are telling Mockito to verify that in the mockEvernote object the listNotebooks() method was called with a parameter of 12.

Monday, April 4, 2011

Writing better CFML Series - Part 1: Booleans

Boolean values are one of the most basic programming building blocks.  Basically boolean values they are switches that can hold only two values, true of false.   Just like a light switch can only be in two poisitions: "on" or "off".

In ColdFusion we are given a lot flexibility of what a boolean is.  ColdFusion will recognize the string values "yes or no", the boolean values of "true and false", and numeric values "0 and anything but 0" as booleans values.

To demonstrate I've written a simple function called outputBooleanValues as shown below:
<cfscript>
function outputBoolValues(boolean yesNoBoolean, boolean trueFalseBoolean, boolean numericBoolean){
 if(arguments.yesNoBoolean){
  writeoutput("Yes/No Boolean is <strong>true!</strong>" & "<br>");
 }
 else{
  writeoutput("Yes/No Boolean is <strong>false!</strong>" & "<br>");
 }
 
 if(arguments.trueFalseBoolean){
  writeoutput("True/False Boolean is <strong>true!</strong>" & "<br>");
 }
 else{
  writeoutput("True/False Boolean is <strong>false!</strong>" & "<br>");
 }
 
 if(arguments.numericBoolean){
  writeoutput("Numeric Boolean is <strong>false!</strong>" & "<br>");
 }
 else{
  writeoutput("Numeric Boolean is <strong>true!</strong>" & "<br>"); 
 }
 
}
</cfscript>

One thing I'd like to point out right away about this script is how booleans are handled.  One of the most common mistakes that new programmers follow is comparing a boolean variable to its boolean value.  Lets look at line 2 of the above script:

<cfscript>
 if(arguments.yesNoBoolean){...}
</cfscript>

A lot of new programmers would write that line as follows:

<cfscript>
 if(arguments.yesNoBoolean eq true){...}
</cfscript>

One of the nicest things about working with boolean values is that we don't have to compare them to their value when writing if/else statements.   Remember that when writing an if/else statement you are comparing an expression to its boolean value.  This means is that you can evaluate just the boolean variable.  Comparing it to its boolean value is redundant and not needed.

Now that we've gotten that out of the way, lets demonstrate how ColdFusion uses many different representations of true/false.   When I run the following code through the outputBoolValues function:

<cfscript>
 outputBoolValues("yes",true,584);
</cfscript>

I get the following output:








One thing that's important to note here is that the value "584" returns "true", in fact any number that  is not "0" returns true.  This can be really powerful when evaluating array's and in other numerical operations as I"ll show later.   Now lets switch the true values to false values and run the function again:

<cfscript>
 outputBoolValues("no",false,0);
</cfscript>

Now you can see that all my values are "false":






Now that we've got a good understanding of booleans we can start having fun with them and seeing how they can be used in our everyday coding.  One common way to use numerical booleans is to check if lists and array's have any elements or not.  Lets create an array with zero elements and check if has any elements:

<cfscript>
 myArray = [];
 
 if(arrayLen(myArray)){
  writeoutput("My array has elements :-)");
 }
 else{
  writeoutput("My array has NO elements :-(");
 }
</cfscript>
 

Running that script would produce "My array has NO elements :-(".  Now if we change the script to add an element to the array :

<cfscript>
 myArray = ["Red"];
 
 if(arrayLen(myArray)){
  writeoutput("My array has elements :-)");
 }
 else{
  writeoutput("My array has NO elements :-(");
 }
</cfscript>

We now get the output "My array has elements :-)".  The same type of logic can be applied to lists, queries, and mathematical operations.

What if we wanted to evaluate many boolean variables at once?  We can use AND statements to tie many boolean values together like so:

<cfscript>
 if(true AND true AND true AND true){
  writeoutput("Its all true");
 }
</cfscript>

If we change any of those values to "false" the statement "Its all true" would not print.  When evaluating more than one boolean variable using "AND" statements every item must evaluate to true for the entire expression to be true.  We can even combine the different ways of expressing booleans:

<cfscript>
 if(1 AND "yes" AND true){
  writeoutput("Its all true");
 }
</cfscript>

I hope this has helped you get a better understanding of booleans and how ColdFusion uses them.  Since this is my first post in what I hope will be many more I'd really appreciate your feedback.  Was this information too technical, not technical enough?  Was it presented in a logical way?  Was there anything I could have done different to more clearly present the concepts?

Thursday, March 17, 2011

Is your ego getting in the way of your career?

If you saw the title of this post and thought to yourself  "Of course its not, how could being the smartest guy in the office hold me back." your ego might be getting in the way of your career.   If you are a great teacher but not a great listener your ego may be getting in the way of your career.   If you don't wake up every day thinking that you could fill Texas Stadium with what you don't know your ego may be getting in the way of your career.  As programmers we are typically very smart people, we solve complicated and abstract problems and others tend to marvel at our skills.  We all know that look of amazement on somebody's face when we tell them that we are a programmer.  So who could blame us for being a little "self confident".  

The key to a successful career as a software developer is to not let that ego get in our way.  I feel that there are two types of programmer egomaniacs: the "Kobe Bryant" and the "Kwame Brown".  I'm sure that most of you who read this will know who Kobe Bryant.  However, Kwame Brown is a name that most of you probably won't know.  That's because he is one of the biggest busts in NBA history.  A former number 1 draft pick who never realized his full potential and now has a hard time staying on an NBA team.

Lets start by talking about the Kwame Brown.  I was a Kwame Brown so this part will be highly introspective.  Kwame Brown was a number one overall draft pick in the NBA right out of high school.  In high school he was a big fish in a little pond.  He was talented but not as talented as he thought he was.  Since he had a relative amount of success in high school never put in the work that took to succeed at the next level.  

ColdFusion seems to breed more of these types of developers than other languages.  That is likely because its so easy to achieve a relative amount of success with ColdFusion.  The Kwame Brown doesn't like frameworks because they think then can roll their own, the Kwame Brown writes mostly in components and feels like they know all there is to know about object oriented programming.  This person picks up a technical book, reads the first two chapters and thinks to themselves, "I already know this stuff" and puts the book down. 

Its hard to say exactly what snapped me out of my rut.  I think it started when I had to open up my code to a outside consultant.  Something finally clicked inside me where I asked myself, "Is this something I'd be proud to show somebody else?"  I was somewhat confident in my approach (of course I was, I was a Kwame Brown) however this consultant started asking me things like, why aren't you using coldspring?  Why didn't you just use ColdBox or Model Glue?  Finally I decided to open up to and learn about these things he was talking about.  And the more new things I learned the more I realized that I didn't know.  IoC, unit testing, MVC, refactoring, design patterns, I was in trouble! 

The developer I am today is a completely different person than that one from two years ago.  Today I wake up each day thinking about how much I don't know and how much fun it will be to learn something new.  I actively explore different programming languages, and I read, a lot.  I read books cover to cover now.  I approach early chapters as an opportunity to learn something new about something that I may or may not I feel that I already know.   I try to blog about what I learn, nothing tells you if you understand something or not like sharing it with others.   I love looking at others code now, I pull a lot of open source projects from github and try to understand the code behind these.  I went so far as to enroll back in school to pursue a Computer Science degree to make sure that I had all the fundamentals I needed to become the best programmer I could.  One of the unexpected side effects of this is that I have a renewed passion for my job.  Each and every day I look forward to coming into work and challenging myself.  I have bad days for sure, but the number of good days I have now far outnumber the bad ones. 

This brings us to the "Kobe Bryant" type of ego maniac.  This person is the "superstar" programmer, a natural talent.  This person reads a book on regular expressions and is churning out complex pattern matches the next day.  They are usually the smartest person in a room full of smart people,  and they want you to know it.  This type of person rarely laughs at others jokes but will heartily laugh at a bug they discover in someone else's code and not hesitate to tell that person about it but rarely offer to sit down with that person and help them learn how to fix it. They hate sharing their knowledge because they get easily frustrated explaining things to others who don't "get it".  This type of developer also hates listening to others suggestions.  When a Kobe Bryant has use a module written by another developer the first thing they do is rewrite the code. 

I've worked with many of them before and I've rarely seen them become anything more than executors.   This is because that the people higher up the food chain can see how others react to these types of developers. Their team members will rarely go out of their way to sing this person's praises knowing that it will only feed their ego.  Instead their peers will watch them closely for any mistake and make sure they point it out to them and everybody else on the team.  Typically the Kobe Bryant developer is so self assured that they either don't see how others react to them or are so confident that their superior knowledge will surely allow them to rise to the top regardless if others like them or not.  Also the people doing the promoting know that they'll have to work more closely with this person and will balk at the notion of having increased interaction with this type of egomaniac.

So what can you do if you have some "Kobe Bryant" in you?  First learn to listen to others and sincerely try to value others input.  Here your reputation can work to your advantage.  If you are known as being a know it all telling someone else "that's a really good idea, thanks for sharing" can go farther than if it was said by someone who is constantly throwing around compliments.  Also actively seek out others opinions.  Even if you have no intention of listening to what they have to say just ask someone, "would you mind looking this code over for me" will make others feel that you value their opinion.   Lastly know that its OK to laugh at a stupid joke, nobody will question your intelligence if you laugh at the latest "Two guys walk into a bar" joke.

 If you suffer from either of these conditions its not too hard to turn things around and become a "Tim Duncan".  Tim Duncan is liked by others, is always working hard on his game, and is a true leader on a championship team.  That's the kind of developer I want to be, however I know that I have to work hard each and every day to achieve it and not fall back into my Kwame Brown ways.

Saturday, March 12, 2011

Writing better CFML Series - An Introduction

Personally I feel that a lot of the negative comments pointed towards ColdFusion are due to the fact that its so easy to learn, and like any language, tough to master.  I think a lot of people pick it up, write a site that works, and consider themselves "programmers".  While this in itself  isn't a bad thing because the ColdFusion community needs as many developers as it can get.   I think that this leads to  a lot of poorly written CFML out there and that that it tends to give ColdFusion a bad reputation.  Instead of getting into a flame war with everybody out there bashing ColdFusion I decided to do what I could about it and write a series of blog posts that are aimed at helping entry to mid-level developers write better CFML.

One of the problems with a lot of the resources out there is that they are either too high level or to advanced.  I think there is a large void in best-practices or mid-level tutorials and articles.  Everybody wants to write about complex or advanced topics that will wow the community and have others lauding over their knowledge (who wouldn't).  

In addition to writing about the many things I have planned my goal is to put out at least two posts a month covering topics like:
  • Object composition: writing useful, well constructed objects and minimizing an objects API
  •  Writing maintainable code by looking at an object's functions and properties and a quick look into refactoring to make messy code more readable
  • A deeper dive into MVC and what "separation of concerns" really means also some guidelines to where objects should live in the MVC pattern.
  • Loosely coupling objects and why its a good thing  along with a brief overview of dependency injection.
  • What in the world are interfaces and why you should implement them and use them for a functions return type and parameter types?
  • Some best practices when writing ColdFusion
If anybody else has any suggestions for things they frequently see in poorly written CFML please let me know, I'd love for more ideas on things to write about.

Wednesday, March 9, 2011

Book Review - O'Reilly's "97 Things Every Software Architect Should Know"


“97 Things Ever Software Architect Should Know” by O’Reily media is a short book composed of 97 short essays by a variety of contributors.   Before reading this book my expectations were somewhat high for it as I was recently assigned the official title of “Technical Solution Architect” so I was hopeful that I could glean a lot of knowledge from some seasoned industry vets.   

One of the first things I noted about this book was that it seemed relatively short for 97 solid pieces of information, the book weighs in at 264 pages in ePub format.  Most good authors with something important to share typically have a hard time condensing a good thought into less than 10 pages. When I read a technical book I always highlight interesting or helpful information that I want to remember.   One of the most concerning things about this book was that I didn’t highlight a single item until chapter 10, or approximately 9.7% into the book.  This chapter talks about quantifying results which was one of the best concepts I took from the book.  The main principal here is to use quantifiable measures in your requirements instead of abstract terms. Instead of adding the words “quick response time” to a requirement use “average response time in under 20ms” instead.  

A lot of the chapters in this book talk about some very fundamental concepts such as simplifying your technical design, which a lesson that I think would do a lot of us good to stay true to.   Other things stressed in this book are:  always put the client first when architecting an application, focus on the maintainability of the system, don’t over plan for the future, plan for today, and to always try to loosely couple system dependencies.  

While in the end I didn’t feel that I learned a whole lot from this book I did find it a quick and somewhat enjoyable read.  It also does a good job of enforcing some fundamentals that we all tend to forget over time.  It was a good refresher to focus on simplicity and the client’s needs.  Too often when architecting an application it’s easy to get wrapped up in implementing the latest frameworks,  go a little overboard with design-pattern s, and over obfuscate simple tasks.   

I wouldn’t recommend putting this book on the top of your “to read” list if you are looking to improve your development or architecture skills.    I would put it somewhere after Fowler’s “Refactoring” and “Patterns of Enterprise Architecture” books and somewhere above “Access 2010  For Dummies”.  If you don't find it the most stimulating book you've ever read you may get a few lol's out of some of the pictures the authors chose to submit.  I know more than once I thought to myself  "That was the BEST picture that person could come up with?", you can decide for yourself who I'm talking about.  To find out more or to purchase this book check it out on O'Reilly's website here http://oreilly.com/catalog/9780596522704/.

Monday, February 28, 2011

Using the Java StringBuilder Class to Increase ColdFusion String Performance

One of the commonly known best practices in Java programming is to use the java.lang.StringBuilder class (read more here) when you are doing a lot of string concatenation operations.  The reason is because Java String (and by association ColdFusion strings) objects are immutable, which means that once a String is created its internal state is unchangeable.  So this means that every time you are changing a string, Java is actually creating a new string object behind the scenes and re-assigning it to your variable.  This got me thinking about the performance implications of using the StringBuilder class in my ColdFusion applications.

For this test I created two templates, one using the & operator to construct a large string and the other using the StringBuilder class to do the same operation.  Below is the code from both of the files (with most of the test text removed however I used the exact same text string for both files):

Using the & operator:

<cfscript>
 writedump(NOW());
 
 stop = false;
 
 myAppendedText = "";
  
 myText = "Lorem ipsum dolor sit amet, ...";
 
 myWordArray = listToArray(myText," ");
 
 for(i =1; i <= 2500; i++){
  
  myAppendedText &= myText;
 }
 
 writedump(NOW());
</cfscript>

Using the StringBuilder class:

<cfscript>
 writedump(NOW());
 
 stringBuilder = createObject("Java","java.lang.StringBuilder");
 
 stop = false;
 
 myAppendedText = "";
  
 myText = "Lorem ipsum dolor sit amet, ...";
 
 myWordArray = listToArray(myText," ");
 
 for(i =1; i <= 2500; i++){
  
  stringBuilder.append(myText);
 }
 
 writedump(NOW());
</cfscript>

The results were quite convincing.   Using the & operator the script ran in 23 seconds, the template using the StringBuilder object ran the code in under 1 second.  So the next thing I wanted to do was to see how well the ScriptBuilder method would scale so I increased the number of times the loop ran that added text to 5500 and the ScriptBuilder method still ran in under a second!

The moral of the story is that if you have to do lots of string concatenation the clear choice is to use the StringBuilder class.  I do stress that the effectiveness of this method only works under situations where you are doing A LOT of string concatenation.  The performance difference between the two methods was very minimal until I started to create some pretty big strings, but once I hit that threshold the StringBuilder significantly outperformed using the & operator.

Tuesday, February 22, 2011

Post some CF code on github and win a copy of the ColdFusion Anthology!

Since I'm far too busy to write a meaningful blog this week, so lets have some fun.  I have a brand new copy of the ColdFusion Anthology to give away (it is a copy with the missing chapter but its free so stop being picky).  To enter the contest all you have to do is write some ColdFusion code that will select a random winner from the comments of this post, create a gist for the code on github at https://gist.github.com/ (make sure you select ColdFusion as the language), and patse a link to the gist in the comments of this post. The contest will go through March 20th since its my son's first birthday. 

Since I'm paying for shipping out of my own pocket I can only ship to the Continental United States.  But if you aren't from the Continental US and still want to submit some code, I'd love to see it.  I can still pick you as a winner but the book will have to go to the runner up.  The winner of the book will be chosen by me as the one with the most creative code.  I also have a few hard copies of the ColdFusion 9 refcardz by Terry Ryan that I'll send to a few of the people chosen by the code that was submitted. 

Monday, February 14, 2011

What I Learned at the Milwaukee Hack-a-thon

This past weekend I participated in my first hack-a-thon put on by Spreenkler Talent Labs.  My team consisted of myself and 3 other developers: my good friend Ryan Nanney who is a php developer, Joe Steinbring who is a fellow ColdFusion developer, and Russel Stetzer who is a networking guy looking to break into the development side of things.


As this was my first hack-a-thon event I wasn't sure what to expect going in and I was very careful to make sure that my team didn't break any rules by doing any development work ahead of time.  Looking back I think I may have been too careful.  Prior to the event our team only had two short meetings to discuss our idea and go over some of the frameworks and technologies we were planning on using.   So going into the event we knew that we were going to build an application that would help non profits looking for volunteers connect to professionals that wanted to volunteer their time and that we were going to use ColdFusion 9, ColdFusion ORM, FW/1 as our MVC framework, github as our collaboration hub, and jQuery as our JavaScript framework.


The event itself was held in a computer lab at the University of Wisconsin Milwaukee, which proved to be a bit small for the amount of participants that were in attendance.   I'm glad I decided to play it safe and pack up my keyboard, external monitor, and mousepad since I arrived at the about 5 minutes late and all of the spots with monitors already there were gone.  Lucikly two of my team members arrived early and I was able to get a spot right by them.

Once the event kicked off our team got off to a slow start, I think that it was around 12:00 before we actually wrote a single line of code.  The morning was mostly spent getting everybody's development environment up and running and working on the getting the look and feel of our application sorted out.  When we finally started writing code things became quite hectic in a hurry. While we had our team roles pretty clearly defined ahead of time, we didn't have a very good plan on how we were going to actually build this application.  I was to be the guy person in charge of the master branch of the project and wiring up the different layers of the MVC framework,  Ryan N was to work on the CSS and jQuery, Joe was to work on the data model and database, while Russ helped work on the view pages.   



One of the biggest strategical flaws that I helped push was to use a few technologies that every team member wasn't familiar with, specifically ColdFusion ORM and FW/1.  While I felt that these technologies are extremely simply to use and learn, 8 hours just isn't enough to teach 3 people to use them and be productive myself. 

By the end of the day we had written a lot of code, however our application was quite disjointed and wasn't quite what we had envisioned for the application.   Even though I wasn't completely thrilled with our final product I can say that I had so much fun at this event that it didn't matter.  I also learned a lot of things that I'll put in practice at the next event because I definitely plan on doing this again.  After a little reflection this is what I learned for the next hack-a-thon:

Have all software installed before the event.
First and foremost make sure that every team member has all the software needed before the event, time is of the utmost importance and you don't want to waste it downloading and installing software.  

Don't be over ambitions with your application.
Just as important as being prepared make sure that you have an idea in mind that can be executed in such a short time frame.  The application you develop for an event like this should be extremely simple, I'd say no more than 2-3 screens max with an equally simple data model.  

While we felt that the application was simple enough before hand, we quickly realized that this application would need 4 or 5 distinct areas, each with its own set of screens and database tables.  This is far too many when you are trying to deliver a complete application in less than 8 hours.

A hack-a-thon is not a time to teach and learn new technologies
While my goal going into this even was to show people how great ColdFusion, ORM, and FW/1 were there just isn't enough time to teach, learn, and execute.  While I did succeed in wowing my team members with the capabilities of ORM and FW/1 too much valuable time was spent teaching and learning when we needed to be executing. 


Break free of your "enterprise" or "corporate" practices. 
When I first sat down to start coding I envisioned writing the elegant API with a very clean and nice separation of concerns in the MVC layer. I think at one point I even was going to thrown in a unit test or two???  What was I thinking??  This is a HACK-a-thon, hack the thing together and make the code pretty later.  Heck it ended up a mess anyway, I might as well have just started out throwing code together saved the time putting together a nice folder structure and object structure.  Since there is no shame in my game if you want to see what we pumped out in 8 hours the code is all up at github here: https://github.com/bittersweetryan/Waternoose.

While I wish our team could have represented ColdFusion a bit better I came away learning some valuable lessons that I will apply in the next event.  On top of all of that I also got a $10 iTunes gift card, the Xbox 360 game "Allen Wake", and a "Make Web not War" t-shirt.  All-in-all not too shabby for a Saturday.  I can't wait for the next one!