JSR 201: Autoboxing, Enumerations, for(each) and Static Imports

Discussions

News: JSR 201: Autoboxing, Enumerations, for(each) and Static Imports

  1. Sun has released a new Java 1.5 JSR that proposes some new "syntactic sugar" in line with the 1.5 theme of improving the overall "Ease of Development" in the next version of the language. The changes include enumerations, autoboxing, enhanced for loops and static import.

    Check out JSR 201: Extending the Java Programming Language with Enumerations, Autoboxing, Enhanced for loops and Static Import.


    From the site:

    The proposal extends the Java programming language in four specific ways:

       1. A syntax for defining enumerated types. This syntax provides linguistic support for the Typesafe Enumeration pattern.

       2. An automatic conversion from primitive types to their corresponding reference type wrappers. This conversion facilitates the integration of generics into the language, and reduces inessential clutter.

       3. Enhanced for loops allow convenient iteration over collections, without the need for an explicitly defined iterator. This reduces the need for boilerplate iteration code and the corresponding opportunities for errors.

       4. Static import. A mechanism to allow the use of unqualified constants.

    This JSR will cover at most these four specific language changes. If other language change proposals should arise from the work of the expert group, these will be pursued in new JSRs.

    Threaded Messages (67)

  2. It's too bad we had to wait for C# before Sun decided to fix some of these minor problems with Java.

    Man, what will be next? Easy to use web servivces? A real IDE? Simplified J2EE? Asynch processing built into the language?

    Here's to hoping Scott copies more of Microsoft. Sheesh, just do what's right Sun instead of complaining insecently and then playing catch-up.
  3. It really is a shame that we have two nearly identical languages (C# and Java) that are such bitter enemies.

    I like a lot of what MS did with C#, and I am also glad that some if the good ideas may be incorporated into Java as well. I just wish Sun and MS could have come to some sort of agreement for a single syntax.

    On the flip side, I guess you could argue that the rivalry between the two driver innovation.

    If only I could write C# code and deploy on WebLogic, JBoss, or pretty much anything besides IIS.
  4. <quote>
    I like a lot of what MS did with C#,
    </quote>

    mmmh if you compare C# with language constructs from Python, Ruby, Perl, Lisp, Haskell,... it seems a rather boring language to me...for a brand new revolutionary language that's going to change the world (according to some people).

    Why create another Java if you can create a new language today that has features that people dreamt of since the 50's, but weren't feasible because of computing power.

    I find it very strange that the evolution from C to C++ to Java to C# has not made many contributions to the expressiveness of these languages. Ofcourse every language has its own subtleties and I'm not saying that these languages are bad but overall they are pretty much the same.

    That's why I'm a big fan of Very High Level Languages because you can express more with less code. The drawback of this is that the execution is slower. But is this still an issue?
  5. The other drawback is that you get ureadable dreck like:

    foreach (@_)
    {
      s/\w\d+\w(\w\w\)[a..z]*/$1gf/wg;
    }

    Most people seriously abuse the language you list, and some of the features of those language cause serious problems. A good example is the lack of datatypes and nonstatic binding. It's very easy to write typos in PERL or LISP that total compile and execute, but just don't work. These same typos would be caught instantly during compilation with "old boring low-level languages".

    VHLL may be more expressive, but they are far less precise, and I don't want to get in an plane or drive a car, or have my heart operated on by something like that. Many business may not want to open themselves up to something like that, either.

    Those sorts of languages are really for expert and experienced programmers, and have no business being used by sloppy and inexperienced hack-a-thon programmers. And that is why they are dangerous.
  6. I do agree with you that for example Perl has some ugly language constructs (with implicit "ripples effects"), but this doesn't mean that they aren't useful and couldn't be implemented in a more clean, consequent and better understandable way. It doesn't mean either that languages need to be non-statically typed when having certain cool features!

    <quote>
    Those sorts of languages are really for expert and experienced programmers, and have no business being used by sloppy and inexperienced hack-a-thon programmers. And that is why they are dangerous.
    </quote>

    Bollocks! It's like saying: let's not include lambda's in Python, they wouldn't understand anyway! Why use OO? It takes a lifetime to master it! Someone who doesn't grasp a certain feature can probably program with ubiquitous "classical" constructs. But a programmer who is smarter would get frustrated because he can't reach out for the right "tools".

    But my main point is that C# doesn't add much when compared to Java. It's rediculous that a multi-billion dollar company can only come up with a slightly improved Java language clone. I think many people would agree, that C# isn't very innovative if you look back at its predecessor languages C++/Java.

    I'm not saying that C# isn't useful, but It isn't giving me (as a Java developer) a WAAAAW feeling either.
  7. C# is a Java ripp off and a waste of time. Microsoft was getting there ass kicked by Java and had to do something to stop the bleeding.

    Java developers are the real winners, since it is so easy to move between the two languages. It is the poor VB programmer who gets the shaft, since it's difficult to move code from VB6 to VB.Net.
  8. <quote>
    It's too bad we had to wait for C# before Sun decided to fix some of these minor problems with Java.
    </quote>

    We still need the attributes on the methods.

    [WebService]
    String sayHello()
  9. ahh there is this JSR for it.

    JSR-181 "A Metadata Facility for the JavaTM Programming Language"
  10. I have just my 2 cents to add:

    First of all I don't believe adding every exotic feature in every language. Java was successful since it omitted most of the obstacle and rarely used features of some of the languages like C++. I think MS again made a mistake and add all the complexities back in C# (reference boxing,even you can manipulate pointers!), and Java doesn't have to necessarily follow their path.

    Templates aka generics are long waited features in Java, that will be part of JDK 1.5 any way.

    As far as features like reference boxing, I don't think so we need that feature so badly in Java. It's better to keep Java clean and simple as it is.

    BTW I wish MS at least should follow the Java path when it comes to notation (varaible names, Method signature, etc). But again, they had their own way of doing things that confuses the whole community.
  11. JSR-201 fails to address the real problems with the current Java standard:

    1) Multiple inheritance. The lack of MI is a serious one for huge applications. The "so-called" problems with MI is largely solved theoretically (a Eiffel-kind-of MI works pretty good). I suspect MI got ditched because Gosling only knew of the stupid C++ implementation of MI, not the well-designed alternatives. Today, MI designs in Java are solved through delegating and it sucks big time and it doesn't scale.

    2) Templates (F-bounded, preferrably). At the point you need some sort of container in Java, you are basically using a typeless feature. And as any experienced software engineer will tell you, typeless features are going to break your application sooner rather than later.
     
    3) Covariant argument types and return types. Even C++ have covariant return types these days!

    4) Support for contracts and aspects. There are already libraries for this - BUT GET IT INTO THE LANGUAGE!

    With these features, Java would rule the world... sort of.
  12. Han,

    1) Java doesn't have multiple inheritance because of strong design arguments, not because Sun didn't get around to it. If you think you have a better solution, go ahead and propose it through the JCP. IMHO the lack of MI probably saves 100 people from using MI badly for each time it gets in they way of using it well.

    2) Are you aware of the Java generics proposal? JSR-201 only addresses minor language issues. The Java generics JSR provides template-like constructs for java (not exactly as powerfull as C++'s templates, but cleaner and probably sufficient for most cases).

    3) AFAIK this is also solved as a part of the Java generics proposal.

    4) I'm not a AOP expert, but I don't think its mature enogth to put in to Java any time soon. Its nice for experiments as long as it's a seperate library, but the JCP has a responsibility to see that it really works well, for Java, for many years before incorporating it into something as important as the JLS. AFAIK AspectJ does a pretty good job at integrating AOP into Java, so what's the problem? No offence to the AOP guys :)

    Gal
  13. Enumerations[ Go to top ]

    Its high time that Java got enums! These are basic vital OO constructs for type safety that have been around in other languages for decades, C++, C (weaker form), Pascal (rich) and Ada (rich). Passing unadorned int-s where we really want an enumerated domain type is a serious quality issue. Type safety is a key principle of object-oriented languages that enhances correct runtime behavior.

    Ibid for templates/generics - the more type safety the better. Every cast from an iterator is a potential class cast exception.

    -- andre
  14. What's AFAIK?
  15. AFAIK -> As Far As I Know.
  16. what is BTW?

    And all these fuss about language features, current Java is simple and powerful enough to solve the programming problems we face today. i will alsways prefer simplicity and good design over complexity and shorthand.

    Another thing, when will Sun implement the single vm high efficiency Java like Apple did. AFAIK, memory and efficiency is the ONLY problem with Java. Java holds the record for the least efficient language for cryin out loud.
  17. Gal,

    1) Not strong design arguments - weak ones. MI as in C++ is terrible and can lead to terrible designs, but THERE ARE ALTERNATIVES and it's needed.

    2) Yup - forgot about that...

    3) That would sursprise me big time. Will check it up.

    4) Agreed - AOP is kind of a wish-list thing.
  18. 1)[Multiple inheritance] Interesting. Do you have any links on these other MI approaches. As an ex-C++ programmer I would kill to stop C++-style MI being added to Java!

    2)[Templates] Check JSR 176 http://jcp.org/en/jsr/detail?id=176 for the full list (prior to those added by JSR 201) of planned features in Java 1.5.

    The down side is that Java 1.5 isn't expected until the end of 2003.

    3)[Covariance] Agree on return types. Strongly disagree on argument types.

    4)[Contracts and aspects] My feeling is that aspects should remain as an extension, but it certainly would be an exciting change if it was included. What is the contract support that you are referring to?


    I am not (yet) convinced of the value of boxing. I have seen negative comments on the C# implementation ( http://www.geocities.com/csharpfaq/box.html ). However, the lack of structs and pass by reference in Java, and the fact that the boxing proposal for Java merely restricts itself to automatic primitive conversion may avoid all of those issues.

    /david
  19. I've built a fairly large and powerful framework (Tapestry) without needing or missing MI.

    In fact, MI would get in my way.

    What Java really gives us, with good garbage collection, is the ability to use aggregation to solve problems, rather than MI. I prefer dividing problems into small (and individually testable) elements, rather than monolithic objects. MI can be thought of as a variant on aggregation that simplifies memory allocation ... aggregate everything into a single object.

    I've found that software agility is aided by dividing up complicated interfaces into several smaller, more specific interfaces. The interfaces may be combined by an implementation ... you sometimes see funny code like:

       foo.soSomething(this, this, this)

    Because the implementation implements three interfaces (but that's pretty rare). From the foo's perspective, it's three different objects providing three different services.

    Summary: I don't like MI because its about building up large monolithic interfaces; Aggregation (especially when combined with interfaces) divides complicated interfaces into smaller, simpler interfaces.
  20. We still need the attributes on the methods.


    >>[WebService]
    >>String sayHello()

    I would say this is the last thing that we need. Why not have a comment such as @webservice and tools like xdoclect et al can deal with it, don't clutter the language with the latest fad
  21. McRobb - you got the point. Sun need to focus on the language basics, not current hype.

    In 10 years time, C# is going to look weird and cluttered, accumulating all sort of stuff into [this-years-cool-thing] declarations. Stupid, stupid, stupid.

    Web Services is a dead end anyway...
  22. Yes the Xccolet tools is great but how many people use it? Yes the most devoted java programmers search the web and gain knowledge. But the thousands of VB/Java coders around doesn't know about these tools. And they read those Master Java 1.3/1.4 books that have this kind of information about all the great tools for Java. And when they compare how they have to do it in the Java world vs. how they do it in the .Net world - well I think they will tell their boss they can get the work done in less time in .Net. The boss doesn't care what the developer use, just how much it cost to develop.

    At my company I can't be around all java projects and tell the guys that ant, xdoclet, struts, jakarta, junit and all other cool java stuff exists and what they can be used for.

    At the end it's our company that pays our salary, I don't bring a bag of money with me when I go to work. And ass long the bosses that pulls the strings ... well they decided on the tools that get the jobs done in less time/price.


    As a pure evangalist for the Java language. Yes I can use XDoclet for the method/class attributes and don't have the language bloated with this stuff. But the language have to evole and fit into the market.
  23. Not too fast, please![ Go to top ]

    Off topic: All that bashing of copying is against (human) nature. We learn by copying of good behavior, good design (patterns promote that, right?), useful features, etc. (Although, I do not know what to do with patents, royalties…)

    On topic: I would be cautious to bring cool features into language itself, there is a big risk.
    Enumerations – yes, I welcome them and I think they will be useful, although it is possible to emulate them relatively easy.

    Personally I am afraid of some “new” features in JDK: one example might be regular expressions in String class itself. That is ridiculous at my taste; it is against my understanding of OO principles.
    Another example: class loader instance is a part of a class identity (name). Are you aware of it? It means that we have issues like:
    Object o = new MyObject();
    o instanceof MyObject returns FALSE!!!!!!!!!! But in debugger or with println( o.getClass().getName() ) we could not see a difference!


    I understand reasons for that behavior (security, sandbox etc.), but all that is far from being obvious and causes some troubles. I would rather try to address this issue; it looks like sign of upcoming DLL like hell.

    Why do not allow turning it on and off like security managers?
  24. Education is the king![ Go to top ]

    <quote>. But the thousands of VB/Java coders around doesn't know about these tools. And they read those Master Java 1.3/1.4 books that have this kind of information about all the great tools for Java.</quote>

    If people are unwilling to learn, then nothing can help. That is impossible to include everything in Java/JRE/J2EE. It looks like an attempt to bring MS ideology on this ground.
    I vote for freedom: there is no car that suits everybody. We will always choose different cars even if they all will have the same price.

    <quote> The boss doesn't care what the developer use, just how much it cost to develop. </quote>
    Really?
    <quote>... well they decided on the tools that get the jobs done in less time/price.</quote>
    Really?!!?!!

    They decide: yes! Is the decision optimal cost wise? That is the big question!
      
    Unfortunately, it is not so simple as question about money. There are much more political and psychological factors in the decision making process. For instance: in a bureaucratic environment boss’s prestige depends on budget of his/her department and number of employees. Such boss simply will not listen to cost reduction arguments.

    Even we talk just about money: are we talking about cost of initial development or about TCO/ROI? With cheap programmers we got really cheap solution in less time (questionable), BUT, what about cost of improvements, maintenance etc.

    Again: those expenses might be paid from different budgets and might be considered as other “projects”.

    <quote>
    As a pure evangelist for the Java language. Yes I can use XDoclet for the method/class attributes and don't have the language bloated with this stuff.
    </quote>

    Keep up doing the good job. Education is the king!
  25. "Man, what will be next? Easy to use web servivces? A real IDE?"

    I think that last question should be "A real IDE that won't require small ISVs to take out a second mortgage to buy?"
  26. I think that last question should be "A real IDE that won't

    > require small ISVs to take out a second mortgage to buy?"

    www.eclipse.org

    Tom
  27. Good artists copy...[ Go to top ]

    ...great artists steal.

    I find this positively funny. I'm painting with a broad brush, but bear me out:

    When MS integrates new functionality from something that exists on the marketplace, there's a giant uproar. "MS is evil!" "They're stealing!" "It's unfair!"

    But when Sun does the same thing no one says a peep.

    I love a good double standard.
  28. Re: Good artists copy...[ Go to top ]

    When MS integrates new functionality from something that exists on

    > the marketplace, there's a giant uproar. "MS is evil!" "They're stealing!"
    > "It's unfair!"
    > But when Sun does the same thing no one says a peep.

    I don't think they are stealing these from C#. Such requests have sat on the bug parade for ages... I think the competition has just driven them to act on it.
  29. Autoboxing is crap. It removes simplicity from the language.
    I do not like for(each). I do not like the coupling of keywords to some specific classes. What if I want use my own collection library instead of the ones in the standard library?. I do not see any problem with the current idiom.
    Static imports are great.
    Enumerations seem OK to me.
    BTW, I do not see why some people here say that Java is copying everything from C#. Most of new stuff coming to Java, like templates, do not exist in C#. I do not know much C#, but AFAIK it does not have something equivalent to static imports, and the autoboxing (which does exist in C#) seems crap to me. I hope they do not include this feature. C# also has enums, but the proposed Java enums seem somewhat different, since their purpose is implementing the Typesafe enum described in the Effective Java book.
  30. Simplicity of Autoboxing[ Go to top ]

    So you're saying that the current way of handling primitives not being objects:

    someList.add(new Integer(1));

    Is more simple than the autoboxing way:

    someList.add(1);

    For the programmer...I don't see how it adds complication.
  31. I will answer in the form of a question (and not even by own question either):

    > From: Daniel Bonniot <Daniel dot Bonniot at inria dot fr>
    > To: nice-info at lists dot sourceforge dot net
    > Subject: [Nice-info] Ambiguity for List<int>
    > Two people drew my attention to a problem with calling
    > the remove function of List<int>:
    > ArrayList<int> alist = new ArrayList();
    > alist.add(10);
    > alist.remove(0);

    > The reason is that List has tow methods: remove(int n),
    > which remove the nth element, and remove(T x), which
    > removes the element x. In our case type T = int, so there
    > is ambiguity.
    > In other words: do we want to remove the element
    > whose value is 0, or the element at index 0?
    ...
    > The news also said the Java 1.5 would include automatic
    > boxing of primitive types (like Nice already has), so I
    > suspect they might come to a similar ambiguity problem.

    By the way, seems to be a better programming language than Java, while at the same time running on a standard JVM and being fully integratable with Java code, and having better support for Generics today than JDK 1.5 will have next year. (http://nice.sf.net)
  32. Great, now if they just drop the stupid "Java 2" marketing crap and get back to just "Java" it will be perfect.
  33. True! I've always wondered what Java will be called when jdk 2.0 arrives.
  34. What happened to Properties?[ Go to top ]

    After writing thousands of empty get/set methods, it is about time that was fixed to. And surely after all this time

    a[x] = b[x];

    Can be defined as syntactic sugar for
    a.set(x, b.get(x));

    so that arrays and collections can be unified.

    And how about keyword optional arguments, even VB has them.

    Feature bloat is a worry, but there are several basic things of which should have been added long ago.

    But plese, no ON ERROR RESUME NEXT!
  35. Fixnums for efficient boxing[ Go to top ]

    Lisp can do boxing without creating extra objects. The trick is to have a 30 bit integer instead of 32 (which Lisp calls FixNums). If objects are int aligned, then you know that the low order two bits of a real pointer are 00. Thus ints can be 01, and you can even fit in 30 bit floats.

    What is amazing is that the SPARC has special instructions to manipulate these 30 bit integers! So they have no overhead.

    But -- that's not what C does. And we are stuck with the C mentality. It is a great shame that lisp died.
  36. Hi ppl,

    Don't really like the idea of autoboxing... But I have a question... If we DO have autoboxing will the semantics of the "+" operator change i.e in the following situations:

    1. int + int
    2. int + Interger

    The first case is clear and is simple addition and we get the sum returned as an int but in the second case what happens? do we still get a String returned or do we have some "automatic" autoboxing done by the JVM which returns the sum as an int (which I guess is unlikely)? Just a thought...

    Comments anyone?

    Cheers

    Smythe
  37. How about handling the obvious too. I've done a remendous amount of Boolean as a return type from a function and having to do


    if ( booleanFunction().booleanValue())

    if Boolean

    should be handled just like

    if boolean

    -D
  38. Two words for all you C# defenders out there :

    - virtual
    - override

    Those two keywords were a shock to me coming from Java... They really shouldn't be necessary anymore. I should have to use keywords to bypass polymorphism, not to enable it.
  39. Actually, that's one feature of C# that I like.

    I believe you should have to explicitly override methods.

    The fragile base-class problem hasn't completely gone away in Java.

    If a framework provides class A and I create subclass B and implement method m() on B you think I'm ok.

    But if a later version of the framework also implements method m(), then class B may be broken in a hard to diagnose way.

    Requireing explicit overrides will allow the compiler and/or runtime to diagnose this.

    I just don't think that's enough. I wish I could declare a much richer set of attributes on my methods ... such as, "if-you-override-you-must-invoke-the-base-implementation".
  40. I can see both sides of the forced over-ride argument.

    However, it's not that difficult to overcome in Java, it's just a matter of discipline.

    When building a system, get into the habit of making all your methods final. That way, if you want to over-ride them, you _will_ get a compiler error.

    This works well when you own all the code. I accept it might not make intuitive sense, but after a while it becomes second nature. It forces you to consider _why_ you are over-riding a method.

    In cases where you are building libraries for others to use, it's even more important that you consider what methods should be over-rideable. You want to let people over-ride certain methods, but not others. It's therefore prudent to start with everything final and then "release" the methods you want people to be able to over-ride by removing the final qualifier.

    Sounds backwards, I know, but it has served me well.

    Oh, and final methods will tend to run faster than non-final ones too so there's another upside. :)

    Chz

    Tony
  41. Need to add using() as well?[ Go to top ]

    Personally, I agree that most of these features have been in the queue long enough, and have not been added earlier mostly due to sheer stubbornness and desire to protect investments (probably not only on part of Sun, but also on the other industry participants in the JCP). I guess .NET has had at least one positive effect as a result.

    One other feature that I think perhaps should be added following .NET's example is using():

    using (obj = ...) {
      ...
    }

    which is simply a syntactic sugar for:

    obj = ...;
    try {
      ...
    }
    finally {
      if (obj != null) obj.dispose();
    }

    I am normally AGAINST sytactic sugars for various reasons, but I feel that in this it is justified. The above pattern is essentially the only proper way to deal with objects representing external resources (files, etc.) in the presence of GC. When a particular syntax is easy, developers tend to use it far more often, and in this case it would lead to avoiding a lot of common problems.
  42. Need to add using() as well?[ Go to top ]

    <Mind Bridge>
    One other feature that I think perhaps should be added following .NET's example is using():
    using (obj = ...) {
      ...
    }
    which is simply a syntactic sugar for:
    obj = ...;
    try {
      ...
    }
    finally {
      if (obj != null) obj.dispose();
    }
    </Mind Bridge>

    Well, then what about blocks (see Joe Walnes' blog: http://radio.weblogs.com/0108103/2002/11/27.html#a113). Here is an example:

    <Joe>
    Here's an example of how a foreach facility could be added to Java/C#.

    public class List {
      ...
      public block void foreach() {
        for(int i = 0; i < internalArray.length; i++) {
          Object item = internalArray[i];
          yield(item); // execute block
        }
      }
    }

    Usage:

    list.foreach(Person person) {
      print(person.getName());
    }

    Okay, that's foreach added.
    </Joe>

    And see the other examples too. Imho it's more flexible than C#'s approach. I really like it. That's the number one thing (besides metadata attributes) I want to see in Java. I don't care much about the other proposed ideas, they are syntactic sugars, this is brings in a lot of flexibility. I really want to see foreach implemented this way, and why not, even overridable by the developer too!

    Ara.
  43. Need to add using() as well?[ Go to top ]

    Actually, you can already do something like that with anonymous classes, which would not introduce anything new to the language and deal with the problem (for example see Nick Minutello's post) - that is, as long as you either subclass List yourself or we get to persuade Sun to add it to its Collection interface.
    Arguably, it's more typing, but I think the syntax is cleaner. In your example one misplaced ; would introduce a really bad bug. The example also suggest the block as an implicit parameter, which is (IMNSHO) rather nasty - what if I want to pass in two, or three blocks?

    Off the topic: c# is going in this direction (sort of) - one of the new features they are going to introduce shortly (along with partial classes and generics) are anonymous delegates. So obviously, they haven't learned all from Java yet ;).
    Regards,
    Vlad
  44. There are a couple of other nice features in C#:

    1) as

    Rather than

    if (o instanceof Dictator.class) {
       Dictator polPot = (Dictator) o;
    }

    you have

    Dictator polPot = o as Dictator;

    (you get a null if o isnt an instance of Dictator)

    Only problem with this is that you are introducing another keyword - hence backward compatibility issues.


    2) goto (no, really!)

    In Java (as in c, C++) the switch statement is quite error-prone, its easy to forget a break; in a switch statement and it often takes a while to be detected. C# insists that either a case: is empty (whereby it naturally falls through), it contains a break; or it contains a

    goto case X;


    Foreach?

    While I initially thought that the foreach was nice in C#, I was convinced otherwise. Does it make sense for a language construct to depend on the interface a class implements?

    I would prefer something along the lines of;

    Collection col = ...


    col.foreach( new IterationHandler() {
        public void handleItem(Object ) {
            String str = o as String;
            // do what you want to do
        }
    });

    Or with generics (yech)

    col.foreach( new IterationHandler<String>() {
        public void handleItem(String item) {
            // do what you want to do
        }
    });

    -Nick
  45. I agree on number 2. It's quite common to make mistakes with the switch statement. You ususally don't let it fall through but insert break statements all the time. It would be nice with a compiler check here.
  46. Nick,

    About the dependency on a particular class, I see your point, but it's nothing new. Throw/catch depend on throwable, the + operator has special support for Strings, etc. If you are worried that the language will depend on classes from java.util, according the the current proposals it won't. Something like an "Iterable" interface will be added to java.lang, and the new for statement will depend on it rather than java.util.Collection. I think that does make things a bit cleaner.

    One thing that bothered me a bit in the current proposal is that you have to declare the type of the iteration var. As long as they figure the type parameter of the iterator themselves, it seems it should be possible to say:

    List<String> names = ...
    for (name : names) {

    }

    By the way, I checked it out, and covariant return types are covered by JSR-14 (generics).

    Gal
  47. 1) I use instance of to provide (incidentall) checking of nulls.
    So, say equals would look like:
    public boolean equals(Object o) {
     boolean result = false;
     if (o instanceof MyClass) {
       // and here I can assume that o is not only MyClass, but
       // also non-null
     }
     return result;
    }
    With as, I would still have to do the null check (remember, you can put nulls into collections? :))

    2) a good code analyser can do that for you (I am working on one if you want to try it ;)). You can get out of the case in a number of other of ways - return, throw, continue in addition to break. Not all of them are nice practice, but they are all allowed by the language. At least you can't do some of the C++ nasty switch stuff in Java.

    3) I agree, especially as it would not require any change to the language. I could never understand why it didn't make into java.util.Collection. It's not exactly a rocket science and with inner classes it's more powerful than STL's functors.

    Regards,
    Vlad
  48. <quote>
    public boolean equals(Object o) {
     boolean result = false;
     if (o instanceof MyClass) {
       // and here I can assume that o is not only MyClass, but
       // also non-null
     }
     return result;
    }
    </quote>

    Actually, what you really need to write is:

    public boolean equals(Object o) {
     boolean result = false;
     if (o != null && o.getClass().equals(this.getClass())) {
       // and here I can assume that o is not only MyClass, but
       // also non-null
     }
     return result;
    }

    Using instanceof, o could be a subclass of this class.
  49. Yep, but given the substituion principle of the OO, I can be happy (and am in a lot of cases) to consider two things the same (for some purpose) even if one is a subclass of the other.
    If we wanted to stretch it, your example won't work always either, as the two classes could be loaded by a different classloaders (a normal situation in an application server), and then MyClass c = (MyClass) c1 throws a ClassCastException even if the c1 is MyClass (instanceof fails here as well).
    Regards,
    Vlad
  50. I don't see why we need to get into us vs them, Java vs C# here. I think there _are_ good features in C#, although I personally wouldn't want to move to a Microsoft-only platform. If Java can benefit from some of C#'s features it's good for everyone. At the end of the day we want a better Java--where particular features come from is immaterial. No language has been completely original for decades, anyway.

    Regarding foreach style iteration, I don't know. I don't miss it. Boxing is worthwhile...how often do we want a HashMap of int, for example, and find it a pain in Java? There are performance issues, but there are with many language features--good developers should be aware of them. Enums should have been in Java 1.0, and have been on the bug parade before anyone thought of C#.

    Attributes (meta-data associated with methods and classes) are a good idea in the .NET IL (not just C#), and there is a separate JSR for them, as someone has already pointed out.

    What I would like to see also is simpler properties syntax. I think C# does this well. So we can define properties on interfaces, and use the simpler format. JavaBeans are great (and in my view, underused) but it's a pity that the JavaBean naming conventions aren't truly integrated into the language.

    Rather than person.setAge(newAge), person.age = newAge.

    I'd also have to say after looking at C# in detail, it isn't fair to call it a Java clone. There's a fair amount of new stuff (not all of it good).

    Finally, I'd like to see some of the ideas from AspectJ incorporated into core Java. C# doesn't offer anything like them.

    Rod Johnson, author of Expert One-on-One J2EE
  51. 3. Enhanced for loops allow convenient iteration over

    > collections, without the need for an explicitly defined
    > iterator. This reduces the need for boilerplate iteration
    > code and the corresponding opportunities for errors.

    From JSR 201 "An enhanced for loop for the Java™ Programming Language":
    > We propose a second form of the for loop specifically
    > designed for iteration over collections and arrays.
    > Traditionally this is done using a foreach keyword, but
    > it seems unnecessary and counterproductive to add a
    > keyword at this late date. Under the syntax of this
    > proposal, the above code could be replaced by this:
    >
    > for (String s : c) {
    > ...
    > }

    Why is it "unnecessary and counterproductive to add a keyword"? What is the big issue with adding a new keyword if it helps clarify usage? How can overriding the "for" keyword with this unintuitive and obscure syntax be deemed a superior solution to adding a new keyword, especially when this keyword is traditionally used for this purpose and is therefore familiar to most users? A larger and more descriptive vocabulary is a definitely a good thing with human languages (one of the key reasons for the success of the English language), so why the resistance to adding new keywords (where they help clarify syntax and aid understanding) to computer languages, and in particular Java? I appreciate the desire to keep the language clean, simple and uncluttered but, imo, an obfuscated syntax is the greater evil as it makes code harder to read and therefore will inevitably lead to an increase in bugs.

    More descriptive languages (including Attribute-Oriented Programming) seem to me to be the way forward. For example, if a programmer wants a collection with fast random-access look-ups, synchronised access, and a changeable number of members then why should the onus be on the programmer to remember that the concrete Collection class he wants to use is java.util.ArrayList and that he needs to call java.util.Collections.synchronizedCollection(Collection c)? Surely it is preferable (more readable, intent is more obvious, less prone to errors) for a programmer to be able to specify this sort of information using attributes and let a precompiler do some of the error-prone mapping from human thought processes to computer-language syntax?
  52. What is the big issue with adding a new keyword if it helps

    >> clarify usage

    Because it breaks backward compatibility.
    Adding a new keyword will mean that any code using that keyworkd will break.
    The JLS controllers are very allergic to breaking backward compatibility - and rightly so.

    -Nick
  53. Backwards compatability is an issue, but I do wish people would stop making it the be all and end all of everything.

    Building with backwards compatability in mind is incredibly limiting. If you do it right, and put in the appropriate compiler switches to ensure backwards compatable code _can_ be produced then that should be the end of it.

    You can't move forward quickly if you spend all your time looking backwards.

    It's a fine line, I accept that, but I think we're all stuck a little on the wrong side of it. :)

    Chz

    Tony
  54. What is the big issue with adding a new keyword if it

    >> helps clarify usage

    > Because it breaks backward compatibility.
    > Adding a new keyword will mean that any code using that
    > keyword will break.
    > The JLS controllers are very allergic to breaking
    > backward compatibility - and rightly so.

    True - there will always be a small chance of a naming clash. This will always be a problem in languages where keywords and identifiers are not distinguishable by syntax (e.g. by having a special character prefix such as # before all keywords or identifiers or by other rigourously enforced naming standards). But it seems a very small price to pay if a tiny minority of people have to amend their code (and these amendments would require minimal effort as they would consist of renaming any identifiers that clashed with new keywords) compared to the benefit of increased functionality/clarity in the language for everybody who uses it.

    To minimise these issues Sun could add a list of potential future keywords to each release so that users are warned at least a version or two in advance that an identifier they are using might clash with a future keyword (like deprecation warnings).

    The Java language has to be allowed some flexibility to evolve and for new functionality to be added. Trying to squeeze new functionality into existing syntax just seems a recipe for disaster, especially when it is unclear and overrides exisiting keywords with new behaviour.

    Obviously trying to preserve backwards-compatibility is important - but, in reality, would adding new keywords really be a big issue if sufficient warning were given? Java must be allowed to move forward more quickly (for example, look at how long everyone has had to wait for generics...)

    Gavin
  55. Why is it "unnecessary and counterproductive to add a

    > keyword"? What is the big issue with adding a new keyword > if it helps clarify usage?

    I totally agree. Clarity == productivity, so I suggest the following:
      - 'if()' replaced by 'If'
      - '{' replaced by 'Then' when used with an 'if'
      - '} else {' replaced by 'Else'
      - '}' replaced by 'EndIf'
      - 'for(){' replaced by 'For'
      - '}' replaced by 'Next' when used with a 'for'
      - 'With/EndWith' blocks to avoid repetitively type object names
      - ';' removed altogether as statements that span only one line are the rule rather than the exception. Multiple line statements could have a '_' at the end of each line.

    These changes are basic, but they would greatly improve the clarity of the language :)
  56. Good one. Why not use VB then :)
  57. How is a different keyword different from a new syntax inside the keyword? Both break backwards compatibility in exactly the same way.
    But then, despite the (outwards) dislike of overriding in Java design team, they rely on overriding in some places.
    + with special meaning for strings (but I can't add two BigDecimals using +?)
    . as a namespace separator (both packages and inner classes) and de-referencing operator (in x.y.z.a.b.c what is z?)
    Regards,
    Vlad
  58. Just a clarification
    foreach(String s : c) does break the backwards compatibility in exactly the same way as
    for(String s : c) does - i.e. not at all, since "String s : c" is not a valid argument list.
    Of course foreach(c) would break it, but since we need to declare the variable we want to use in the loop - or at least I would like to be able to declare it :).
    Regards,
    Vlad
  59. i think they mean backwards compatibility in a different way than what you are describing.

    currently "for" is a reserved word and "foreach" is not, therefore "myObject.for()" is invalid but "myObject.foreach()" is valid.

    if "foreach" were added as a reserved word "myObject.foreach()" would become invalid.

    that happened when they added "assert" in 1.4 -- ILOG has a very used method called "assert" that compilers and 1.4 IDEs don't like, etc.

    and that brings up the whole IDE thing - you could write an IDE (java 1.3) that is upwardly compatible to display and compile code for future versions (1.4), but if those future versions add reserved words (assert) it causes "inconsistencies".

    etc. etc. etc. - i don't think adding a reserved word is a big technical challege, just a headache in most other aspects.
  60. But I can still write an LLR parser that disambiguates the two without any problems- because "String s: c" is not a valid argument list, so I just need to do a lookahead.
    Assert is a different story, as it evaluates a boolean expression which _is_ a valid argument list.
    So yes, they would have to write a slightly smarter parser, but java is not exactly LLR(1) anyway because of a couple of quirks.
    Regards,
    Vlad
  61. I would consider adding additional final keyword that applies to the object not just to the reference, e.g. in C++ there is constant pointer and pointer to the constant object that means that object properties cannot be changed. This would allow to avoid unnecessary cloning of the object when passed as method argument or returned from the method call.
    I don’t know what the right syntax should be, but it is just details…
  62. I could not agree more!

    Having to do defensive copying of objects passed as method arguments or returned from a method call is a pain and language support in this area would both reduce code clutter and help clarify an API coder's intent.

    Whilst they are at it, perhaps they could finally get around to sorting out Java's cloning mechanism...
  63. Yes, enforcing object immutability would be helpful. But it might be hard to implement. How would the compiler know which methods were read-only?

    Rod
  64. Why not tag read-only methods with a read-only modifier?
  65. <snip>
    Why not tag read-only methods with a read-only modifier?
    <snip>

    When Java has attributes, we could do it in a more general way through a read-only attribute. Btw, I completely agree regarding clone. I'd love to see a better solution.

    Rod
  66. const in Java (global optimizations)[ Go to top ]

    I'd like to see this as well, but since then I had a closer look at JLS/JVM spec and understand why it's a no-go at the moment.
    You would have to enforce it at a load time, rather than compile - becuase other things than compiler can produce bytecode. That means the codeverifier would have to check for this at load time, which is quite an expensive check at the moment.

    This falls under something I call global optimizations - the loader/linker goes through code and optimizes globally rather than just local things. The computing power unfortunately isn't entirely there yet to do it at the load time.

    Regards,
    Vlad
  67. I agree that adding C++ style const references and methods is very important. Its been in the Bug Parade as a RFE for ages.
    I've heard some talks that it might be addressed when the new Java Memory Model kicks in, because the new JMM will likely be more fully "aware" of the constness of references to make performance optimizations anyway (current JMM ignores it AFAIK). Anybody know anything about this?

    Gal
  68. It's not clear to me wether this Enumeration and foreach enhancements will generalize over Collections AND arrays. That's a thing that I think is very elegant in C#.
    It removes the necessity for a lot of wrapping and converting between arrays and collections.

    By the way: I think it's great Sun is polishing java with these enhancements. This way java remains to me an exciting environment.

    Groeten,
    Joost