Language improvements
and models make
great Java - JavaWorld
Tutorial Details:
Language improvements and models make great Java
Language improvements and models make great Java
By: By Eric Armstrong
Java enhancements, like generics and asserts, improve this already cool programming language
June 8, 2001 -- As an object-oriented, network-enabled, platform-spanning language smart enough to include primitive data types for efficiency, Java has always been cool. But it just keeps getting better!
Once you code in a few different languages, you come to realize just how important the language is to solving a given problem. When you're using the right language, some puzzles just fall apart. But as someone who once tutored freshman who were ill-fated enough to take a class that forced them to solve real-world business problems using FORTRAN, I can tell you that the wrong language can turn a molehill of a problem into a nearly insurmountable mountain.
And, for all its beauty, Java experienced a few problems of its own. One of the major gaffes was the inconsistent, persnickety mechanisms for looping over arrays, vectors, and strings. Sun Microsystems Senior Staff Engineer Joshua Bloch came to the rescue on that front with the elegant Collections API. Just as Java itself is platform-spanning, Collections present a mechanism-spanning API, thereby creating uniform, consistent mechanisms for writing code.
The latest language improvements include generics and assertions. In addition, a variety of application templates and design patterns have become available to help you write better code more quickly. This article explores these enhancements:
Generics
Assertions
Effective Java
J2EE Blueprints
Common interface standards
Generics
Gilad Bracha, the specification lead and computational theologist for Sun, announced that the generics facility will arrive in the Tiger release of the Java platform (version 1.5). The bad news is that 1.5 is not due to be available until 2003. The good news is that an early-access version is available now, and you can actually make use of the technology in some practical ways.
It turns out that Merlin's (JDK 1.4) compiler is the generic-capable compiler, only with generics disabled. That means that the generic facility will undoubtedly be stable by the time it arrives. But it also means we'll have to wait a fairly long time for something that is (almost) here today.
( Note: For those familiar with the generics landscape, Bracha mentioned that Java's generics facility is based on Pizza and Generic Java, and that much of the documentation on those precursors (available on the Web) applies to generics.)
The advantages of generics
The ability to write generic classes, methods, and interfaces makes it possible to write general template classes. However, they significantly differ from C++ templates, as you'll see. Such template classes can be reused for multiple purposes without requiring general Object parameters that must be cast to the appropriate data type when the class is used.
For example, writing a generic data pool would make it possible to cache and deliver objects of type "X" to an application. One application could then create a pool of Car objects, while another application could create a pool of network Connection objects. Both applications would use the generic data pool facility. Neither application would have to write a data pool library, but both would be able to access Car objects or Connection objects, as appropriate, as though they had written a custom library.
Prior to generics, the only way to write a generic data pool was to return objects of type Object . But that return value forces the application to cast the object to the real type, with code like this:
Car c = (Car) dataPool.get();
Such casts have two problems. First, they interfere with readability -- especially if you want to invoke a method on the returned object, because you wind up with a mess like this:
Car myCar = ((Car) dataPool.get()).initialize(make, model);
With generics, that code turns into something more readable:
Car myCar = dataPool.get().initialize(make, model);
But the second -- and larger -- issue with casts is that bugs in programs that use them show up as runtime errors. As Gilad said, a cast amounts to a declaration in which "we hope and pray" the variable contains an object of the indicated type at runtime. If it doesn't, the app is hosed.
On the other hand, with generics, the data pool's contents are documented, both for the human reader and the compiler. Because the compiler knows what the pool is supposed to contain, errors are discovered at compile time instead of runtime. That shift speeds application development and improves confidence in the final product.
How generics work
The declaration for a generic class, method, or interface uses angle brackets to indicate the generic part of the declaration:
interface List {
...
}
The above code defines an interface for a generic list class. Typically, single-character names indicate the generic component, but any valid identifier could be used.
Within the declaration, the angle brackets are no longer needed, so the identifier E would refer to the generic data type within the body of the declaration. For example:
interface List {
void add(E x);
...
}
When the generic definition is referenced, the angle-bracket syntax is once again used to indicate the actual data type, like so:
List myList = new LinkedList();
( Note: In 1.5, the Collections API will be fully genericized, so you'll be able to use the code above. On the other hand, the generics facility has been cleverly designed so that it is totally backward compatible. As a result, old code of the form List myList = new LinkedList() will continue to run exactly as it did before. That code will still need to cast the data types, but it will run unchanged against the libraries' generic version.)
The data type named in a usage statement could itself be a generic type too. The declaration for a list of lists, for example, would look like this:
List> myList;
( Note: Type aliases are currently being considered as an extension to the language in order to simplify such declarations. But the expert group is looking for a way of doing so that avoids adding (abusable) C-style typedefs to the language.)
A generic declaration can also name multiple generic types:
interface Function { B value(A arg); }
The declaration above specifies that a class that implements the generic Function interface will include a value() method that takes an argument of type A , and returns an argument of type B .
One important difference between Java generics and C++ templates is that in Java, generic declarations are compiled and type-checked into classes that can be reused directly, instead of expanded into additional classes.
That fact has several important advantages for the Java developer:
If a generic class is used multiple times in an application, only one copy of it exists, rather than one copy for each data type. Consequently, program size is reduced.
When a bug is found and a correction made, there is no need to recreate dependent classes that were expanded from the template -- the fix automatically applies to all uses of the generic class.
Since the generic code is used as a class, rather than expanded from a source code template, the source code does not need to be present to use the generic code. That means third-party library providers can distribute generified components in the same way that they deliver other classes. (And, since a generic class can be used as though it weren't generic at all, a developer who is unfamiliar with generics can use the libraries as they normally would.)
Compilation also reduces application size since the template isn't expanded into a different class each time it is used. Finally, since generics are compiled into classfiles, the source code is not required to use a generic library. And since the compiled classes are totally backward compatible, they can be used with code that employs older code like LinkedList() instead of LinkedList() .
After the presentation, Ed Hansen, a senior application architect for Vision Service Plan and an experienced C++ template developer, had this to say: "It's a great API. And the fact that generic declarations are compiled and type-checked instead of expanded at runtime (like C++ templates) makes debugging a lot easier."
Using generics today
Despite the fact that generics are not yet a standard part of the Java platform, the generics facility can still be used today! You can download and use the generic compiler with the resulting classes running in Java 1.4.
At the moment, the best way to use the generics facility is to create a generic API for your existing library classes. For example, you could add generic declarations to an interface, or you could copy a class, remove the code, and add generics to the resulting stub.
You would then compile the generic stub with the generic compiler and import that stub when you compile the code that uses the library (with the generic compiler, once again). That code remains unchanged -- it still references List , for example, instead of List .
When you compile, you turn on unchecked warnings, which warn you when a cast may not be valid -- a warning you cannot get today in any other way. However, you'll receive many meaningless warnings as well. It remains to be seen how easily you can filter out the warnings you don't care about so you can find the potential bugs in your app.
When you run the program, you run with the original classes -- the nongeneric versions. That way, you use the stable 1.4 versions at runtime, but you will have had the advantage of the additional compile-time error detection.
Since the 1.4 compiler is essentially identical to the generic compiler, you shouldn't have to recompile the code that uses the libraries. The resulting classes should be identical with eit
Read
Tutorial at: Click here to view the tutorial
Rate Tutorial: Language improvements
and models make
great Java - JavaWorld
View Tutorial: Language improvements
and models make
great Java - JavaWorld
Related
Tutorials:
Enhance your Java application with Java Native Interface (JNI)
Enhance your Java application with Java Native Interface (JNI) |
Put Java in the fast lane
Put Java in the fast lane |
Effort on the
edge, Part 1
Effort on the
edge, Part 1 |
Get the inside
track on J2EE architect certification
Get the inside
track on J2EE architect certification |
Call JavaBean methods from JSP
Call JavaBean methods from JSP 2.0 pages |
Quite poor
testing
Quite poor
testing |
Worth
reading
Worth
reading |
Using Java Classes in Windows Batch Files
Using Java Classes in Windows Batch Files - a simple approach for system admin
Although Java is an ideal language for implementing rich GUI applications, it is equally well-suited for the development of small console-based programs that, in turn, are p |
Data Models for Desktop Apps
Data Models for Desktop Apps
This is the third article in a series that presents the prototype of a Java desktop application called JImaging. The first article described the three major Java GUI toolkits: AWT, Swing, and SWT. In the second article, I int |
Sphinx-4 - A speech recognizer
Sphinx-4 - A speech recognizer
General Information about Sphinx-4
Introduction
Sphinx-4 is a state-of-the-art speech recognition system written entirely in the JavaTM programming language. It was created via a joint collaboration between the Sphinx |
Introduction to Jena
Introduction to Jena
Use RDF models in your Java applications with the Jena Semantic Web Framework
RDF is increasingly recognized as an excellent choice for representing and processing semi-structured data. In this article, Web Developer Philip McCart |
YourKit Java Profiler 2.5.2 Released
YourKit Java Profiler 3.2 Released
With help of YourKit Java Profiler, an outstanding tool for Java professionals, you can easily solve wide range of CPU and memory related performance problems in J2EE and J2SE applications.
|
Build scripts with Groovy and Ant
Build scripts with Groovy and Ant
Summary
In nearly all developers' toolboxes, Ant is the standard build tool for Java applications, thanks to its open, standard, and multiplatform structure. Though it represents a great improvement in automating produc |
YourKit Java Profiler 3.2 Released
With help of YourKit Java Profiler, an outstanding tool for Java professionals, you can easily solve wide range of CPU and memory related performance problems in J2EE and J2SE applications. |
Core Java Data Objects Excerpt
This book excerpt is from Core Java Data Objects, |
Five Reasons to Move to the J2SE 5 Platform
Five important reasons to move to the Java 2 Platform, Standard Edition (J2SE platform) 5.0, supported by data and references to prove that the 5.0 release will reduce development and runtime costs. |
Asking "Why" at Sun Laboratories: A Conversation with Director, Glenn Edens
Sun Laboratories Director, Glenn Edens, discusses new research developments in the Java language and the gratifications and trials of running a research lab. |
We are providing Downloadable Version of Mandrake 10.1 Official Edition Linux CD's.
We are providing Downloadable Version of Mandrake 10.1 Official Edition Linux CD's.
Mandrake 10.1 Official Edition Linux
Now Available Mandrake 10.1 Official Edition CD's
Mandrakelinux 10.1 Official is a new-generation Linux operating system for |
We are providing Downloadable Version of Mandrake 10.1 Power Pack Linux CD's.
We are providing Downloadable Version of Mandrake 10.1 Power Pack Linux CD's.
Mandrake 10.1 Power Pack Linux
Now Available Mandrake 10.1 Power Pack CD's
Power Pack is a Linux system that will appeal to all advanced users. It's great for Office |
Accessing Database from servlets through JDBC!
Accessing Database from servlets through JDBC!
Java Servlets
J ava Servlets are server side components that provides a powerful mechanism for developing server side of web application. Earlier CGI was developed to provide server side capabilities |
|
|
|