Friday, April 23, 2010

Finding Intersections Destructively / Nondestructively - Java Collections

What is an intersection?


Mathematical set theory states an intersection is the common elements between given sets. It's stated as such, A ∩ B, where A and B are different sets. 


Visually it looks like this: 















When would you need to calculate intersects?


Given n collections, you need to identify only the elements they have in common and ignore the rest.


Admittedly, I'm a bit spoiled coming from a web technology wherein most cases you can just write up some snazzy SQL to find the commonality and return the record set. In a good sized Java application though you'll often have a good amount of objects and data stored using collections in cache, so SQL is out of the question. You may be tempted to go down the road and create some sort of method that looks like so numberOfOccurrences(Set, String)that returns the number of occurrences and you use that number to determine what to drop and what to keep. This could work but there is a better, more efficient way to achieve this using a built in Java method - retainAll() that resides in the Collections interface. Lets see how:


The code







































  1. We create two sets each holding fruits. You'll see that Apple and Orange are the common elements between the two sets. Make believe these two sets are your collections sitting in cache.
  2. We create an HashSet called intersection to hold our common values. Since we are created a holding set, we are finding the intersection nondestructively, which means without modifying the any of sets being compared. Simply instantiate the intersection set passing in set1 as the initializer.
  3. To find the intersection, all we do is call retainAll(Collection c) passing in the collection to be compared.
  4. Then we print out the intersection results.
  5. Next I show you how to destructively find the intersection by using set2 against set1, again using retainAll() and printing out the both sets. You'll see that set2 has been altered.
You should see the following results...









So, there you have it. Pretty painless right?

Thursday, April 8, 2010

Helpful IntelliJ IDEA Shortcuts

IntelliJ IDEA Shortcuts

After settling in at the new gig, the IDE of choice for my team is IntelliJ IDEA. I've been using Eclipse for many many years now so there has been growing pains because of the simple fact that I was extremely familiar with all the ins-and-outs of Eclipse and the shortcuts they offered. After a month or so of using IntelliJ, I'm getting more comfortable with it. I found myself writing these notes on a scratch pad and figured I post an entry on it before I spill hot coffee all over my notepad and start crying like a little baby. Without further ado, heres my list:

Various Fixes - alt+enter

This tool is equivalent to ctrl+1 in Eclipse and acts as a kind of quick fix tool for you. You'll probably use it the most for the following:
  1. Adding import declarations.
  2. If code is highlighted yellow, IntelliJ is suggesting that you can possibly write your code in a more efficient manner. Simply double click the piece of code and hit alt+enter. This will give you some refactoring options.
Code Complete - ctrl+shift+enter

This nifty shortcut will complete syntactical code for you such as closing braces during a method declaration, or by typing "if" then hitting ctrl+shift+enter will close add the parentheses for evaluation as well as the open and close brackets for the if block. Probably does a lot more but that's what I use this for the most.

Dumb Auto Complete - ctrl+space

This "dumb" autocomplete usually appears automatically after you type the "." after an object variable. For instance assume someArrayList is of type ArrayList and when typing "someArrayList.", suggestions are offered based off of that object appear.

Smart Auto Complete - ctrl+shift+space

This is really useful one. It acts similar to the dumb complete key but there's is a crucial difference. This shortcut narrows suggested methods down by type. For instance, let's take our "someArrayList." example again. Shortly after the period you will get suggested methods based off of the entire ArrayList object. This is the the expected "dumb" auto complete view as I explained in the previous shortcut. However when you instead press ctrl+shift+space, IntelliJ will actually filter those methods based on the type in which the return is being assigned to. So if we were create a integer variable to store the size of someArrayList like so "int size = someArrayList.", smart complete will only expose methods off of the ArrayList object which will only return an int value like size(), hashCode(), lastIndexOf() and indexOf()... Very useful!

View Java Docs - highlight method or class+ctrl+q

Nuff' said.

Highlight instances of a term - highlight item+ctrl+shift+f7

Nifty shortcut that will search, locate and highlight all the matching terms you've selected within a file.

Refactor a piece of code - shift+f6

Highlight code and shift+f6 to view suggested refactoring options.

Extract expression to a method - ctrl+alt+m

There are times where you find yourself writing inline, procedural code that should be in its own method but you just don't get around to extracting it because you're lazy. This awesome shortcut provides a very simple way to highlight code, turn it into a method update your references to it. Just like Geico says, "so easy a caveman could do it". Do it!

Select word the cursor is currently on - ctrl+w

When you really don't feel like using your mouse... geek.

Cycle through open editors - ctrl+left arrow or ctrl+right arrow

Nuff' said.

Cycle through methods in a file -ctrl+up arrow or ctrl+down arrow

Nuff' said.

Once debug servers are setup to launch debug shift+f9+enter

Launches debug server.

Terminate the debug server - ctrl+f2

Nuff' said.

And finally, the usual suspects...
Search for a Java Class - ctrl+n
Search for file in project - ctrl+shift+n
Search for term within project - ctrl+shift+f
Comment out code - highlight lines+ctrl+/

There you have it. Hopefully this can help guide IntelliJ noobs like myself in the right direction. I'm still feeling my way through this tool so if anyone has any other useful tips for IntelliJ, please post a comment. I'd love to hear them!

PEACE.
-Mick

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.