March 2006


For Each Loop

I realized the other day I often use the old version of the for loop, with collections. Sun has the obligatory explanation that is good if you understand collections and generics. It is here. Their explanation taken verbatim is:


Iterating over a collection is uglier than it needs to be. Consider the
following method, which takes a collection of timer tasks and cancels them:

void cancelAll(Collection c) {
    for (Iterator i = c.iterator(); i.hasNext(); )
    i.next().cancel();
}

 

The iterator is just clutter. Furthermore, it is an opportunity for error. The iterator variable occurs three times in each loop: that istwo chances to get it wrong. The for-each construct gets rid of the clutter and the opportunity for error. Here is how the example lookswith the for-each construct:

 

 

void cancelAll(Collection c) {
    for (TimerTask t : c)
    t.cancel();
}

When you see the colon (:) read it as “in.” The loop above reads as “for each TimerTask t in c.”

What is important here is to read this as follows. Read it as you see the for keyword as "for each" and the colon (:) as "in".
The loop pattern above then becomes, "For each element in array do …".

 

Typed Collections or Generics

Java has had a set of collections which can store any object derived from Object like ArrayList and LinkedList. The problem with this is when storing you basically lost the type of the object and what was retrieved was of type Object. You then were forced to cast to the required type you needed.

NetworkDevice myDevice = (NetworkDevice) devices.get(deviceNumber);

Now we all did it this way and it worked didn't it. But because our ArrayList object accepts anything derived from Object (so any object) you could theorectically add any type, not just of type NetworkDevice.

In Java 5 we now have types collections and

ArrayList myDevices;

 

we can now declare it as

 

private ArrayList myDevices;

 

We have to make a corresponding change where the ArrayList object is created in
the constructor. Instead of:

 

myDevices = new ArrayList();

 

we now write:

 

myDevices = new ArrayList();

This can be read as the <..> roughly as "of". Thus, we can read the new construct "ArrayList" as ArrayList of NetworkDevices". This new definition declares that all elements of this ArrayList will be of type NetworkDevices. The reason for this is javac will enforce this by allowing only NetworkDevices objects to be added.

In a typed collection, since the type of its elements is now known, does not require a cast to be used when objects
are retrieved from it.

If we wanted to iterate over our collection in a method it requires an extra step because it is an untyped Iterator. The solution is to type the Iterator, because a typed collection will then returna typed Iterator:

     // show all out devicespublic void showAllDevices(){
     Iterator nwd = myDevices.iterator();
     while(nwd.hasNext()) {
          NetworkDevices dev = nwd.next();
          System.out.println(dev.toString());    }
     }

     // show all out devicespublic void showAllDevices(){
           Iterator<NetworkDevices> nwd = myDevices.iterator();
           while(nwd.hasNext()) {
               NetworkDevices dev = nwd.next();
               System.out.println(dev.toString());    }
         }

A last note, our collection above used one type parameter. When using a HashMap you do not enter a single element, you enter key/value pairs instead. Like this:

private HashMap<String, String> networkNamesMap;

And there you have it, completely type-safe and elegant.

 

Advertisements

I have been exploring and trying to explore and understand the new features in Java 1.5. I know, it is actually old news and I have been using them. But the other day I realized I really hadn't explored all of them and in the case of Annotations just kinda ignored the fact they were there. I will hopefully get to the new features of release 6 sooner.
Auto Boxing and Unboxing

We have all wrote code like this below to convert between primitive types like ints and objects.

Integer myInt = new Integer (27);
and
int i = myInt.parseInt();

Well 1.5 allows automatic conversion between primitive and object types.
So now you can write cleaner and less code that looks like this. This is
called autoboxing and unboxing.

Integer myInt = 27;

and

int i = myInt;

The code is really is more elegant than casting code everywhere.
The precise rules for autoboxing can be found in this

JCP article.
 


	
	

