Thursday, February 25, 2010

Code coverage & cyclomatic complexity calculations coming to ColdFusion

We've heard it over and over again that ColdFusion 9 has made excellent headway in terms of providing engineers with great support to execute proper object orientation without all the bloat. Along with CF9 and awesome unit testing tools like MXUnit and Mockbox, unit testing is really becoming a mainstay for a lot of ColdFusion applications and I hope that it continues to stay that way. 


However one critical and often overlooked aspect of unit testing is code coverage and cyclomatic complexity calculation. Often times, developers feel that just because they've got a good amount of tests that its "good enough" without taking a step back and asking themselves questions like:

  • Are my unit tests covering every line of code?
  • Am I testing for every distinct path of execution inside a method?
  • Is my code written efficiently or is there room for improvement?
Perhaps you've asked yourself these questions but didn't know what the answers to it are. Well the answers lie in code coverage and cyclomatic complexity...

Code Coverage

Code coverage metrics show you the percentage of code that is covered and not covered by your unit tests. This is extremely beneficial to identifying the "holes" in your unit tests. Uncovered lines means no unit tests exist for those lines which is an indirect measurement of code and test quality. If you have not tested it, then it's at risk for error and should be addressed asap before rolling that beaut into production.

Cyclomatic Complexity

Also known as CCN, it answers the question of "is my code written efficiently?". To boil it down, take a method and imagine all the ways you as the developer can cause simple or complex conditionals. Meaning if's, switches, nested if's, inline method calls to other methods etc... 

The basic idea is that each of these "conditional" execution paths add to code complexity. In the programming world you always want to keep code complexity to a minimum because the more complex conditional code you have riddled throughout your code base, the less maintainable it is and extensibility becomes almost impossible. Your software becomes risky as more complex paths are added resulting in unhappy customers and stressed out engineers - and I think you'd agree with me that stress sucks and in a volatile software, release days are nail biters... 

So the idea is that you run CCN metrics on your classes and it will spit out a number for you. The standard is that the number should be under 10 and anything over that should be flagged, reviewed and more often that not re-written.

Code Coverage and CCN coming to ColdFusion


In languages like Java and C#, there are tools that provide this level of support but not for ColdFusion. That is until now!


Written with Java and ColdFusion, cfcommon's Chimera project will provide you with that critical line of defense to help engineers identify parts of their code that need unit tests and/or need to be re-factored because of too much complexity.


Attached is a preliminary screenshot of Chimera playing nicely with MXUnit tests.


Chimera ColdFusion Code Coverage Analysis


Although this image shows ColdFusion code writted in tags, we will also be providing script support as well ;)


Please stay tuned as we will be releasing Chimera BETA very soon and you can check out cfCommons in the meantime!


PEACE.


Mick

Tuesday, February 23, 2010

Building a cfcommons application - Battlefield Part I

Overview




cfcommon's pluggable architecture allows you to harness many of its stable modules and plugins bit by bit, piece by piece without inheriting bloated code and unnecessary overhead. Each module is carefully crafted and engineered to ensure stability and developed with clear and concise features. Gone will be the days of installing multiple frameworks for different feature sets and having to deal with the baggage of worrying about collisions and incompatibility issues that can occur between them. 

To get a full appreciation for what cfcommons is all about, in the next few posts we will create a cfcommons application from the ground up, utilizing each module and plugin "as needed". You will see how incredibly simple it is to not only plug and play features, but also how each module plays nicely with each other.

Without further ado let's create our application using first up cfcommon's Neodymium  - an automatic dependency injection plugin.

dependency injection, what is it?

Also known as "Inversion of Control", is one of the most critical pieces in building clean, enterprise level object oriented software. If you are unclear about dependency injection, I encourage you to first read about what it's all about.

Many languages have frameworks that enable your software to leverage dependency injection like Java's Spring to .NET's Castle Windsor to ColdFusion's Lightwire. The old way was to "wire" up these dependencies via XML or bean configuration which is extremely wasteful in terms of keystrokes causing you to run into either a gigantic bean config file or a gigantic XML. A good way to induce coder's coma...


