Wednesday, April 30, 2008

NetBeans 6.1, UML, and Attribute/Operation Visibility

NetBeans 6.1 supports three types of UML projects: platform-independent UML, Java-specific UML, and UML reversed engineered from Java code. In this blog entry, I'll briefly cover the differences between platform-independent UML and Java UML attribute and operation visibility for class diagrams in NetBeans. In a previous blog entry, I discussed the differences between these two types of UML in relation to placement of data types for attributes (members), operations (methods), and return values from operations/methods.

Platform-independent UML uses different notation to denote visibility than does Java-specific UML. While Java-specific UML uses the same keywords as Java code syntax itself (public, protected, private, and package), platform-independent UML instead uses + for public, - for private, # for protected, and ~ for package.

NetBeans makes attributes private by default in both forms of UML and makes operations public by default in both forms of UML. If the developer specifies a visibility for operations or attributes that is not recognized by NetBeans, NetBeans will make that operation or attribute package visibility in Java-specific UML and will mark such an operation or attribute with a ~ symbol in platform-independent UML.

The following two PNG files were exported from NetBeans using its "Export as Image" (CTRL+Shift+X) option. They show how NetBeans 6.1 treats attributes and operations of these various visibilities in Java-specific UML and platform-independent UML respectively.

Java-Specific UML

Note that NetBeans automatically creates a constructor for Java-specific classes and also automatically generates get/set accessor methods for all added attributes no matter the visibility of those attributes.



Platform-Independent UML

Note that no constructors or accessor methods are automatically created by NetBeans for platform-independent UML.

Tuesday, April 29, 2008

Specifying Variable, Parameter, and Function Types in ActionScript and UML

ActionScript is generally a very easy language for Java developers to pick up because of many similarities including syntax similarities, common object-oriented features, ASDoc similarities to Javadoc, and other common features. However, there are a couple small things that can seem a little strange to the Java developer who is starting to use ActionScript. These include the need to declare local variables as const or var and the placement of a datatype after the name of the variable, parameter, or function that type applies to.

While placing the datatype of the variable or constant after the variable's name or the constant's name seems a little strange to Java developers, it is the prescribed way of expressing type in the Proposed ECMAScript 4th Edition Language Overview. Likewise, placing const or var is also called out in this newer in-work version of ECMAScript (ECMAScript Edition 3, the specification behind most flavors of JavaScript, was finalized clear back in December 1999). In fact, Firefox/Mozilla JavaScript already supports use of const and all major flavors of JavaScript support var.

What may be even more interesting to Java developers transition to ActionScript is that the ActionScript syntactic approach to expressing data types matches the UML approach. As shown in Class Diagram examples (Figures 2 and 3) of UML Basics: An Introduction to the Unified Modeling Language, the data types for class data members and for method return values are expressed following the data member name or function they describe with a colon connecting them. The diagrams in the previously referenced article don't show it, but the same is true for parameters to methods -- the data type of each parameter is expressing after the name of the parameter with a colon between the name and type.

In NetBeans 6.1, the UML tool allows for "Platform-Independent Model" UML diagrams to be generated or the developer can select "Java-Platform Model" UML. If the platform-independent UML is used, the data types for the data members are expressed following the data member names. Likewise, the data types follow the methods and following the names of parameters in a method signature. In other words, class data member, function return values, and function signatures look very similar in platform-independent UML as they do in ActionScript. The next screen snapshot (click on it to see larger version) shows how this platform-independent UML looks very much like ActionScript syntax.



When one uses NetBeans 6.1's Java-Platform Model UML capabilities to generate a Java UML diagram, it looks Java-like as shown in the next screen snapshot (click on it to see larger version). Note also the class descriptive text in the lower left corner. Also note that the NetBeans 6.1 IDE automatically adds the getter/setter method for the Java class attribute in the Java platform UML.



When the UML diagram above is generated as code using the NetBeans option of "Generate Code..." provided by right-clicking on the UML project, the following code is generated (note that the class documentation is included as Javadoc documentation for the class):


/**
* <p style="margin-top: 0">
* This class is being created in NetBeans 6.1 using its UML tool to
* demonstrate UML representation of a Java class.
* </p>
*/
public class SomeJavaClass
{
private int aVariable;

public SomeJavaClass ()
{
}

public int getAVariable ()
{
return aVariable;
}

public void setAVariable (int val)
{
this.aVariable = val;
}

public void doSomethingToAVariable (String aVariable)
{
}
}


While ActionScript syntax for expressing data types of class members, function return types, and function parameter types may seem a little strange to Java developers at first, the fact that this same syntax is used with platform-independent UML should help with the transition.

Monday, April 28, 2008

Effective Java Second Edition

There have been several blogs (see here and here) recently talking about the second edition of Effective Java, expected to be released at 2008 JavaOne Conference. As of this blog entry's writing, Amazon.com's "Look Inside" feature for the Second Edition still links to the table of contents for the First Edition. However, the Pearson web site does link to the new table of contents for the Second Edition.

The Pearson web page's listing of the Effective Java Second Edition Table of Contents shows 78 items in the Second Edition (the First Edition had 57 items). There are entire new chapters in this edition to cover features introduced with J2SE 5. For example Chapter 5 is called "Generics," Chapter 6 is called "Enums and Annotations," and the Concurrency chapter (chapter 10) appears to be quite different to cover the Java threading support.

The table of contents for the Second Edition certainly gives a good insight into what to expect in that edition. Another preview of this edition is available in the 2006 JavaOne presentation Effective Java Reloaded (TS-1512).

Saturday, April 26, 2008

Flex 3 Versus Flex 2

I've been enthusiastically telling fellow Java developers about the many benefits of using Flex with Java EE back-ends in recent months. As part of this effort, I have presented on the benefits of Flex at conferences and a common question at the conferences and in person when talking with developers is "What is the difference between Flex 2 and Flex 3?" This is a bigger question than I can hope to answer, but I will document the differences that are most important to me in this blog entry.

The first and most important observation related to comparing Flex 2 to Flex 3 is that the changes are nowhere near as significant as going from Flex 1 (or Flex 1.5) to Flex 2 (or from ActionScript 2.0 to ActionScript 3.0). Because many of us started using Flex after Flex 2 was already available, it is shocking to us when we learn what Flex 1 and 1.5 were and how different Flex 2 was. With the transition from Flex 2 to Flex 3, there are new features and enhancements, but nearly everything written in Flex 2 will work in Flex 3 and even much of your new code will probably remain unchanged from what you would have written in Flex 2.