I attended the Northern Virginia Ruby User Group last night.  The presentation was an interactive live example of the capabilities of Ruby and well done by Devin Mullins (Thank you!).  Being very much on the beginning end I had the feeling I was probably one of the least experienced people.  There were 4 guys from Steve Case’s new healthcare company there and they are using Ruby (well Ruby on Rails) in production.  Their company Revolution Health Group is looking for Ruby developers.  A quick search on Hotjobs for “Ruby” returned 678 jobs.  Of course a share of these have nothing to do with the programming language Ruby such as companies located on “Ruby Street” but will be interesting to see any developments in this area (and I don’t have the time to weed out the non IT ones so lets just stick with 678).
Ruby appealed to me first of all with the “everything is an object” concept.  I skirted with Smalltalk in the early 90’s before being pulled head first into a C++ project.  By the time I emerged from that project Smalltalk had disappeared from the radar.  It has everything an OO language should have and what I have seen and the little bit I have done, it is fun.  Yes fun.  Not challenging like Java but you catch yourself going “wow, that was cool” a lot.  There is a good overview of Ruby on devx.com. If you are using Windows there is a one click installer located here.  As of writing, my favorite part is Modules or Mix-ins.  Modules are like classes except they have no instance and are not allowed to create a subclass from them.  You can think of these as a collection of similar methods in one place.  The other use of modules is as a mix-in (and this is really cool).  Ruby does not have multiple inheritance, but you can include one or more modules in a class and the class has access to the methods in that module. And, (drumroll please) it can be done at runtime.  Why if multiple inheritance is so bad do all new languages have a way to cheat the system and do it?  Just a thought.
I have read that Ruby, besides other uses, would be effective as a tool for teaching programming.  Hmmm, not sure about that one as; 1) I think learning should be done in a stricter language and; 2) Once students use Ruby they will be ruined for life as they will have had so much fun.  Would there be enough Ruby jobs out there to keep them going for their whole career?
Ah, the old IDE wars… 

Ian Skerret in his blog is claiming market share increase for Eclipse.  This is according to SD TImes.  This is not really new news as the blog from Ian was March 11th.  What is interesting in first Netbeans response.  Romaun Strobl a Sun Netbeans evangelist has responded in his blog.  Interesting is the two methods used to come to their conclusions. I think both are telling the truth in respect to their data gathering methods.  However, I have to say the Netbeans argument and method convinced me more.  They are using a unique ID for each IDE and not counting people begind firewalls etc.  Eclipse has certainly a large market share and it is a great open platform.  But Netbeans 5.0 has put the pressure on them. And don’t you just love the competition.  I mean the winner will be us, the users.
Last, in my line of work, in teaching at the University or just because I work in the field I am often asked about IT as a career.  Personally I think this is one of the best times to be in this business right now.  Here is an interesting article on the subject in Computerworld.   It basically backs up what I always say, if you are good, motivated and interested in not only the technology but in the business you are working in (don’t live in a bubble!!!) then you will be in demand and successful.
Bye for now….

Is anyone as confused or overwhlemed as I am with the choices facing developers today.  Now I know we all like to consider ourselves experts and masters of technologies but between Java, .NET, rich clients, thin clients, Ruby on Rails, various othert scripting languages and etc…  what is the right tool?  I have decided to do the following (this will probably, no I know it will, change).  Master Java/J2EE as much as possible, understand .NET and keep a keen eye on and play with Ruby On Rails.  I always loved Java since I started using it, it was a natural progression of C++ which I was pretty good at and didn’t have pointers.  I didn’t miss multiple inheritance and liked the platform independence.  No big news here.

When it came to desktop clients, well it is also no secret I did not understand why it was so darn hard to create a GUI in Swing.   I think I had a mental block.  Well Netbeans 5.0 came along and Matisse solved that one too.  But you still needed to add a jar file from Netbeans to your distribution.  Well, Sun does listen and they are doing the right thing.  The GroupLayout is going to be part of Mustang or Java 6.  Read this article on JavaLobby.  Proves Sun does listen to the community and know how to progress Java.  Great news!!!

As I mention in my short Bio here another interest both personally and professionally is Biometric security and specifically an area involving KeyStrong Dynamics.

Keystroke dynamics is a form of Biometric security. It is in the same category with retinal scans, finger print identification or voice recognition. Specifically it is the process of analyzing the way a user types on a keyboard and identifies him or her based on his typing rhythm habits. A user’s typing pattern can be unique because similar neuro-physiological factors that make written signatures unique are also exhibited when typing. Keystroke dynamics is not what you type, but how you type.

Features commonly used to describe a user’s typing pattern are:

– Latencies between successive keystrokes (the elapsed time between the release of the first key and the depression of the second)

– Duration of each keystroke (How long is the key held down)

– Finger placement

– Pressure applied on the keys

– Overall typing speed

The idea behind Keystroke Dynamics has been around since World War II. It was well documented during the war that telegraph operators on many U.S. ships could recognize the other sending operator by his typing patterns. Known as the “Fist of the Sender,” the uniqueness in the keying rhythm (even of Morse-code), could distinguish one operator from another.

http://www.wsta.org/publications/articles/1003_article06.html.

Advantages of Keystroke Dynamics:

– Non intrusive and wide user acceptance

– Natural authentication mechanism for computer and network security

– Continuous verification (monitoring) is possible

– Minimal training

– No additional hardware

For more information check the following links:

www.verticalcompany.com or www.biopassword.com

This week was an eventful one for me. We did loads of business at FDM and I even made it out to a client to do some programming. Our guy there had to take off for a couple of weeks because his mother is ill and we needed to keep moving as well as show the client we care (which we do). So in between everything else and being Spring Break at GMU I spent 5 hours gettings some pieces working.