Yea yea, you can break things up into separate XML files or use "shortcut" attributes to help lessen the bloat but still, we're talking about making what will be a thousand line XML template down to hundreds...at least for awhile until it grows even bigger. Thanks, but no thanks..

what do you mean by "automatic" dependency injection?

Neodymium allows you to simply annotate your class properties with the right type and it will automatically inject those properties for you during application startup or reload. Once you ask the factory for a bean it will return to you the object with its dependencies properly injected for you.

so no XML mappings or bean config??!?






None. Nada. Zilch.

what if you don't want objects to automatically be injected?

Then use the exclude annotations.

what if I'm l337 and I want the type to be an interface?

Then use the combination of @type and @implementation, which gives the path to the concrete class. You're so 1337...

Battlefield Application - Part I

Let's create a cfcommons app shall we?! I didn't want to use the played out car/student/shapes/{insert boring, mind numbing tutorial topic here}, so I opted to go with a battlefield app which I'm hoping we can turn it into some sort of army game over the next few posts.

We will start by implementing automatic dependency injection via Neomydium. The battlefield code is also available for you to download and install as you follow along...

install cfcommons and create the web directory for this tutorial



  1. Install the cfcommons core modules library into your web root.
  2. Create a /battlefield/ directory under your web root. This will be the directory that houses our sample application.
  3. Under create a /model/ directory. Here is where we will put all our classes and interfaces.
  4. Under the /model/ directory create an /interfaces/ directory. Self explanatory...
create the context config XML file


This file is the central file that you will drop the cfcommon plugins.
  1. In /battlefield/, create a /config/ directory
  2. Inside the /config/ directory create an XML file called context-config.xml that looks like so:
 

In this XML you'll see we've declared both a development and production environment and told the Battlefield application that we will use the Neodymium automatic dependency injection plugin via one simple plugin tag.

