|
3.5. O, Templates! Where Art Thou?Programmers familiar with C++ may be wondering how in the world an OOP language without templates can be useful. Note Actually, something very much like templates is available in Java 5.0.[14] A new feature, which Sun calls generics, looks an awful lot like C++ templates (including similar syntax). It provides compile-time type checking and implicit casting when retrieving objects from a generic container.
Speaking as programmers who worked with C++ before it had templates, we can sympathize. Java's previous lack of true templates does impose some limits on generic programming, but not as much as one might think. Remember that unlike C++, all Java classes inherit from exactly one base class, and that if no base class is specified, they extend the Object class. This means that every single Java class either directly or indirectly extends Object, and thus all Java classes are instances of Object. So if you need, for example, to implement a container, you can guarantee that it can contain any Java class by implementing a container for the Object type. Java also has runtime type identification features that are more than a match for anything C++ has, plus it has type-safe downcasting[15] so that in the worst case scenario, your program has a nice, clean type exception. You simply do not get the kind of "mystery bugs" that you can get in C++ when you miscast an object.[16]
Thanks to interfaces and a true single object hierarchy, many of the uses of C++ templates go away. We doubt very much that you will miss them. In many cases, such as STL algorithms and other functional programming implementations, you can use interfaces to produce similar results. Critics of the Java language have a point when they complain that all the type casting of class references in order to expose desired interfaces tends to produce code that violates object-oriented principles. The fact that a class or interface implements all these other named interfaces is hard-coded all over the place in an application's code. Such critics say this is a bad thing, because it violates encapsulation and implementation hiding. These critics have a point. If you find yourself frequently downcasting object references, consider using the Java 5.0 generics, or try to find another way to code what you want to do. There may be a better way. In defense of the original Java approach (before generics), all casts are runtime type safe. An exception is thrown if a class reference is improperly cast. In C++, if you miscast a pointer, it assumes you meant it. Java certainly can be awkward, but errors will get caught. Sometimes that is more important. |
|