Slashdot Mirror


Java Gets Templates

lastberserker writes "Call them all you want - generics, parametrized types, thingamagic mumbojumbo - but (tada!) Java gets templates in 1.5 release. Nice landing after 5+ years of dancing around a bush. Competition is good, pardon my pun."

22 of 121 comments (clear)

  1. Operator Overloading? by Wrexen · · Score: 3, Interesting

    Does this mean Java will get operators soon? Back when Java was introduced, lack of templates was called a "feature", just like the lack of operator overloading. Have the designers seen the light?

  2. Re:OMG templates totally rule! by jilles · · Score: 5, Informative

    Sounds like you don't get the point. The reason templates are useful is because it reduces the amount of code you need to write for common situations in a typesafe way. This makes your code more compact (duplicate code) and less error-prone (it's all type safe and you only write it once).

    BTW. generics are old news. The prototype compiler and the proposal have been available for at least a year. On the javalobby there's a link to some additional language extensions: http://www.javalobby.org/thread.jsp?forum=61&threa d=6009 (lets hope /. gets this right). Lets hope all these goodies end up in 1.5.

    --

    Jilles
  3. Re:OMG templates totally rule! by Wrexen · · Score: 3, Informative
    Templates are useful for tons of things other than generic containers. Consider something like this in C++
    template <class T> T Max(T x,T y) {
    if(x>y)
    return x;
    else
    return y;
    }
    The compiler can determine at compile-time if you're comparing similar types, and error if you're not. Also, it doesn't need to do any run-time type checking to figure out which > to use.

    The Java equivalent would return an Object and take two Objects as parameters. All the type safety you work so hard to preserve is lost, and at run-time you're taking a performance hit every time this is called for a myriad of reasons.
  4. Re:OMG templates totally rule! by lightspawn · · Score: 3, Informative

    The compiler can determine at compile-time if you're comparing similar types, and error if you're not. Also, it doesn't need to do any run-time type checking to figure out which > to use.

    The Java equivalent would return an Object and take two Objects as parameters.


    No, the java equivalent would use an interface, probably called "comparable" or somesuch.

  5. How sad by Tal+Cohen · · Score: 3, Insightful

    Sad to see that the suggested implementation of templates does not include type-specific elements, a-la Eiffel (so, for example, I could declare a SortedList type, where only types that implement Comparable can be used). Java's single-root nature would mean that if you want to accept any type as a parameter, just use Object.

    --
    - Tal Cohen
    1. Re:How sad by Hellkitten · · Score: 3, Informative

      Damn I hate replying to myself

      It seems I may have misunderstood the parent post. Reading through it again I believe he meant something like

      class MySortedList<Comparable Element>{
      void insert(Element e) {
      /* now we can do this: */
      int i = e.compareTo(another_element);
      /* because we can be sure that e implements
      comparable */
      }
      }

      which it seems the specification doesn't support, and it should have. (to be really useful)

      --
      - We are the slashdot. Resistance is futile. Prepare to be moderated -
    2. Re:How sad by bunratty · · Score: 4, Informative

      You should be able to write this as:
      class MySortedList<Element implements Comparable> {
      void insert(Element e) {
      /* now we can do this: */
      int i = e.compareTo(another_element);
      /* because we can be sure that e implements comparable */
      }
      }

      --
      What a fool believes, he sees, no wise man has the power to reason away.
  6. Nooooooo by Khazunga · · Score: 3, Insightful
    Please don't. Operator overloading is one of those cool features that tend to create write-only software. I don't want the meaning of '+' to be different every time I look at it in someone else's code. And please, don't come up with the string concatenation example.

    <irony> 1+1=3 for large enough values of 1 is the most I can concede in operator deviant behaviour. </irony>

    --
    If at first you don't succeed, skydiving is not for you
    1. Re:Nooooooo by Khazunga · · Score: 5, Insightful
      The language should not be expected to prevent you from defining functions named toString() just because they don't perform the function you think they should. Why should it be any different with operators?
      Operators, to be usable, should be very terse. Three characters maximum is a good recommendation. Most operators are one or two characters.

      With that short a definition, the operator's meaning must be inferred by the reader's culture. + is the arithmetic sum operator. We know what it does after working with it for years.

      Methods, on the other hand, can have extremely verbose names. That is one of the good things on the Java coding guidelines. Names are verbose. There's no strcmp. There's String.compareTo. If the compare is case insensitive, there's String.compareToIgnoreCase.

      Objectively, you are right. There's no guarantee a function performs what its name implies. However, if a function's name is incorrect, I can smack the developer on the head. If an operator's name is incorrect, the developer may have done it right, since having an operator named multiplyTransposeAndNormalize is awkward. It's the whole concept of operator overloading that is wrong.

      --
      If at first you don't succeed, skydiving is not for you
  7. Good, but need to avoid a few problems by magnum3065 · · Score: 5, Informative

    Doing mainly C++ development I've learned to love the STL and most recently the Boost libraries and I've long regretted that Java didn't support templates. It always confused me that with as much emphasis was placed on strong typing in Java that there was so much need for casting.

    Although I'm glad to see the introduction of templates, I'm also concerned about how some of the problems I've encountered with C++ templates will be avoided. The biggest problem I've encountered has been the lack of interface checking.

    For example the templated function for_each(begin, end, function) iterates from 'begin' to 'end' calling 'function' on each item inbetween. However there is no mechanism to specify that the type of passed to 'begin' and 'end' must have an equality operator and an operator* and 'function' must take one parameter of the type returned by *begin. This can cause very strange compiler errors when a user tries to pass a variable that doesn't support the proper operations to be compatible with the function. These errors actually appear to occur within the templated code, not the user-written code and can make determining the cause of these errors very difficult.

    The Boost Concept Check library provides a way for programmers writing templated C++ code to enforce the interface requirements on the templated parameters in a way that gives more informative error messages. However this is rarely used, even in the Boost libraries. The documentation on the Boost Concept Check gives a good example of the kind of errors that C++ programmers dread.

    In order for Java templates to be successful they will need to provide some manner of enforcing requirements on the interface necessary for the templated code to work and provide useful errors at compile time if it doesn't.

  8. Re:OMG templates totally rule! by __past__ · · Score: 3, Flamebait
    So, what else is still missing from the language?
    • Metaclasses
    • Higher Order Functions
    • Multiple Inheritance
    • Multimethods
    • Integration of primitive types and classes
    • Makros
    • A GUI library that is not dog slow (Swing) or bothers you with memory management (SWT)
    • A Free implementation. Maybe a standard would help, too.
    Feel free to complete...
  9. AAAAAAAAArgh -- missing the point sooo badly by Anonymous+Brave+Guy · · Score: 5, Interesting

    Sorry, but I'm going to rant now, because every time I see this ill-informed argument it really annoys me.

    Operator overloading is a fact of life when you are working with generics. Suppose I want to write a generalised summation method, which adds up all the elements in a list, whether those are int, float, SomeComplexNumberType or whatever. Question: what well-known and easily understood notation would make sense to use when writing this method? Should I write another method called add that has several versions, for each type I'd like to add up? Or maybe it should be addTo? After all, by your own argument, verbose and descriptive names are the way forward. But what if someone else provides a fixed-point type with a method called sum instead? Or maybe a static method taking two fixed-point values called sumOf? Do you see my point here? If everyone uses + to mean +, then writing such code is easy. If everyone uses different notation, which is forced if you don't allow operator overloading, then what you get is unmaintainable crap that cannot take advantage of generics in many of the most useful ways.

    Java already has operator overloading anyway. You have + to concatenate strings. You have a conversion operator called toString. You have / that divides real numbers, but takes the integer part of the result for integral types. The only difference between these and what you have in a language like C++ is that in Java, you can only take advantage of this concept where the Java designers want you to, whereas in C++, you can write your own types at full strength as well.

    Yes, operator overloading can be abused. So can method naming (and no, you can't smack the developer on the head, if he happens to work on the other side of the world and you're stuck using his library). But op overloading is more than mere syntactic sugar, where generic programming is involved. There are accepted standards for how we write certain concepts such as addition or strict ordering, and operator overloading is necessary to allow user-defined types to meet those standards, and thus to allow well-written generic code to take advantage of parameterised types and such to best effect. Without it, you've got a fabulous canvas, yet nothing but coarse paintbrushes to draw with.

    Alas, as is so often the case, I fear the Java community has been too quick to think it understands, and to go for the buzzword feature without investigating the supports deeply enough. Parameterised types are a good start, and I'm glad to see them included, but I suspect that with experience, there'll be some serious enhancements in a couple of revisions' time...

    --
    If you disagree, post your argument. (-1, Overrated) isn't your personal censorship tool for views you don't like.
    1. Re:AAAAAAAAArgh -- missing the point sooo badly by nojomofo · · Score: 5, Insightful

      I don't necessarily disagree with everything you're saying here, but a few things drew my attention....

      You have a conversion operator called toString

      Um, no. You have Object.toString() which is a method, not an operator.

      There are accepted standards for how we write certain concepts such as addition or strict ordering, and operator overloading is necessary to allow user-defined types to meet those standards...

      It sounds like you're talking about why operator overloading is necessary for C. For one, "user-defined types" don't exist in Java. Second, I don't agree with what you're saying. What about Lisp? Do you think that Lisp is a poor language because you don't add two numbers by saying 1 + 2? Lisp breaks your "accepted standards for how we write... addition".

    2. Re:AAAAAAAAArgh -- missing the point sooo badly by Hard_Code · · Score: 3, Insightful
      Suppose I want to write a generalised summation method, which adds up all the elements in a list, whether those are int, float, SomeComplexNumberType or whatever. Question: what well-known and easily understood notation would make sense to use when writing this method?


      In Java, operators already only apply to primitives anyway, with the exception of the + operator, and then only when in a string context (ok ok, there is 'instanceof' and 'new'...i'm not sure if these can be meaningully considered "operators" as they are reserved for very specific uses). Collections also only apply to objects. It already doesn't make sense to be able to perform certain operations on arbitrary objects. E.g., what does the addition operation do with operands of Bicycle type and the Color orange? If you are going to use generics for collections, you are already going to declare them to use some homogenous base class. In your case it would be something like Addable, which would have an add() method or whatever. Or perhaps just Number, from which you get primitive values, and add them with the primitive + operator. At some point you have to draw the line in defining things. Performing arbitrary operations on arbitrary objects at best makes no sense, and at worse can be very very dangerous.
      --

      It's 10 PM. Do you know if you're un-American?
  10. Re:Not really the point. by Kynde · · Score: 4, Informative

    Its sad how many ./ers dont truely understand o/o concepts or the many other cool features of Java. Hell many still think the only place Java exists is within Applets.

    Although I agree with you, I must say that "understanding object orientation" amongst programmers is little like "understanding humour" amongst ordinary people. Everybody think they do.

    Any language (that I know of, and that is quite a bunch) can be used to write "proper OO code" aswell as plain-old imperative programming.

    I think Alan Cox put it well when he said "object orientation is a state of mind". Linux kernel is really object oriented on many many levels.

    --
    1 Earth is warming, 2 It's us, 3 it's royally bad, 4 we need to take action NOW
  11. Obligatory "parametrics != generics" comment by Anonymous+Brave+Guy · · Score: 3, Informative

    Since no-one has yet pointed it out that I can see, it should be noted that what we're talking about here is parameterised types, and to a limited extent, parameterised methods. This is still quite some way from what you can do with serious generics in other languages.

    There is an obvious comparison with C++ templates here, and although those are not the best generics around themselves, they do have a few very useful tricks up their sleeves. In Java, you can now do parameterised containers, and to a limited extent you can do generic algorithms, although the lack of things like operator overloading cripples these from birth. You can't, AFAICS, do some of the funky stuff with traits classes, and things like template metaprogramming, expression templates and Andrei's tricks combining templates and inheritance -- the stuff that's used in several of the best C++ libraries today to give them an edge -- are out of the question for now.

    That's a shame, because one of the great things about C++ templates is that using them is pretty easy, but there's quite a bit of power under the hood for people actually implementing class and function templates, such as the designers of those libraries. That means improved performance and/or flexibility for Joe Developers everywhere, even if only a few people know and use the features under the hood.

    --
    If you disagree, post your argument. (-1, Overrated) isn't your personal censorship tool for views you don't like.
  12. Too little, too late by MobyDisk · · Score: 4, Insightful

    Too late:
    Sun ignored requests from the developer community to extend the Java core language. Now they finally listen, after Microsoft copied Java with C# and added generics. This is why Java has gone from the hottest thing since Starbucks, to yet another language. They didn't listen to their user base until 2 years after it was too late.
    Lessons learned:
    This is also why Microsoft is so successful - they constantly innovate, rather than sitting on their market dominance. I foresee Sun suddenly trying to play catch-up with new core Java features. I will enjoy reading the spin Sun puts on this, after saying for years that none of these features were necessary.

    1. Re:Too little, too late by addaon · · Score: 4, Informative

      Sun (or at least the people I've spoken to at Sun, who do represent their company) never said that generics weren't necessary. They said, with surprising honesty, that no one had yet come up with an implementation of generics that made sense for the virtual machine. The current implementation of java with generics has been available for around 18 months (externally for what, 12 months?), and has been a compromise implementation, giving a highly requested feature at some cost, perhaps, in the potential beauty of the implementation. The reason that generics weren't included with Java 1.0 is that no one could agree on how to do them; Sun has since realized that they won't be perfect, regardless, but that it's time to push them out the door. Probably, their publication of this stuff is prompted by C# (which uses, more or less, the same flawed-but-usable implementation). But I really do respect Sun's restraint in trying to make it as good as possible.

      --

      --

      I've had this sig for three days.
    2. Re:Too little, too late by pmz · · Score: 3, Interesting

      This is also why Microsoft is so successful - they constantly innovate, rather than sitting on their market dominance.

      Sure they do. Microsoft is extremely good at seeing what other people are doing and, then, copying, buying, or squashing it to meet their agenda. In the case of C#, they first inhibited Java with their VM "embrace and extend" scheme, and then took Java, copied it, renamed it, and added a few things.

      I guess you could call standing on other peoples shoulders innovation, but that is a relatively weak use of the word. Microsoft is more like the business partner that is your friend right up to the point of stabbing you in the back and taking credit for your work.

      As for real innovation, I often wonder what "killer apps" were stifled over the years by Microsoft. Like weeds in a garden, Microsoft is always there...

    3. Re:Too little, too late by DmitriA · · Score: 4, Informative

      Wrong! C# uses a RADICALLY different implementation of generics - Java opted for 'erasure' approach because they needed to preserve backward-compatibility. So that means that all generic type information is removed by the compiler/translator and that code is replaced with polymorphic subtyping with casts (essentially, using the same collections of Objects but everytime you insert or retrieve an element, it will do a cast) - thus, horribly slow runtime performance.

      Next version of C# will support generics in the VM and that will remove the need for casts and allow you to do other nifty stuff like polymorphic recursion, getting specific runtime information that Vector is really that and not a Vector - in Java, you would have to look at the actual elements to determine that.
      In fact, Microsoft Research people that presented a paper on generics in .Net at PLDI '01 claim that this is the first ever implementation of generics with support in the VM itself. But I think if Sun had the time to do it in Java in the beginning, they would've opted for a similar design, but since they hadn't and now they can't go around changing all the VMs and losing compatibility with all the code that is out there, that wasn't an option for them

  13. Re:OMG templates totally rule! by Hard_Code · · Score: 4, Funny
    Hey, you forgot:

    • My pet "feature" of dubious merit


    Until it has that it is obviously not complete!
    --

    It's 10 PM. Do you know if you're un-American?
  14. Missing from the language... by Tom7 · · Score: 3, Insightful

    > So, what else is still missing from the language? It seems almost ready to go mainstream.

    Well, I don't know about most Java programmers, but the missing features that constantly bug me are:

    - Higher-order functions (Seriously, you can't live in a language that doesn't have this once you get used to programming with them!)
    - Algebraic Types and Pattern Matching (Vital for manipulating syntax trees, like in a compiler)
    - Tuples
    - Getting rid of 'null' (This is possible, in fact, easy, and would make the language much cleaner, less error prone, and even more efficient)
    - Uniform typing discipline (ie, int vs. Integer ... I think this is relieved a little bit by generics)
    - Parameterized Modules (a la SML's functors)

    There are also some bugs in the language itself, though those wouldn't really bother me day-to-day.

    - Arrays are covariant, leading to class tag checks on every array write (in the general case)
    - The description of binary compatibility is broken (It can lead to situations where recompliation of the class files either leads to a different program, or to a failure to compile!)
    - ...

    A language that makes some of these strides is called Nice , though I've never used it.