Once complete, your directory structure should look like so (minus the .settings, that's eclipse stuff.): 



ok the good stuff now. let's take a look at what we are about to build.
    Simple right? We are going to create a soldier that "has-a" weapon. For all intents and purposes, let's usimagine that by default the Soldier should always be equipped with a knife by default. Meaning every time we need an instance of a Soldier from the bean factory, let's always make sure it has a knife object attached to it.








    where the rubber meets the road...




    Line 3 baby, it's where the magic happens. By simply annotating the property, Neodymium will register Soldier beans with its dependencies properly injected.


    test drive - index.cfm




    Here, we are:
    1. Creating an instance of the PluggableContextFactory based off of our context-config.xml we created earlier with the Neodymium plugin installed.
    2. Then we simply ask the context factory for the soldier object.
    3. Then dumping the Soldier and it's weapon.
    index.cfm results


    Viola! Notice that the Soldier object has a Knife object dependency attached to it. Automatic dependency injection baby...

    download the code

    Battlefield Part 1 - be sure to also install the latest cfcommons module library here.

    conclusion

    Hopefully you are starting to see the power behind cfcommons. With one simple declaration in the context-config.xml, we've added dependency injection support in literally a few seconds.

    Neodymium also supports the usual suspects when it comes to dependency injection like singletons, interface based typing and custom annotations. Find out more about it here.

    In Part II, we will build upon this application and integrate the SimpleMVC then perhaps SimpleSecurity.

    Visit http://cfcommons.org/ for more information or to be a contributor.

    Till next time, later peeps!

    Mick

    Friday, February 19, 2010

    cfcommons Reflection API

    what is reflection?


    Reflection is the ability for a program to introspect details about itself (the source code), understand it and even modify it. 


    is it possible in ColdFusion?


    Yes, don't get it twisted :P


    really, how?


    In ColdFusion functions like  getComponentMetaData() and getMetaData() that will provide you with source level information such as method names, arguments name, type information, annotations, class hierarchy  etc. So when you call one of those methods you are essentially using reflection. You are asking the object to reflect upon itself and let you, the developer, know about it.


    ok, but how is this powerful?


    Simple - let's take cfcommon's lightweight automatic dependency injection plugin called Neodymium. The problem was how do we provide a lightweight automatic dependency injection plugin with these goals in mind:




    • It must be lighting FAST
    • Absolutely zero XML
    • It must be lighting FAST
    • Absolutely zero bean configuration
    • It must be lighting FAST
    • Absolutely no other feature other than dependency injection to bloat the code
    • It must be lighting FAST

    By leveraging cfcommon's reflection API, at application start/reload we are able to to reflect upon all classes (cfc's) in a designated directory (package) check to see that if they have a type attribute associated to it then we will automatically inject those dependencies into the object factory. If there was a doNotInject annotation then we simply do nothing.

    See how powerful that is? Extremely. Oh and did we mention it's freaking fast?

    if ColdFusion already gives us the ability, why use cfcommons? 

    Although ColdFusion's reflective functions are helpful, there is a lot of uneccessary code you need to write to get at specific information. cfcommon's Reflection API provides you with object oriented classes that help you get at what you need with one method call. Some examples:
    • Need to check if a class is annotated? use isAnnotated()
    • Need to get all annotated methods of a class? use getAnnotatedMethods()
    • Want to know if a method has an annotation? use hasAnnotation()
    • Need the superclass? use getSuperClass()

    sky's is the limit

    The goal of the cfcommons project is to push the limits forward for ColdFusion. It's a call to developers to think outside the box and to help provide stable, reusable  modules using a powerful platform. Reflection is just one of many modules available to you. 

    So give it a try it! Can you think of a problem that you can solve via reflective methods?

    i want more information!

    A must read about Reflection API WITH examples - reflection documentation.

    Questions?

    Brian Carr,  the mastermind behind cfcommons,  can always be reached via:
    • email : brian@cfcommons.org
    • twitter: @cfcommons
    You can also reach me at micky@cfcommons.org or on twitter (@mickydionisio).

    Thanks peeps!

    Thursday, February 18, 2010

    ColdFusion Commons Project Released

    Over the past few months I've been involved with a new project called the ColdFusion Common Modules Project. Inspired by Java's Spring framework, Apache Commons, and ColdFusion's Quicksilver framework. What exactly is it? 


    ColdFusion Common Modules Project


    The ColdFusion Common Modules project (CFCommons) is a collection of initiatives intended on producing reusable, stable, object oriented ColdFusion component libraries.


    What's in it for you?


    This project is intended to provide ColdFusion developers with highly scalable, reusable components. Components that are created for YOU, by YOU.





    You as a CFCommons developer will make an effort to ensure that your components/plugins  play nicely with other plugins and that your interfaces are extremely stable and reusable by implementing proper object orientation techniques and interfaces. This ensures that any developer using a CFCommons component can rest easy knowing that installing a new component won't break ten other CFCommon components.

    In its first release, CFCommons offers a handful of features and Context plugins that range from simple MVC to layout management, from automatic dependency injection to ReST web services, from templating to service level transactionality.  CFCommon's plug and play architecture allows you to produce decoupled plugins by utilizing the CFCommon Context and Reflection API. The sky is the limit on what you can create.

    Let's take a look at the CFCommons modules...

    CFCommons Modules

    • Context - The CFCommons Context is a reflective, pluggable application platform. This is the heart of CFCommons.
    • Reflection - The Reflection API is a small set of components that wrap the standard structure output of the native CF reflection methods, getMetaData() and getComponentMetaData() and provide an object-oriented and enhanced view into ColdFusion component (.cfc) meta-data.
    • AOP - The AOP module brings full-featured stand-alone Aspect Oriented Programming facilities to ColdFusion with an API that is both easy to understand and implement and that is not dependent upon any other libraries or frameworks.
      • Leverages ColdFusion dynamic language features to provide a programmatic join point model which supports before, after and around join points.
      • Fast and easy applicaiton of advice to pointcuts.
      • Advice types are custom function references, or methods that exist on object instances. No need to have advice implement an interface or extend another AOP API specific type.
    • Templating - The cfcommons templating module promotes fixed content reuse by providing a means to inject variable content at specified locations within given text. Perfect for the implementation of semi-mutable views such as form-letters or email templates, this module provides an object-oriented set of Components that promote effective templating.
    • Faceplait - Faceplait is a stand-alone, framework agnosting layout manager.
    • HTTP- This module provides library components who's purpose it is to make working with common HTTP tasks, easy.
    • Chimera - A Java/CF based code coverage and cyclomatic complexity tool. (Built to place nicely with MXUnit.) MXUnit peeps, we'll be reaching out soon so stay tuned!
    Here's a quick screen of chimera:



    Want a test drive? Take Weyland out for a spin.


    To get up and running quickly install Weyland along with the CFCommons core. Weyland is a simple HTTP Context with MVC, automatic dependency injection, layout and security support.
    1. Drop the org directory in cfcommons into your web root.
    2. Drop the weyland directory inside of root as well.
    The directory structure should look like so:













    And after visiting http://localhost/weyland you shuold see this:






    From that screen you can try out the secure login example and dive right into the code using the documentation. Download them both here!

    Interested in learning more or contributing?

    Please visit the CFCommons site, poke around, read some documentation and try it out.

    Are you interested in becoming a CFCommons developer? Contact us to submit yourself as a contributor.


    Holla.

    Thursday, February 4, 2010

    Immediate Web Performance Enhancements

    Been doing a lot of research lately on web performance and came across the work of the Exceptional Performance Team from Yahoo!. This team is responsible for putting together best practices to achieve high performing web sites.


    I've hand picked some of their best practices that are, in my opinion, relatively quick to implement. Below I've listed the tips and a quick summation of each. However I encourage you to take a look at the entire list posted by the performance team. There are a total of 34 best practices spanning 7 categories. I've posted the link at the end of this post.


    Without further ado, let's jump right in:


    Content


    Minimize HTTP Requests

    • Combine script and css files -  During your release process, you can use a number of the tools out there to combine, also known as minifying, your scripts and css files.
    • Use css sprites - combine images into one file and use the css image styling properties to display the correct image. For instance, if you had a set of images that are essentially rollover images, combine them all into on image so that instead of the browser having to load 10 on/off images, it only needs to load it once in one HTTP request.
    Cache AJAX Requests - Expires or Cache-Control headers are your friends. Append a timestamp to your url to ensure so that any subsequent calls to that url will be from the cache. It's important to note that if for some reason the user performs some action that will need to make a request to the url that has already been cached, you need to ensure you update that url's timestamp. 



    Split Components Across Domains - Per the HTTP/1.1 spec, browsers download two components in parallel per hostname at a time. As a rule of thumb, you should separate your static content like images/css/scripts/documents from the servers that server up your dynamic content. This means that if you have three domains, one that serves dynamic and two that serves static, then you allow 6 "parallel downloads" at a time per request.


    CSS


    Put style sheets at the top - This tip is more of a pseudo performance boost because the idea is all about progressive loading.  It's all about instructing the browser to load items such as images and layouts as soon as possible, once they are available. The HTML page should be your loading indicator.


    Choose link over @import - In IE, @import behave just like a link at the bottom of the page which impedes progressive loading. Keep it simple...


    Javascript 

    Make Javascript and CSS external - well it's almost always a good idea. The reason I say almost is that you should be mindful of, as the team puts it, "..the frequency with which external JavaScript and CSS components are cached relative to the number of HTML documents requested.". If there is a page that uses CSS and/or Javascript but that page is only visited 1-2 times upper limit per user session (like the homepage), then it might not make sense to load external files since quantifying the performance boost would be difficult and probably end up being negligible. Better to put it inline so that CSS can be loaded quickly lessening HTTP requests to external files and maximizing progressive loading. Of the course on the opposite side of the spectrum if you have CSS/JS that is being used across different pages and those pages are high trafficed, then you should absolutely place those CSS and Javascript files in external files. 


    Remove duplicate scripts - no brainer here...


    Put Scripts at the Bottom - Putting scripts in the head of the HTML file blocks parallel downloads. If you can get away with it, put your scripts right before the end of the body tag.


    Minify Javascript and CSS - Basically this means to remove spaces characters and comments from your JS and CSS files. You can take this a step further and even combine your minified files into one. As with anything in programming, use your discretion as the need for combining scripts or css into one file might not make sense in every application.


    Server


    Flush the buffer early - If your page is heavy on the back end processing you might consider flushing the buffer. In doing so you will allow you to begin fetching components like images, css, scripts. The ideal place to put this is right after the head tag, before the body.


    Add an Expires or a Cache-Control Header - This is inline with their "Cache AJAX requests" rule. The performance team boils it down to two rules.

    1. For static components: implement  the "Never Expire" policy by setting far future Expires headers.
    2. For dynamic components: use an appropriate Cache-Control header to help the browser with conditional requests.
    So there you have it. Some of the few practices from the Yahoo! Performance Team that I believe you could probably do in a reasonable amount of time.


    Also if you haven't already take a peek at YSlow that integrates with Firebug for FireFox. Also Smush.it from Yahoo! is a pretty cool tool for optimizing images without losing quality.

    Till next time... PEACE.


    -Micky

    References
    Best Practices for Speeding Up Your Web Site - Yahoo! Exceptional Performance Team



    Tuesday, February 2, 2010

    Javascript Closures

    What is a closure?

    If a function is created in such a way that it will retain it's local variable scope even after the function exits - then its a closure.

    What do I need to understand first about Javascript to understand closures?

    1. Javascript uses lexical scoping. Huh? Simply put, local function variables are kept alive even after the function exits. You'll hear this explained a few different ways - "variables are kept alive after the stack frame/pops off/deallocated/ends/completed/{insert geeky word to signify stack frames ending}".
    2. By default, inner functions have access to variables within their outer functions. It does not matter whether its 1 or 10 levels up. This is absolutely paramount in understanding closures.

    How do you create a closure?


    Any time you create a function within a function and the inner function refers to an outer function's private variable, you've created a closure. Simple as that, don't over complicate it.


    A Simple Closure




    In this example, here is what's going on...

    1. Line 1 - We create a function called multiplyTemplate with one argument.
    2. Line 2 - The argument is saved to a private variable called multiplier.
    3. Line 3 - We declared an inner function. Something should have clicked here. Remember what I mentioned about inner functions having access to parent function's variables scope. multiplyTemplate is now a closure. Why? Because it is using its PARENT function's private variable multiplier. What's going on here to the end of this inner function on line 5 is absolutely critical to understanding closures.
    4. Line 4 - We return the value of multiplier times y. Multiplier is a private method of the outer function.
    5. Line 8 - we create a new variable that executes multiplyTemplate(5). Remember the return of  is a multiplyTemplate function, not a primitive int value. It's on this line where the rubber meets the road. Here is what just happened:
      1. multiplyTemplate(5) was fired and a new function context was created.
      2. The argument of 5 was assigned to this function context's private multiplier field.
      3. An anonymous function was returned whose value of x is being RETAINED/KEPT ALIVE even though multiplyTemplate(5) has exited.
    6. Line 10 -  multiplyBy5(10) is executed using the function context declared on Line 8. The argument 10 is actually the y argument on line 3 which uses x to multiply to itself. The multiplier x is still 5 through closure and the value that returns is 50.

    Why use a closure?
    I'm sure there are a handful of reasons where you would want to use a closure, however in my experience I've only used them for a couple reasons. 

    1. On main reason is if I need to properly encapsulate data inside an object whether it be transient or a singleton.
    2. Attaching event handlers to a DOM object via anonymous methods+closure inside of a for loop.
    That's the skinny. There are many many many resources out there that explain closures in less-than-understandable format but hopefully this helps demystify it a bit.

    -Mick