Newsletter sign-up
View all newsletters

Enterprise Java Newsletter
Stay up to date on the latest tutorials and Java community news posted on JavaWorld

Sponsored Links

Optimize with a SATA RAID Storage Solution
Range of capacities as low as $1250 per TB. Ideal if you currently rely on servers/disks/JBODs

An API's looks can be deceiving

Penetrate the hidden complexities that spoil simple conceptual models of Java APIs

  • Print
  • Feedback

Page 4 of 4

  1. The methods retrieve the first child element (and not the first node) when performing a lookup. The implementation of the getFirstChildElement() method will skip any intermediate nodes that are not of type ELEMENT_NODE.
  2. The methods eliminate all blank text nodes from the document.


While both solutions will work, the second approach might remove some white space not considered ignorable.

A run of GoodDomLookup.java produces:

C:\classes\com\javaworld\jpitfalls\article4>java 
com.javaworld.jpitfalls.article4.GoodDomLookup myaddresses.xml
Method #1: Skip Ignorable White space...
# of "ADDRESS" elements: 2
This node name is: ADDRESS
This node name is: NAME
Method #2: Normalize document...
# of "ADDRESS" elements: 2
This node name is: ADDRESS
This node name is: NAME


The results show that both approaches succeed in finding the correct NAME element.

Match your model to the implementation

Each pitfall in this article was caused by our hypothetical programmer developing an incorrect conceptual model of how an API operates. I do not believe there is any blame to place here; the pitfall is neither the fault of the programmer nor of the API developer. The reality is that not all APIs can be simple. A Swing GUI has a single-threaded, ordered event model, and the DOM includes ignorable white space in its tree of nodes. The solutions I outlined to the pitfalls merely took those implementation realities into account. Once your conceptual model matches the complexity of the implementation, you can easily avoid these Java traps.

About the author

Michael Daconta is the director of Web and technology services for McDonald Bradley, where he conducts training seminars and develops advanced systems with Java, JavaScript, and XML. Over the past 15 years, Daconta has held every major development position, including chief scientist, technical director, chief developer, team leader, systems analyst, and programmer. He is a Sun-certified Java programmer and coauthor of Java Pitfalls (John Wiley & Sons, 2000), Java 2 and JavaScript for C and C++ Programmers (John Wiley & Sons, 1999), and XML Development with Java 2 (Sams Publishing, 2000). In addition, he is the author of C++ Pointers and Dynamic Memory Management (John Wiley & Sons, 1995).

Read more about Core Java in JavaWorld's Core Java section.

  • Print
  • Feedback

Resources