An obvious starting point for looking at what's new in Flex 3 is the Adobe Developer Connection (Flex Developer Center) article What's New in Flex 3? by Matt Chotin. This article covers some of the new features you see listed in association with Flex 3 in other articles and blogs: native support of Adobe Integrated Runtime (AIR), new components,
FlexBuilder enhancements, the Persistent Framework Cache, and (most importantly to some) the open sourcing of Flex compiler and SDK.

The Flex 3 SDK Release Notes and the Flex 3 Builder Release Notes are two more obvious sources of information about differences in Flex 3 as compared to Flex 2. The Flex 3 SDK Release Notes list many of the same new features as the Chotin article mentioned above, but also include later developments and additional information. We see in this document that the Flex Charting package was significantly enhanced for Flex 3 and that the two newly added components (Advanced DataGrid and OLAP DataGrid) are only available with FlexBuilder professional. These are, of course, not benefits to users solely of the free SDK. However, we also see in these Release Notes that the Flex Ajax Bridge Library is now a standard part of the Flex SDK and there is more information on the open sourcing of Flex 3. The FlexBuilder 3 Release Notes have an even longer list of enhancements, but I don't intend to go into those here.

As one can ascertain from the above descriptions, users of Flex-related products with licensing fees (FlexBuilder, Charting Package, etc.) enjoy many of the Flex 3 enhancements that the open source, freely available SDK does not. Perhaps the most disappointing to me free SDK omission was the only two newly added Flex 3 components not being included with the free SDK (although Flex charting is really nice and I'd love to see that in the free SDK as well).

One thing worth pointing out to people is that Adobe open sourced BlazeDS before they released Flex 3. While it is easy to think of the release of BlazeDS and Flex 3 as one and the same, they were actually two separate releases. This made BlazeDS freely available to Flex 2 developers and it is likewise available to Flex 3 developers as well.

There are already some interesting consequences from the open sourcing of Flex 3. For example, Flex SDK Code Conventions and Best Practices has been released. I am sure that many organizations will adopt these for their own just as many organizations using the Java programming language have adopted Sun's Java Coding Standards.

In this entry, I've referenced some of the highlights of new features of Flex 3 and even elaborated on a few of them. However, there are smaller enhancements that are very useful. One of these is the conditional compilation.

I have run into very few issues migrating from Flex 2 to Flex 3. However, the document Flex 3: Backwards Compatibility and Migration is useful to have handy as a reference when doing such a migration. Another useful reference is Migrating Applications from Flex 2 to Flex 3.

There are numerous resources covering the differences between Flex 2 and Flex 3. For anyone starting greenfield projects, I enthusiastically recommend beginning with Flex 3. Even though there are not a lot of books available on Flex 3 yet, Flex 2 is so similar and there are so many things in common that a good Flex 2 book will help developers get going quickly even with Flex 3. Likewise, online Flex 2 resources will generally be applicable to Flex 3 as well. In addition, there are new Flex 3 resources available all the time.

I really enjoyed using Flex 2 and Flex 3 and look forward to the enhancements that will be delivered with Flex 4 (Gumbo) in the future.




Additional Resources Comparing Flex 3 to Flex 2

* Flex 2 vs. Flex 3

* Flex 3 - The Most Important Feature

* Flex 3 New Features Collection

* Dramatically Smaller Flex SWF Files

* Components and SDK Enhancements

* Flex 3 Code Enhancements

* Flex 3 New Charting Features

* My Thoughts on Flex 3 Features - Part 1

* My Thoughts on Flex 3 Features - Part 2

What Makes a Good Technical Book?

One of the abstracts for 2008 JavaOne Conference that looks intriguing is the Birds of a Feather session "Writing the Next Great Java™ Technology Book" (BOF-6588). Most of us have our own list of favorite books and our own reasons for why we prefer certain books (the subject of this blog entry), but this BOF sounds interesting because the two facilitators of the BOF (Joshua Bloch and Brian Goetz) are authors of successful Java-related books.

Joshua Bloch wrote Effective Java and Brian Goetz was the lead author of Java Concurrency in Practice (Joshua Bloch was one of several co-authors on this book as well). How do we know these books have been successful? Perhaps the most obvious sign of success (especially to publishers!) is the number of copies sold. This is often related to the number of printings and/or editions of the book. Bookseller web sites such as Amazon.com also list where these books rank in terms of overall book popularity and in narrower categories. For me as a developer and user of these books, however, there are even more important indicators of how "good" a technical book is. One sign of a good technical book are consistently high ratings of the book across reviewers and across sites selling the book. An even better sign, for me, of a good technical book is how many copies I see of it sitting on my colleagues' shelves. I definitely have seen many copies of both Effective Java and Java Concurrency in Practice on the shelves of many of my colleagues and both of these books get consistently high ratings on bookseller web sites.

With the prevalence today of blog entries, online articles, and even freely available online books, it is becoming more important than ever for a software development book to provide some value above and beyond what these freely available resources can provide. If a book doesn't provide much beyond what is available freely on the web, it likely won't sell well and almost certainly won't see many printings or editions. The online resources are especially effective in releasing information quickly, so books have a built-in disadvantage in terms of timeliness of delivery.

I have no idea which specific books will be discussed in this Birds of a Feather session or what traits of good technical books will be discussed. However, I have my own opinions of which books are the "classics among the classics" in modern software development and I similarly have some theories and observations about common traits of these books.

My list of the "classic technical books" (not necessarily Java-specific or even Java-related) would likely be slightly different on any given day I put it together, but as of right now of this day, here is my list, in no particular order.

Expert One-on-One J2EE Design and Development

While this book may be best known for exposing many of the inadequacies of the hyped EJB 1.x and 2.x technologies, for the first public exposure to what would become the Spring framework, and for (along with the follow-up book J2EE Without EJB) leading to significant improvements in the EJB3 (and Java EE 5) specifications, it remains a deep treatise into practical Java EE architectural and design principles. Even now, years later and several specifications later, there are vast amounts of applicable and useful information packed into this book. When I first read this book, I was relieved to see that I was not the only one who had misgivings about EJBs. After reading so many things in this book that articulated my own thoughts and opinions better than I ever could have, I was very open to the author's thoughts on things with which I did not have as much experience. I truly firmed up my opinions and realized many other lessons from reading this book. It is, I think, a must-read for all Java EE developers even today.

Effective Java

This is another "must-read" book for Java developers. While a few things are now not as applicable as they used to be (such as Item 21 on enums), most of the book is still as applicable today as it was when it first came out. In fact, even some of the most basic items (such as always overriding toString(), still get neglected more often than they should and I think we all benefit from reading and re-reading this book. I like to flip this book open randomly to an item or two now and then just to refresh my knowledge.

Effective C++ and More Effective C++

With the new edition of Effective C++ now covering 55 items rather than the original 50 covered items, these two books now cover 90 items for effective C++ design and coding. For the first time in my career, I'm actually not using C++ currently, but these books were tremendous aids for my many years of C++ development.

Patterns of Enterprise Application Architecture

The PofEAA book contains two main parts and I spend the majority of my time in the first (and shorter) part (called Part I: The Narratives). This section of roughly 100 pages provides an excellent overview of architecture considerations in enterprise applications. The remainder of the book (Part II: The Patterns) focuses on specific enterprise patterns and I do use it for a reference on certain patterns at times, but I find the overview and conceptual coverage to be widely useful in my daily development efforts.

Design Patterns: Elements of Reusable Object-Oriented Software

Although there are now numerous books on design patterns (including books specifically on Java and design patterns such as Core J2EE Patterns, the Design Patterns Java Companion, and Holub on Patterns), the Gang of Four Design Patterns book is still THE design pattern book. I cannot think of a single book that is more widely owned by my colleagues than this one. Nearly 100 percent of the C++ and Java developers I know own this book.

When I first read the Design Patterns book, I thought it was terrible. Sadly, I did not revisit the book again for several years. However, when I did read it again, I was amazed at how insightful this book had become. This book is worth owning or borrowing from the library or borrowing from one of the many colleagues who have a copy for just the first chapter alone. In fact, as I described with the Fowler PofEAA book above, I only refer to the cataloged patterns directly now and then, but I often use the first chapter to illustrate the importance of concepts such as favoring interface inheritance over implementation inheritance and favoring composition over implementation inheritance. The aforementioned Holub on Patterns book has similar (albeit more strongly worded) focus in its first part as well.

The Practice of Programming

Although somewhat dated (publication was in 1999), this book still speaks to many of the frustrations and hard-earned lessons experienced developers have encountered. This book can help experienced developers realize how to avoid the problems again and help new developers hopefully reduce these types of negative experiences. One of the undersold advantages of this book is its relatively short length. There is a lot of experience packaged into a little book.

Code Complete

This book covers a wide gamut of software development as illustrated by its really detailed contents listing.

201 Principles of Software Development

One of the key strengths of this book is its creativity and usefulness in filling a niche. This book covers 201 proven software development principles in very short text sections (usually a paragraph or two) that fit completely on one of the book's small pages. Each topic also includes references to authoritative resources focusing in significantly greater detail on that topic. The association of topics with these authoritative resources is a worthwhile collection in its own right, but the concise textual summarizations of each topic are highly useful. The topics cover everything from general development and design principles to software management principles.

This book and its author reiterated something that I have always believed -- that the software development industry moves in cyclic patterns, repeating periodically the same basic trends of earlier years with new names and technologies. I was fortunate to attend a Denver Java Users Group meeting (October 2006) where the author, Alan M. Davis, spoke. It was an excellent presentation where he explicitly tied some of the "newest" and "trendiest" ideas in software development to suspiciously similar concepts and ideas that were popular several years or even decades ago.

The Mythical Man-Month

One of the most quoted books in the software development industry (in its literature and among its artisans), this book really focuses on how management and mismanagement of software projects contributes to the success or failure of a software project as much as the technical capabilities of its developers. Although this book is somewhat dated by technology standards, it is still true and still on the mark. The programming languages and concepts have changed, but the general manager-developer impedance mismatch still exists.




So What Makes These Books Classics?

The books I listed above share many characteristics that seem typical of software development books that become classics. Here is my list of current thoughts on what makes these and select other books rise above the rest.

Authoritative Nature

One reason I might purchase a book on a subject that is covered already by online resources is because of credential of the author or the authoritative nature of the book and/or author. For example, an attractive feature of the book Pro EJB3: Java Persistence API was that its lead author, Mike Keith, was a co-lead of the EJB3 (including JPA) JSR-220 specification. It turns out that I really like this book and I believe that much of its value comes from the expertise of the two authors. Other examples of this include Ruby on Rails creator David Heinemeier Hansson being a co-author of the tremendously successful Agile Web Development with Ruby on Rails book (along with Dave Thomas and others).

All of the books I have listed above as "classics" are associated with authors who are arguably authoritative. Even when their formal credentials may have lacked when they wrote the book, the writing speaks for itself and in many ways establishes their informal authority.

Readability and Detail Abstraction

While many of us want our technological books to be authoritative as described above, we don't want the language or concepts to be at a specification or too technical level, especially in introductory books and chapters. After all, the reason most of us do buy books instead of accessing online resources such as standards specifications and early blog entries is that we want a uniform, consistent, abstracted treatment of the technology or concept. We also want it presented in a perhaps more introductory way for new technologies or we want new insights, lessons learned, and best practices for more mature technologies.

An example of this is the book Learning Perl. I'm not a fan of Perl, but I think the first chapter of this book is one of the most useful chapters written in any technology book. Because I only use Perl when I absolutely must, I don't use it much and don't know it well. However, I can usually get 50% to 75% of what I need to do each time I return to Perl from this first chapter alone. The first chapter gently leads the reader through some basic concepts while teaching some of the most frequently used features and syntax along the way.

Most of the "classic" books I highlighted above bring clarity or abstraction to more difficult design and development concepts.

The Subject Matters

The subject matter of the book does influence the potential of a book to be a classic. No matter how well written the book is or how qualified or authoritative the author is, a book can only become a classic if it is able to influence numerous developers. With this in mind, it is no surprise that the books in my list of "classics" are associated with long-term (and widely used) programming languages like C++ and Java or are so general in nature that they can span different programming languages. No matter how "good" (a very subjective measure) the programming language, if few people use it, it is very difficult for a book focused on that language to ever be popular enough to become a classic.

Because programming languages do come and go, the books that are largely language-independent have the best chance to be true software development classics. Books with a programming language focus can still be classics in that language's community, but really need a language with a long life to be considered classics.

Beyond 'Hello World'

With the ready and timely availability of information on new languages and development concepts, it is increasingly difficult for a mediocre book to add much value even for new languages and concepts. In general, it is difficult for a general technical book to do well solely because it's first to market. There are some examples of books whose quality and introductory content have made them hugely successful (such as the Core Java series, the Java in a Nutshell series, and the Java Cookbook), but it is more difficult for books like these to become classics because there are so many introductory and basic books in these popular areas. This is where books like Java Concurrency in Practice can shine. Books such as these are more specialized and in-depth.

As an author of several online articles and blog entries, I feel somewhat qualified to point out that many online resources (including mine) tend to focus on basics and introductory material. There is nothing wrong with this and resources like this are needed, but this also leads to an opening for more focused and detailed books to thrive. It is far more difficult to write a good focused and detailed book or article than it is to write an introductory book or article, but the value from the effort for the reader is huge.

IN SUMMARY

I want to finish this lengthy blog entry with one final example differentiating a good book from a classic book. I really like the Programming Flex 2 book, but I would not call it a classic (yet). While it is a great introduction to Flex, its ability to ever be considered a classic depends largely on the future of Flex. Being language-specific is an automatic disadvantage in terms of a book being considered a classic ten years from now and almost certainly a Flex 2 book cannot be a classic a decade from now. That being said, variations of this book for future versions of Flex could be collectively considered classic if Flex gains in developer popularity.

I like this example because it shows that a great book will not necessarily become a classic technical book. Another perspective on that idea is that a "good technical book" does not have to be a "classic" and can still be a simply "good technical book." There are many more "good technical books" than "classic technical books." The example also illustrates how the most likely books to be considered "classics" more than ten years from now are those that are not tied to a specific programming language. Other books that fit the "good technical book" (but perhaps not yet classic) category for me include Agile Web Development with Ruby on Rails, Spring in Action, JMX in Action, Effective XML, Java Threads, and Pro EJB3: Java Persistence API.

This all makes me wonder about my own list of "classics" shown above. Will I still have books like Effective C++, Effective Java, and J2EE Design and Development on that list in ten years? I almost certainly will still have 201 Principles of Software Development and the Mythical Man-Month on that list in ten years because the covered principles in those books aren't likely to change much even in ten years. However, I'm not as certain that the language-specific books on my list of classics will be as influential then.




By the way, another potentially interesting presentation that caught my attention is "JavaScript™ Programming Language: The Language Everybody Loves to Hate" (TS-4986). I loathe JavaScript, but it is a necessary evil for much of the web development community. One of the things I have most enjoyed about using OpenLaszlo and Flex lately is leaving browser-dependent JavaScript behind (Flex uses ActionScript and OpenLaszlo uses its own browser-independent JavaScript subset).

Thursday, April 24, 2008

Negative Zero and Java

The Wikipedia article on negative zero explains that negative zero is a computing-oriented concept rather than a mathematical concept. Because Java treats (positive) zero the same as negative zero in terms of equality comparisons, this concept of a negative zero and a positive zero is often not a problem.

The simple Java code below provides some tests of the negative and positive zero and their relationships in Java to one another.


public class NegativeZeroExample
{
public static void main(final String[] arguments)
{
final String negativeZeroString = "-0";
final String positiveZeroString = "+0";
final String zeroString = "0";

final double negativeZeroDouble = Double.parseDouble(negativeZeroString);
final double positiveZeroDouble = Double.parseDouble(positiveZeroString);
final double zeroDouble = Double.parseDouble(zeroString);

System.out.println("Zero : " + zeroDouble);
System.out.println("Positive Zero: " + positiveZeroDouble);
System.out.println("Negative Zero: " + negativeZeroDouble);

System.out.println("\nMath FUNCTIONS");
System.out.println( "Min(Zero, Negative Zero): "
+ Math.min(zeroDouble, negativeZeroDouble) );
System.out.println( "Min(Negative Zero,Positive Zero): "
+ Math.min(negativeZeroDouble, positiveZeroDouble) );
System.out.println( "Min(Zero,Positive Zero): "
+ Math.min(zeroDouble, positiveZeroDouble) + "\n" );

System.out.println( "Max(Zero, Negative Zero): "
+ Math.max(zeroDouble, negativeZeroDouble) );
System.out.println( "Max(Negative Zero,Positive Zero): "
+ Math.max(negativeZeroDouble, positiveZeroDouble) );
System.out.println( "Max(Zero,Positive Zero): "
+ Math.max(zeroDouble, positiveZeroDouble) + "\n" );

if ( positiveZeroDouble == negativeZeroDouble )
{
System.out.println("-0 is the same thing as +0\n");
}
else
{
System.out.println("-0 is NOT the same thing as +0\n");
}

if ( positiveZeroDouble > negativeZeroDouble )
{
System.out.println("+0 is greater than -0\n");
}
else if ( positiveZeroDouble < negativeZeroDouble )
{
System.out.println("+0 is less than -0\n");
}
else
{
System.out.println("+0 is neither less than nor greater than -0");
}
}
}


When the simple code above is compiled and run as shown in the following screen snapshot (click on it to see larger version), we see how Java treats (positive) zero and negative zero values. The equality operator (==) and the inequality operators (< and >) treat negative zero and (positive) zero exactly the same. However, the Math.min and Math.max functions treat (positive) zero and negative zero differently. While not shown in this code, StrictMath.min and StrictMath.max functions also treat (positive) zero as different than negative zero.



A highly useful tool for understanding the concept of negative zero and general issues surrounding the IEEE 754 floating point format is the web page and Java applet titled Inner Float: A Float Reveals Its Inner Nature. A much deeper treatise on floating point arithmetic is David Goldberg's What Every Computer Scientist Should Know About Floating Point Arithmetic.

Wednesday, April 23, 2008

Favorite Programming Languages

Over the last several months, I have been interested in passively watching the Tiobe Programming Community Index. While Java holds onto its #1 position consistently and other languages such as C# (steady rise), C, C++ (starting decline), Perl, Visual Basic, and PHP have consistently been ranked high, it has been interesting to watch the small bursts of enthusiasm for a wide variety of different languages. In particular, it has been interesting to watch the rise in popularity of Ruby (27th to 9th in ~3 years) and ActionScript (last rank was #23). I really like Java, Ruby, and ActionScript and apparently so do a lot of other people (at least there are a lot of searches online for terms related to these languages).

I was particularly interested in the Paul Jansen article Programming Languages: Everyone Has a Favorite One that appeared in the May 2008 edition of Dr. Dobb's Journal. He summarized some of the same trends I was seeing in this index of programming language popularity based on search engine searches. In particular, I have witnessed similar trends among colleagues related to programming languages he specifically mentions in the article such as C#, Java, Perl, and ActionScript. I also agree largely with his assessment about the Next Big Language (NBL).

The Tiobe web site with this index is at www.tiobe.com.

Tuesday, April 22, 2008

Oracle Open Sourcing XQilla XQuery Engine

About a month ago, Justin Kestelyn (Oracle Technology Network) posted a link to a press release announcing Oracle's release of the XQilla XQuery Engine under an Apache License. I have blogged several times regarding XQuery (and especially about Oracle XQuery implementations) and am excited about an open source XQuery engine being available.

Oracle's FOSS (Free and Open Source Software) page already has a link to another Oracle web page focusing on the XQilla XQuery Engine. This has been one of several recent moves by Oracle to actively participate in the open source implementation of standards movement. Other relatively recent moves in this space have included ADF Faces, the JPA 1.0 reference implementation TopLink Essentials, the open sourcing of the full-fledged TopLink product, and proposal for and support of the JPA 2.0 reference implementation EclipseLink.

The following are other links to articles and blogs on the open sourcing of XQilla.

* Oracle Open Sources XQuilla XQuery (note spelling error that I keep wanting to make as well when I type it -- the "u")

* Oracle Announces XQilla

* Oracle's XQilla Open-Source Contribution and the Art of PR

Monday, April 21, 2008

A First Look at BlazeDS: RPC Mechanisms

Many of us were excited to hear about Adobe's releasing of BlazeDS in late 2007. However, there seemed to be a relative lack of documentation on how to use BlazeDS as compared to other Flex approaches. However, since that announcement, there have been several good resources explaining BlazeDS. These include Andrew Powell's blog entry BlazeDS in Plain English, Wade Arnold's blog entry BlazeDS: Worth Figuring Out! Hello World Example, Christophe Coenraets's article BlazeDS 30-Minute Test Drive, BlazeDS Developer's Guide, BlazeDS Public APIs, BlazeDS Features list, BlazeDS: Remoting != Messaging and the BlazeDS and LCDS Feature Difference table.

HTTPService: With and Without BlazeDS

BlazeDS supports HTTPService. This can be a little confusing at first because HTTPService has been available in the free Flex SDK since Flex 2 and before BlazeDS was made available. In fact, it is the same HTTPService in both cases. Without BlazeDS, a Flex developer is limited to using HTTPService with its useProxy attribute set to false and the connection is made directly to the HTTP service specified by the url attribute.

So, why is it useful to be able to set HTTPService.useProxy=true to take advantage of BlazeDS's proxy server support for HTTPService? The advantage is that BlazeDS's support for the Flex proxy server allows for use of HTTP methods other than POST and GET (including DELETE and TRACE). This is more REST-friendly and is described in the Flex 3 Language Reference documentation for HTTPService.

Another advantage of using BlazeDS in conjunction with HTTPService is that doing so removes the need to use a crossdomain.xml file when accessing a remote server from a Flex application. Besides removing the need for a crossdomain.xml file, the use of BlazeDS server proxy also enables more granular control over access of a server-side service. This means that useful additions like service authentication and service access logging can be performed.

WebService: With and Without BlazeDS

Like HTTPService, the Flex WebService is supported both with and without BlazeDS. The differences between using WebService without BlazeDS as compared to with BlazeDS are similar to those for HTTPService. Instead of the url attribute (used by HTTPService), a WebService used without BlazeDS will use the value of the wsdl attribute as the location of the server-side SOAP-based web service to invoke and, as with HTTPService, the useProxy attribute must be set to false when BlazeDS (or other Flex server implementation) is not used.

As with HTTPService, there are advantages to using WebService in conjunction with a BlazeDS-provided Flex server. These advantages are strikingly similar to those for HTTPService with BlazeDS: no need for a crossdomain.xml when remotely accessing a web service on a remote machine and greater ability to log access or perform authentication checks on potential web service access.

RemoteObject: Only Available with BlazeDS

The previously mentioned two RPC approaches (HTTPService and WebService) can be used with or without BlazeDS. BlazeDS supports a third RPC mechanism, RemoteObject, that is not available in standard Flex without BlazeDS (or other Flex server proxy product).

Besides being only available with BlazeDS, another difference with RemoteObject (as compared to HTTPService and WebService) is the encoding used with RemoteObject. While HTTPService and WebService both make use of XML/text over HTTP, RemoteObject uses Action Message Format (AMF) encoding. Also, RemoteObject allows Flex developers to write ActionScript code as if they were accessing server-side Java classes directly rather than handling XML as is often the case with HTTPService and WebService.

The three RPC mechanisms supported by BlazeDS are highly useful and each has its own advantages. I hope to devote some future blog entries to more in-depth details on each of these three RPC mechanisms and to demonstrate them with code examples. I also plan to include future blog entries on the Flex-to-server communication support offered by BlazeDS outside of the RPC mechanisms (Messaging mechanisms).

Thursday, April 17, 2008

Flex and OpenLaszlo in NetBeans 6.1 Beta

As I blogged in NetBeans 6.1: A JavaScript IDE, the NetBeans 6.1 beta IDE has added tremendous support for JavaScript. This latest release of NetBeans also has added built-in support for the Spring Framework. While this newly added support for JavaScript and Spring is very helpful to me in my daily work, I'd also like to see support added for Flex and for OpenLaszlo. In this blog entry, I demonstrate how easy it is to associate Flex's MXML files (by extension .mxml) and OpenLaszlo's LZX files (by extension .lzx files) with XML so that at least XML color coding and XML checks can be used with these files.

Before demonstrating how simple it is to associate LZX and MXML files with XML in NetBeans 6.1 beta, it is worth noting that OpenLaszlo uses its own JavaScript subset for scripting. With NetBeans's excellent new JavaScript support, external JavaScript files (.js) accessed from LZX files can take advantage of some of NetBeans's JavaScript features. Flex ActionScript cannot enjoy the JavaScript additions as much because ActionScript has significant changes and improvements from more traditional JavaScript even though they are both ECMAScript implementations.

The next two images show how a Flex MXML file and an OpenLaszlo LZX file appear in NetBeans without any association of these files types with XML. Click on the images in this entry to see larger versions of the images.

MXML Source Code in NetBeans without Color Syntax Support



LZX Source Code in NetBeans without Color Syntax Support



To enable color coding for LZX and MXML files, one can use the main Tools drop-down menu in NetBeans, select Options, click on the Advanced Options button, expand IDE Configuration, expand System, expand Object Types, and select XML Objects. At this point, one can then click on the small button on the right (and to the right of the label Extensions and MIME Types) with three periods (...) to expand the list of file extensions and MIME types associated with XML objects.

The next two screen snapshots indicate how LZX and MXML files can be associated in NetBeans as XML files. Specifically, by adding mxml and lzx file extensions, NetBeans treats files with these extensions as XML, enabling color syntax and well-formed XML checking.

Associating MXML with XML via mxml Extension



Associating LZX with XML via lzx Extension



With the .lzx extension and the .mxml extension associated in NetBeans as XML, it is time to see how the sample code in both XML grammars now appears. The next two screen snapshots show the MXML and LZX source code shown above, but now with color syntax thanks to NetBeans recognizing these as XML format.

MXML with XML Color Coding Syntax in NetBeans



LZX with XML Color Coding Syntax in NetBeans



Associating LZX and MXML with XML in NetBeans also enables XML checking for well-formed XML documents to be performed on these files.

Enabling color syntax and XML checking for Flex MXML and OpenLaszlo LZX files is easy with NetBeans 6.1 beta. However, it would be nice in a future version of NetBeans to have more comprehensive support for Flex and for OpenLaszlo development.

Speaking (or writing) of NetBeans 6.1 beta, the NetBeans IDE 6.1 Beta Blogging Contest ends on Friday, April 19, 2008 (tomorrow or today depending on where you live). I intend to submit this blog entry for consideration in that contest because it covers features of NetBeans and expresses a desire of mine for additional NetBeans support of Flex and OpenLaszlo.

Tuesday, April 15, 2008

More on Flex + Java Popularity

In the blog entry The Popularity of Java + Flex, I talked about some signs of the increasing popularity of using Flex with Java EE back-ends. In this blog entry, I will build upon that entry and cover additional examples that, in my mind, demonstrate the increasing popularity of Flex as the client-side technology for enterprise applications with Java EE on the back-end. I want to emphasize that I really like Java SE and Java EE. However, I have found that the easiest way for me to deliver rich front-ends in a web browser backed by enterprise-strength software is with the coupling of Flex and Java EE.

One interesting development is the recent job change of Filthy Rich Clients author Chet Haase, a well-known advocate and significant contributor to Java Swing. Chet Haase left Sun to work at Adobe on Flex and Flex-related products. I do not think this necessarily indicates doom and gloom for Swing's future. Instead, it indicates optimism and potential for Flex as a client-side framework and library.

Speaking of Chet Haase and Adobe, the two authors of Filthy Rich Clients will be speaking at 2008 JavaOne Conference on "Filthy-Rich Clients: Filthier, Richer, Clientier" (TS-6611). Other presentations with Adobe speakers at JavaOne 2008 Conference include "Service-Oriented Architecture and Java™ Technology: Level-Setting Standards, Architecture, and Code" (TS-6887) and "LiveCycle ES: Adobe’s Java™ 2 Platform, Enterprise Edition (J2EE Platform) SOA Platform" (TS-4841). Other Flex-related presentations at 2008 JavaOne Conference include Tony Constantinides's "Rich Internet Applications with Adobe Flex and Java™ Technology" (TS-5389) and Stephan Janssen's Birds of a Feather session "Parleys.com: An Adobe Flex/AIR and JavaFX™ Case Study" (BOF-4798). Finally, "So Many Faces: Web 2.0 XD Experience with JavaServer™ Faces and JavaFX™ Technology, Flex, and Windows Presentation Foundation" (TS-5349) covers building web applications with Flex and three other presentation technologies.

Adobe is certainly making an effort to support languages other than ActionScript and Flex. Flex includes many general communications mechanisms that work with Java and other back-end technologies as well as some communications mechanisms that are Java-specific. Also, a recent article states that Adobe has a research project looking into making other languages such as Ruby, Java, and C++ run on the Flash Player.

I don't see Flex as a "Java killer." In fact, I think the use of Flex for client side coupled with JEE for the server-side makes Java-based enterprise applications easier to develop, more beneficial to users, and more pleasing to users than ever before.

Sunday, April 13, 2008

The Popularity of Java + Flex

In a previous blog post, I mentioned that I am hearing increasing discussion from colleagues and other Java (SE and EE) developers regarding use of Flex for the public-facing portion of their Java-based applications. Many of them are discovering what I have discovered and what Bruce Eckel discovered and wrote about in Hybridizing Java -- Flex as the front-end technology and Java EE as the back-end technology makes an impressive combination of technologies that benefit the developer and the end user.

As I mentioned in that same blog entry, there still seems to be a lot of resistance against Flex (or more specifically against Flash) that prevents many Java developers from even considering use of Flex or learning more about it. That's a shame and it's their loss because there many are situations where Flex and Java EE are the perfect complements of one another. In this blog entry, I'll demonstrate why I believe that Flex is becoming more popular in the Java development community.

Vendors Associated with Java Supporting Flex

Whether customers drive vendors or vendors drive customers, the result is the same -- vendor support for a tool or technology generally drives use of that technology or tool, but it can also be a sign of increasing customer use of that technology or tool. Some of the biggest vendor names in the Java community (particularly the Java EE application server community) have already shown significant interest in Flex.

Oracle Corporation and BEA have shown particular interest in Flex as shown in the following links. Oracle uses Flex in its Metalink tool and in its BI Publisher. BEA has started supporting a Flex plugin for its BEA Workshop Studio IDE.

Oracle Adopts Flex

James Ward's 7-Part "Oracle Chooses Flex"

What's With Oracle and Flex?

Using BEA Workshop Studio and Java to Create Flex-based RIAs

Flex Messaging with BEA Workshop Studio

BEA, Adobe Flex Their Muscles in Pushing Toward RIAs on the Enterprise Desktop

IBM DeveloperWorks: Develop Web Services Clients with Macromedia Flex


Flex Hangs with the Cool Crowd

Another sign of the rapidly growing interest in Flex for Java and other software developers is the set of popular toolkits and frameworks that people are using Flex with. For example, I spoke with some individuals at RMOUG Training Days 2008 who are using Flex with Ruby on Rails. They are not alone. Also, I know of people who are using Flex with the Spring Framework. Ruby on Rails and Spring are two of the "coolest kids" right now and Flex is hanging out with them. Links related to these combinations are shown next.

Flex for Ruby Developers

Book on Flex and Rails: Flexible Rails

Using Flex with Spring


Flex + Java Blogs, Articles, and Books

The increasing number of blogs (including mine!) and articles on using Flex with Java provide more evidence of the increased use of Flex and Java. There is even a book (Rich Internet Applications with Adobe Flex & Java) on using Flex with Java. Adobe's Developer Center has a section Flex and Java devoted to articles and other information on using Flex with Java. James Ward and Yakov Fain have written extensively about Java and Flex. The article Integrating Macromedia Flex with Java was published in late 2004 when it was still Macromedia Flex (rather than Adobe Flex) and it was J2EE rather than Java EE. However, while this was covered back then, the open sourcing of Flex, the availability of the Flex SDK for no license fee, and Eckel's account have led to increased interest in using Flex with Java EE.


The Jury is Still Out

The blog entry 1 in every 10 Java Developer is Learning Flex? is interesting (especially the feedback comments). While my anecdotal experience is that nowhere near one in ten of the Java developers I know is currently learning Flex, it would not surprise me if that comes to pass in the near future. What I find even more interesting is that of my close associates who are Java developers and who have spent any significant time trying Flex out, 100% of them have come away impressed. In fact, two of them (Michael Martin and Bill Jackson) are the co-authors of the presentation (Add Some Flash to Your Oracle DB Applications: Flex and OpenLaszlo) that I will be giving as part of the IOUG Forum at Collaborate08.

Friday, April 11, 2008

Properties in Spring: PropertyPlaceholderConfigurer and PropertyOverrideConfigurer

The Spring Framework's PropertyPlaceholderConfigurer and PropertyOverrideConfigurer make using Java .properties files with Spring easy. In this blog entry, I'll use a simple example to demonstrate these two classes that enable configuration of Spring via .properties files.

The first code listing is a simple Java class that will be exposed by Spring and will have its attributes set based on Java properties files.


package dustin;

/**
* Simple Java class that will be exposed as a Spring bean and configured via
* properties files.
*/
public class SpringPropertiesHandlingExample implements SpringPropertiesHandlingIf
{
private String valueFromConfigurer;
private String valueFromOverrider;

public SpringPropertiesHandlingExample()
{
}

public String getValueFromConfigurer()
{
return this.valueFromConfigurer;
}

public void setValueFromConfigurer(final String valueFromConfigurer)
{
this.valueFromConfigurer = valueFromConfigurer;
}

public String getValueFromOverrider()
{
return this.valueFromOverrider;
}

public void setValueFromOverrider(final String valueFromOverrider)
{
this.valueFromOverrider = valueFromOverrider;
}
}


The interface for the above class is simple and shown next.


package dustin;

/**
* Interface for simple Java class configured in Spring via properties files.
*/
public interface SpringPropertiesHandlingIf
{
String getValueFromConfigurer();

String getValueFromOverrider();

void setValueFromConfigurer(final String valueFromConfigurer);

void setValueFromOverrider(final String valueFromOverrider);
}


The next code listing is the executable Java class that bootstraps the Spring container used in this example.


package dustin;

import org.springframework.context.ConfigurableApplicationContext;
import org.springframework.context.support.ClassPathXmlApplicationContext;

/**
* Main executable starting Spring Container.
*/
public class SpringPropertiesMain
{
/**
* Main executable starting Spring Container.
*
* @param arguments Command-line arguments; none anticipated.
*/
public static void main(final String arguments[])
{
final ConfigurableApplicationContext context =
new ClassPathXmlApplicationContext("/spring-properties-example.xml");
final SpringPropertiesHandlingIf propertiesExample =
(SpringPropertiesHandlingExample)
context.getBean("SpringPropertiesHandlingBean");
System.err.println( "Configurer Value: "
+ propertiesExample.getValueFromConfigurer());
System.err.println( "Overrider Value: "
+ propertiesExample.getValueFromOverrider());
}
}


This simple main class instantiates the Spring container. It then displays its attributes as set in the XML configuration file (called spring-properties-example.xml and shown next).


<?xml version="1.0" encoding="UTF-8"?>
<beans xmlns="http://www.springframework.org/schema/beans"
xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xmlns:p="http://www.springframework.org/schema/p"
xmlns:util="http://www.springframework.org/schema/util"
xsi:schemaLocation="http://www.springframework.org/schema/beans http://www.springframework.org/schema/beans/spring-beans-2.5.xsd
http://www.springframework.org/schema/util http://www.springframework.org/schema/util/spring-util-2.5.xsd">

<bean class="org.springframework.beans.factory.config.PropertyPlaceholderConfigurer"
p:locations="classpath:/spring-properties-configure.properties" />

<bean class="org.springframework.beans.factory.config.PropertyOverrideConfigurer"
p:locations="classpath:/spring-properties-override.properties" />

<bean id="SpringPropertiesHandlingBean"
class="dustin.SpringPropertiesHandlingExample"
p:valueFromConfigurer="${value.configurer}"
p:valueFromOverrider="yadayadayada" />
</beans>


In the Spring XML configuration shown above, the highlighted portion contains use of the PropertyPlaceholderConfigurer and the PropertyOverrideConfigurer.

The Spring XML above points at two properties files. They are simple in this example and are shown next.

spring-properties-configure.properties

value.configurer=Hello, World!
value.overrider=Hello, Spring!


spring-properties-override.properties

SpringPropertiesHandlingBean.valueFromOverrider=Overridden!


The first properties file is used to set the two values of the simple Java class and the second properties files overrides the value of the second of the two values of that Java class.

The output from running this looks like this:


Configurer Value: Hello, World!
Overrider Value: Overridden!


If I comment out the single line in the spring-properties-override.properties file so that it doesn't do any overriding, the output from running this now looks like this:


Configurer Value: Hello, World!
Overrider Value: yadayadayada


These two pieces of output show that the PropertyPlaceholderConfigurer configures the values in the Spring application based on properties files and the PropertyOverrideConfigurer allows these values to be overridden. Of course, you could override hard-coded values in the XML as well, but I thought it was interesting to see both the original values set with PropertyPlaceholderConfigurer and then see them overridden with PropertyOverrideConfigurer.

Thursday, April 10, 2008

Resistance to Using Flex

I am starting to hear Java developers other than the well-known Flex/Java developers (Bruce Eckel, James Ward, and Yakov Fain) and lesser known Flex/Java peers (Bill Jackson and Michael Martin) talk about using Flex in enterprise Java applications. It seems that at least weekly I hear directly or indirectly of a Java developer being pleasantly surprised by what Flex offers.

While many Java developers seem to be investigating and adopting Flex, there still is a large contingency that cringes at the thought of Flash. I think that some of them let previous abuse of Flash in web sites keep them from seeing the virtues and values of Flex. It is easy to forget that just because a technology can be misused or abused, this does not necessarily mean that it cannot be effectively applied as well. There are plenty of examples of bad things that can be done with any programming language. The key for me is what can I do for my customers with a particular language. I have found that I can create richer web experiences more easily with Flex than with any other framework that I have tried.

Besides negative user perception of Flash from previous slides that misused or abused Flash (which we don't have to fall into when using Flex), what are the other reasons that some Java developers resist use of Flex for rich web applications? The general reasons seem include fear that Adobe will treat Flex like it treated SVG; concern about using "proprietary" Flex versus standardized web technologies like HTML, CSS, DOM, JavaScript, and XML; inability to use the Back button, bookmarks, and other browser capabilities; problems being adequately covered by search engines; and cost. In the remainder of this blog entry, I'll attempt to demonstrate that these concerns are overstated or, at least to me, seem manageable now.

While it does appear to many of us as if Adobe has abandoned or at least changed course dramatically in relation to Scalable Vector Graphics (SVG), I think their support of Flex may be a different story. There are several differences including the seemingly greater support for Rich Internet Applications (RIAs) in general than SVG enjoyed, including wider community and wider availability of books and literature.

Very few web developers have the stomach to use the underlying Ajax technologies of CSS, HTML, DOM, JavaScript, and XML directly and without use of a third-party library or framework. Even when these third-party libraries are open source and freely available, they still require our code to meet certain API expectations. Now that Flex 3 SDK is open source and freely available, it is increasingly difficult to see how using of third-party Ajax framework is much "safer" than using Flex. The other thing I don't think Java developers realize is that Flex is based on standards as well. Flex code consists of an XML grammar (MXML) with an implementation of ECMAScript (ActionScript 3.0). I personally find the ActionScript 3.0 implementation of ECMAScript to be much nicer to use than JavaScript implementations of older versions of ECMAScript.

Some people worry that developers will need to learn "whole new languages," but my experience was that my previous experience with JavaScript and XML made learning and applying ActionScript and MXML easy. My Java experience was valuable in easily migrating to Flex as well because Flex adopted many Java-isms like asdoc (think Javadoc for ActionScript), many syntactical similarities, and Java-like class-based object-oriented features.

For my primary uses of Flex, the limitations surrounding use of browser features like the Back Button, bookmarks, and so forth have not proven significant in most cases. The whole idea behind an RIA seems to move the user away from these types of approaches anyway and some of them can be simulated. It is also worth mentioning that many Ajax solutions can suffer these same limitations.

The problem of having a Flex-based Flash application being listed by search engines can be an issue for sites that depend on search engine traffic. As discussed in How to SEO Flash, there are ways to address this to some degree.

As stated above, the Flex 3 SDK is freely available, so previous complaints about the cost of Flex aren't really stated as much now.

Adobe has apparently invested significant resources into making Flex appealing to Java developers. Evidence of this include the Adobe Developer Center focus on Flex and Java and the fact that Adobe has made BlazeDS available, allowing for Java-specific client-server communication mechanisms. Prior to BlazeDS, Java developers could use the free Flex SDK to communicate from the browser to server-side Java via HTTP (servlets when in Java on the server-side) or via web services. However, these approaches could be used with non-Java server-side technologies as well. BlazeDS offers more freely available communication mechanisms including faster-performing Java-specific mechanisms.

If one needs more evidence of the powerful combination of Flex with Java EE, one need only look at Microsoft's interest in Silverlight and Sun's interest in JavaFX to see that these two companies also see the value.

Wednesday, April 9, 2008

Removing an Entry from a Java Map During Iteration

I am a big fan of the enhanced Java for-each loop that has been available since J2SE 5. The vast majority of the iterations I need to do over collections fit the appropriate uses of this enhanced for loop and it has become a habit to use it now for all Collections iterating.

If I ever forget that there are cases where the enhanced for loop does not apply, I am quickly reminded when I use it in such cases. The three cases in which the enhanced for loop is not allowable are in iterating over parallel collections, in trying to change values in the collection as you iterate, and in removing elements from the collection you are iterating. The last usage is the subject of this blog entry.

The Collections Framework documentation makes it very clear that items can only be safely removed from an iterated collection via the Iterator's remove method. Because the enhanced for loop hides the Iterator (making the code so much cleaner and more concise), removal is not an option with this loop style.

The following code snippet demonstrates how to safely remove an element from a Java Map and also demonstrates how NOT to do this with commented out code that leads to different exceptions (ConcurrentModificationException and IllegalStateException).


import java.util.Iterator;
import java.util.HashMap;
import java.util.Map;

public class LoopingFun
{
private static Map<String, String> translatorMap = new HashMap<String,String>();

static
{
translatorMap.put("zero", "cero");
translatorMap.put("one", "uno");
translatorMap.put("two", "dos");
translatorMap.put("three", "tres");
translatorMap.put("four", "cuatro");
translatorMap.put("five", "cinco");
translatorMap.put("six", "seis");
translatorMap.put("seven", "siete");
translatorMap.put("eight", "ocho");
translatorMap.put("nine", "nueve");
translatorMap.put("ten", "diez");
}

public static void main(final String[] arguments)
{
System.out.println("Pre-Size: " + translatorMap.size());
for ( final String translatorKey : translatorMap.keySet() )
{
// Line below is commented out to avoid ConcurrentModificationException
// (cannot remove directly on the Map while iterating; must remove from
// the Iterator, but the enhanced for-each loop "hides" the Iterator).
//translatorMap.remove(translatorKey);
}
final Iterator mapIter = translatorMap.keySet().iterator();
while ( mapIter.hasNext() )
{
// Line below is commented out to avoid IllegalStateException (need to
// call Iterator's hasNext() method first.
//mapIter.remove();

// Line below is commented out to avoid ConcurrentModificationException
// (cannot remove directly on the Map while iterating; must remove from
// the Iterator).
//translatorMap.remove((String)mapIter.next());

mapIter.next();
mapIter.remove();
}
System.out.println("Post-Size: " + translatorMap.size());
}
}


When the code exists as shown above (working with problem lines commented out), the results of running the compiled class look like this:



The next three snapshots show what the runtime output looks like when the appropriate code is commented out and the three commented out examples in the code above are each individually uncommented. Note that these are runtime errors rather than compile time errors.

Because the for-each loop hides the Iterator, one might tempted to call the remove method directly on the Map. When this is done, a ConcurrentModificationException occurs as shown in the next screen snapshot. Note that the line cited in the trace is the line of the for loop rather than the line where the remove() is actually called.



If one tries to call a removal in a more traditional explicit Iterator-driven iteration without first calling Iterator.next(), an IllegalStateException is thrown as shown in the next screen snapshot.



Finally, the last "don't do it this way" example shows trying to call remove directly on the Map rather than on the Iterator. Even though this third example of Collection removal abuse is included in a traditional explicit Iterator-driven iteration loop, it still results in a ConcurrentModificationException because only an Iterator (and not the Collection itself) allows a safe removal during iteration. The final screen snapshot indicates this exception, which in this case shows the line of the remove() call in the trace.



The enhanced for-each loop in Java is a sweet piece of syntactic sugar. It can be used for many of the common, everyday Java Collection iteration/looping needs. However, as this blog entry demonstrated, there are times when it is not appropriate and the more traditional and explicit Iterator-driven iteration must be used instead.