One of the system components we had discussed but not yet decided how to handle was the charting for the system. I had read about JFreeChart several times but hadn’t really had time to evaluate it. Well I have now and I am sold, beyond sold. One thing you will find is I rarely cover products, frameworks etc I don’t like so this will be full of compliments. If it is not good it won’t be mentioned here too often.

I started by downloading the framework, playing with the sample application and showed it to our client. All OK so far. Then I paid the $40 or so for the complete developer handbook and source code to the demo. I figure the demo has every chart that we will need and with the source code we will save way beyond $40 of time. I will keep you updated but it is really good.

Do you want to learn J2EE, check out the course from Sang Shin at the JavaPassion website. I looked at his content and he has basically added some exercises, structure and provides guidance on the Sun J2EE Tutorial. If you have time enough to do it then take and see if it is what you might like.

By the way a couple of my friends have looked at ThinkFree Office that I mentioned last time. So far thumbs-up from all parties. I had a problem with downloading of the applet the first time I used it and sent an email to support and had an answer within a few hours.

On my links I have the e-magazine from Mark Collins-Cope called ObjectiveView. This is another great read and one you can view online in the PDF or download the entire PDF for later reading (my preferred method). I ran across it researching information on Ruby of which the last issue (Issue #9) has two good articles. There was also a good article about Ajax as a bonus.

News on a new open source SE version of Java. It is explained here. Supposedly Eclipse is running on a version of it, but would it work if Eclipse was using Swing? Interesting question I think.

As you may have noticed I like reading Joel On Software. I found one of his archived articles with tips on making realistic schedules while managing a project. I actually cover most of these in my IT Project Management class at GMU (in the middle of 1000 other items over 15 weeks). I did see a couple of extra ones like number 9) Put Debugging Time Into the Schedule that I will add in there.

Currently perusing the Java Cookbook by Ian F. Darwin. Books like this are an excellent Sunday read and give you loads of ideas and tidbits to use later. I am already using parts in the current development project.

OK, enough for today.  Check out the interview with Steve Ballmer on Channel 9.   That guy has some energy.

The week is flying by as usual and I have not put anything in here out of the 1000’s of items I have considered.   I downloaded another editor, this one I heards about on the Java Posses podcast.   It is called the BlueJ – interactive Java Environment.  In my last Programming II class which we use Java for a lot of the students struggled.  There were many reasons but the main problems are: 1) Complete lack of very basic OO and Java knowledge (which they should have from Programming I; 2) Difficulties with Swing programming (event handling, layout managers) etc.  While I totally understand number 2 as I went through that myself, I struggle with number 1 as they should have it and it completely throws off the course if I spend too much time doing this.  So, I have been looking, considering and pondering a solution.   Along came BlueJ.  In my, so far, short evaluation it allows each development of small classes, ability to build relationships between classes (inheritance, containers, etc.) and best of all to visually see this relationship.  Stay tuned!

Because a consultant who works for me and was to start at a client has had a family emergency, I have been forced to dive into Java programming.  Halleulujah!   As you can imagine I am not unhappy with this and welcome the chance to spend some time away from sales, contracts and budgets.  The project is in its infancy but requirements have been gathered and a basic design made (all by me earlier).  Therefore, for a change, I am finally puting to use an IDE I downloaded in a way other than just checking out the newest features.  Netbeans 5.0 is wonderful to work with.  Let me tell you why.  One word, Matisse.  The Swing GUI builder is a piece of art.  Anyone who has struggled as much as I have in Swing GUI building (manually and in JBuilder) will love this.  Maybe I was spoiled as my first GUI building experiences were in Gupta SQL Windows, then Powerbuilder and the MS Visual C++ with MFC.  All of them worked like I thought they should work.  Well, in Gupta the GUI building did anyway.   Then I worked on my first Java development and was faced with the flexible, powerful and confusing GridBagLayout and GridBagConstraint.  Now I subscribe to the view development will never be a matter of only pointing and clicking.  Manual programming will never go away but I do subscribe to the view this should not be the case for the user interface of the application.  Well, now Matisse has come along and although an additional jar file is needed as they use a Swing extension for the layout manager I actually can lay out the GUI and my UI controls don’t move on their own, look the way they do in design as when I run the application and are easy to align and build due to the c oncept of snapping.  Thank you!

Now Matisse is being ported to Eclipse.  See this article for more information.

Cool product, for editing and storing Office documents over the Internet is ThinkFree Office.  Check it out.  Even if you don’t want to use it just try it out to see how cool applets are becoming again.

Finally, it probably has been discussed and linked and argued more in the past week than any other article in our world, but if you haven’t read it James Gosling is not worred about C#, Ruby or PHP

Next Page »