Follow Slashdot blog updates by subscribing to our blog RSS feed

 



Forgot your password?
typodupeerror
×
Java Programming

Summary of JDK1.5 Language Changes 839

An anonymous reader writes "Over at java.sun.com, there's an informative article about the new features in JDK1.5. Some of the changes like generics are nice and should make some things easier. Some of the enhancements to me are purely sugar, like enumerators. When it comes down to it, once the code is compiled, it's the same. The thing I hope is, some of this new syntactic sugar doesn't result in more obfuscated code. Unlike some people, I feel using programming shorthand leads to increased maintenance. This is especially true when you have to debug a complex application."
This discussion has been archived. No new comments can be posted.

Summary of JDK1.5 Language Changes

Comments Filter:
  • enumerators (Score:4, Insightful)

    by billnapier ( 33763 ) <napier@pob[ ]com ['ox.' in gap]> on Friday May 09, 2003 @12:50PM (#5919637) Homepage
    enumerators are much better than just plain ints. Even though they may compile to the same thing, the compiler can do a little more checking on the enumerators, since it know the valid ranges for the enumerator so you don't have to explicitly check the range. You do check to make sure you get passed a valid value for all your int-as-enumerators? Don't you?
    • Re:enumerators (Score:4, Informative)

      by customiser ( 150740 ) on Friday May 09, 2003 @01:18PM (#5919877) Homepage
      It's good to see enumerators formally supported, but you were not really _forced_ to use plain ints up to now. It is just some sort of an anti-pattern, which everybody seems to be using happily.

      The type-safe enum pattern shows the correct way of handling enumerations. And you can the Jakarta Commons Lang library [apache.org] to make it a bit easier.
    • Re:enumerators (Score:5, Interesting)

      by iabervon ( 1971 ) on Friday May 09, 2003 @01:42PM (#5920145) Homepage Journal
      They're actually objects (you can put them in collections, for instance), they can have fields, methods, and constructors, etc. It's just that the compiler takes care of creating the instances and all, plus you can use them in swtch statements because the compiler knows they're enumerated.

      Evil thought: you could get relatively nice-looking static instances with methods if you combined enums with anonymous inner classes...
    • Re:enumerators (Score:5, Interesting)

      by ProfKyne ( 149971 ) on Friday May 09, 2003 @02:13PM (#5920469)

      I don't use ints for my enumerations anymore after reading Josh Bloch's Effective Java. The type-safe enum pattern he recommends is fantastic.

      For those not sure exactly how it works, you simply create a class to represent an instance of the enum, and you make the constructor private so that no one can create their own instances. Then you just provide a public static instance of the class for each enum.

      I used this pattern simply to achieve its intended effect of providing an enumeration, and then later found that by adding methods to the class, I could even give behaviors to the enumeration instances! Try doing that with an int. This was far more elegant than creating a giant "if" statement and performing conditional logic to test the value of the enumeration, because I simply used a polymorphic method call.

      An example:

      public class SenseEnumeration {
      // the action associated with this enumeration
      private java.lang.reflect.Method sense;

      private SenseEnumeration(Method m) {
      this.sense= m;
      }

      // assuming we've already created some
      // Method instances to use here
      public static SenseEnumeration TASTE
      = new SenseEnumeration(myTasteMethod);
      public static SenseEnumeration HEAR
      = new SenseEnumeration(myHearMethod);
      public static SenseEnumeration SMELL
      = new SenseEnumeration(mySmellMethod);

      ...etc...

      public Method getSenseMethod() { return this.sense; }
      public void invokeSenseMethod(Object target) {
      sense.invoke(target, null);
      }
      }

      You get the main idea. No, not as fast as an int, but far more powerful.

      • Re:enumerators (Score:5, Interesting)

        by slagdogg ( 549983 ) on Friday May 09, 2003 @02:17PM (#5920512)
        This is a fine alternative ... but cumbersome, and indeed once you add the toString() methods and other such niceties, it's approaching messy. The fact that a single statement now can offer all of these features is outstanding.

        It's nice to see Java stealing something from C# for once ;)
  • Generics (Score:3, Interesting)

    by boxhead609 ( 671383 ) <prowe2@yahoo.com> on Friday May 09, 2003 @12:52PM (#5919654) Homepage
    I think Generics is going to be a really nice long awaited feature. I am wondering if this type of change is going to require a modification to the bytecode specification. If that is the case, then new code bytecodes will not work with older bytecodes. Does anyone think that Sun can pull this feature off without a change to the bytecode spec? Would this be major compiler change?
    • Re:Generics (Score:5, Interesting)

      by gray peter ( 539195 ) on Friday May 09, 2003 @01:03PM (#5919738) Homepage
      Agreed that it's a great feature. I use collections all the time and not only is it time consuming to keep casting (especially when you write out long class names like I do...) I'd say a huge % of my runtime errors are from bad casting. I'm definitely looking forward to this. As far as the bytecode specs go, I don't see that this will cause much change at all. The compiler should do the same thing it's always done.
    • Re:Generics (Score:5, Informative)

      by blamanj ( 253811 ) on Friday May 09, 2003 @01:23PM (#5919939)
      No bytecode changes are required. There have been "test" implementations out since Java 1.2. You can get the current 1.3 release at [sun.com]
      http://developer.java.sun.com/developer/earlyAcc es s/adding_generics/
    • Re:Generics (Score:3, Insightful)

      by forgoil ( 104808 )
      It looks like Java's generics are much like C++'s templates. This means that it is a compiler feature, and not a runtime feature. This is not a step forward, but a way to keep the VMs still working. A trade off.

      For some interesting words on generics, and implementation for both Java and M$ CLR take a peak at this link:

      http://msdn.microsoft.com/library/default.asp?u r l= /library/en-us/dv_vstechart/html/vbconCProgramming LanguageFutureFeatures.asp

      All you "I hate M$" people out there will more than likely
      • Re:Generics (Score:3, Insightful)

        by Mindbridge ( 70295 )
        It looks like Java's generics are much like C++'s templates

        No, they are not. In fact, they are very different. C++ templates are heterogenious (every parameter set means a new class, hence you get lots of additional classes); Java generics are homogenious (one class serves all parameters). C++ templates' requirements for the parameters are "as they come" -- the code is simply recompiled with the new parameter classes; Java generics' parameters need to implement interfaces/extend classes if a particular me

    • Re:Generics (Score:3, Interesting)

      by justins98 ( 316484 )
      I don't think it will require a bytecode change. I don't know the details of how it works, but my guess is that the compiler will simply insert the casts for you. For example, when you say:

      List<Foo> list = new ArrayList<Foo>();
      list.add( myFoo );
      Foo otherFoo = list.get( 0 );

      The compiler will interpret the second and third lines as if they said:

      list.add( (Foo)myFoo );
      Foo otherFoo = (Foo)list.get( 0 );

      It's a pretty elegant way to incorporate type-safe generics without imposing any changes on
      • Pretty close. For "list.add(myFoo)", it won't add a cast, because the type checker verifies that myFoo is-a Foo. The compiler will also add "bridge methods" for classes that implement a parameterized interface:

        class Byte implements Comparable<Byte> {
        ...
        public int compareTo(Byte obj) {
        return this.value - obj.value);
        }
        }

        The method compareTo is supposed to override the method in Comparable, which takes an object. So they create a bridge method that overrides it normally:

        class Byte implement

  • by GGardner ( 97375 ) on Friday May 09, 2003 @12:53PM (#5919661)
    I feel using programming shorthand leads to increased maintenance

    I agree. This is why I never create my own functions or methods. Evey program should be just one big function.

    • by NReitzel ( 77941 ) * on Friday May 09, 2003 @01:05PM (#5919758) Homepage
      During my time at telco, development costs were always a fraction of maintenance costs. Producing write-only code may be cute, and may cut back on other people using it, but it also cuts back on your own people being able to maintain it.

      Oh, do I agree, in boldface.
      • by radish ( 98371 ) on Friday May 09, 2003 @01:16PM (#5919862) Homepage
        Of course maintenance costs more than development, that's a given. But the thing which reduces maintenance costs is easy to read and understand code, coupled with good documentation.

        The ultimate removal of "syntatic sugar" would take you down to raw machine code. I do not believe that would be easier to maintain than Java, or pretty much any higher level language. The aim of syntatic constructs is (or should be) to make it easier for the developer to express the algorithm clearly. It's not about saving typing (unless we're talking perl) and not about being smart for the sake of it, it's about making it easier to read and understand.
        • by DunbarTheInept ( 764 ) on Friday May 09, 2003 @01:43PM (#5920149) Homepage
          The problem is that some syntatic sugar doesn't actually increase readability. Consider operator overloading. If your language has that, you can never again know what on earth is going on when you see x = y + z, unless you are aware of every operator overload which was used. Let's say y is a char* and z is an integer. Normally then the expression (y+z) would mean in C++ "a char pointer which points at the character at index 'z' of the string stored in y." But with operator overloading in the language, you can never be too sure. Maybe somewhere in the code the programmer thought it would be a good idea to say that char* plus int really means "convert the string to integer with atoi(), then add the integer second argument to it, then convert back to string form and return that."

          • The problem is that some syntatic sugar doesn't actually increase readability. Consider operator overloading.

            Maybe it's just me, but I think operator overloading is closer to syntactic poison than syntactic sugar ...
      • "Shortcuts" are not the problem. Stupidity is the problem. A good programmer, or at least a kind programmer, uses "shortcuts" so that somebody else can figure out what's going on without having to everything about an object.

        Enumerated types will save your ass the first time you change databases or some project manager adds a new "status level" in between DONE and FINISHED. They are much faster than using internalized strings, which is how I had been testing for this crap. Remember, once they hit the object code they're just constants anyway...

        Foreach was easily the coolest thing about C# when I started using it, indexers were the second, and the code they create is FAR more maintainable than for(Object o = someList.FirstItem(); o != someList.LastItem(); o = someList.NextItem()){ ...}.

        Automagic "boxing" is a beautiful thing for newbie coders...I have had to teach so many the difference between a Byte and a byte that it isn't funny. I intend to use it, too...we pass in and out of the classes for char, int, byte, bool etc so often it makes sense to have the compiler/VM do our dirty work for us.

        And generics...well, they look real queer in Java, where we've never used the syntax before. But they will save our behinds on reuse! Besides no doubt being faster, it will make more sense when typing collections of inherited objects. We have a BaseRecord class. We have an optimized BaseRecordColl class, usually full of different types of ChildRecord classes. If we can write the one collection class, and not have to explicitly cast each child op, it will save time, space, and hassle...and avoid calling the superclass methods of uncast subclasses!

        Metadata is the only ingredient here that seems like it could cause trouble, and if it does it will be because people are using it wrong. Java is not a language that inlines...that's the whole idea of the JIT...and with today's cut and paste GUI IDEs, there's no need for programmers to use the lazy C declarations of the past. If people start doing so because it's neat, just nip it in the bud. Find/Replace when the code hits your desk. Eventually they'll get the hint.
    • by eGabriel ( 5707 ) on Friday May 09, 2003 @01:14PM (#5919840)
      It's true that wading through 20 different ways of doing the same thing in one program can really be maddening, but within reason some of these shortcuts should exist, and should have from the beginning.

      Every language has idioms, and a programmer should use those idioms in preference to other allowable ways to do things unless they have a good reason. It's all just part of good style.
  • Agreed.. (Score:5, Insightful)

    by MilesParker ( 572840 ) on Friday May 09, 2003 @12:55PM (#5919671)
    ..Thought C# has some nice innovations, one of my big problems with it is that so many of its new 'features' are so much syntactic sugar. One of the big things I appreciate about Java is that there is typically onyl one right way to do something; a big change from C++ for example. Plus, modern IDEs like IntelliJ make it very easy to construct iterators and such [Ctrl-j itar..] That said, I don't think that the majority of the Java improvements are really sytactic sugar; things like generics will be very positve improvements. And its very important that Sun keeps up these improvements -- as long as they continue to be well thought out. Ideally we will continue to have a fairly state-of-the art language without any fluff.
  • by earache ( 110979 ) on Friday May 09, 2003 @12:56PM (#5919677) Homepage
    The metadata, auto-boxing, enhanced iteration looks like catch up with C#'s attributes, foreach, etc.

    Where are true properties though?
    • It sounds like C# uses a lot of stuff from Ada (and I'm sure countless other languages), but forgot to honor prior work. :-)

      Seriously, the "C# copied from Java/Java copied from C#" argument misses the point. There's a lot of prior work, and finding the right balance between usability and clutter is difficult. As much as I loved writing stuff like "for (value'range) do..." I would rather see a conservative approach to features since it's always easier to add stuff than remove it.
  • by hrbrmstr ( 324215 ) * on Friday May 09, 2003 @12:57PM (#5919683) Homepage Journal
    I remember - back in the day - when new language feature discussions weren't so contrived and "happy!"

    Q: What's wrong with happy/contrived Q&A "articles"?

    A: I was hoping you'd ask!

    While humor and a semi-light tone are good ways to make technical discussions accessible to more people, treating folks like children who need to be entertained and talked-down to does more to alienate professional developers than it does to attract new converts.

    Having said that, I am *really* looking forward to the "foreach" in 1.5 and the auto-boxing/un-boxing. While mucking with an established language is tricky - and potentially dangerous (from an acceptance p.o.v.) - the community process seems to be working out well for Sun and giving developers what they have wanted for years.

    Let's just hope that the next "preview" of new features is more in the style of traditional FAQ's.
  • by Rombuu ( 22914 ) on Friday May 09, 2003 @12:58PM (#5919689)
    When it comes down to it, once the code is compiled, it's the same.

    Hell, lets write everything on fucking Turing machines then.

  • by nother_nix_hacker ( 596961 ) on Friday May 09, 2003 @01:00PM (#5919709)
    I feel using programming shorthand leads to increased maintenance

    My code was hard to write to it should be hard to read. :)
  • by jameson ( 54982 ) on Friday May 09, 2003 @01:05PM (#5919760) Homepage
    Hi,

    FYI: Generics are _much_ more than mere syntactic sugar (as are enumerators, a weak form of algebraic datatypes, if handled type-correctly).
    These are actually the kinds of things that make program maintenance considerably easier, since they allow more concise specifications of intended semantics to be done. No longer having to typecast (and thus expect run-time exceptions) when using a "vector of FooObjects" gives more power to the type checker, and thus allows a much richer class of programming errors to be detected at compile-time. This is the one major improvement in Java that's been missing since its very inception.

    But note that "generics" or "parametric types" have been present in languages such as Eiffel or Sather for well over a decade, and for much longer in ML. In a way, it's embarrassing that such an essential feature was added this late during development.
  • Uglification? (Score:5, Insightful)

    by oblom ( 105 ) on Friday May 09, 2003 @01:05PM (#5919763) Homepage
    Is anybody else irked by generics? One of the arguments in C++/Java discussion that I've read was: "Java removes complexity of C++, while remaining OOP". Well, generics remind me of C++ templates, which where a bit hard for me to swallow. Not to mention that attached to variable name doesn't make code any more attractive to look at.

    It appears that Java's way to solve run time errors is to screw the bolts as tight a possible during compile time. Will generics become THE way, or just remain one of the options?
    • Re:Uglification? (Score:3, Insightful)

      by ptomblin ( 1378 )
      I'm really looking forward to generics. I've got tons of code that casts the results from iterators or collections or maps. I've either got to test like hell and hope that I don't see any ClassCastExceptions and hope the testing was exhaustive, or I've got to do a lot of "instanceof" tests. Since 90% of the time when I use collections/maps I'm putting all of the same type in them, this just irks me.

      But for that other 10% of the time, remember that all classes are children of Object, so I'm betting you c
    • Re:Uglification? (Score:5, Insightful)

      by Anonymous Coward on Friday May 09, 2003 @01:27PM (#5919991)
      No, I'm not irked. Not even a little bit.

      If your only experience of generics is C++, then all you've seen is the *worst* implementation of generics ever done in a language. Template code is almost unreadable. (Have you ever tried debugging one of the STL implementations?)

      Besides, the lack of generic types cripples Java's ability to do static type checking, since your code ends up being full of things like this:

      Foo f = (Foo) vector.elementAt(i);

      where type errors can only be detected at runtime. That not only makes it impossible to detect errors at compile-time, it hurts performance at runtime.

      Check out how generics are handled in Modula-3 for to see a much better way to handle them than C++ templates, or look at ML for something even more groovy (ML uses polymorphic type inference instead of generics, so you don't even have to mention types - the compiler just does the Right Thing).

      Once you've worked with a good generic implementation, you'll never want to stop using them.

      Harry
    • Re:Uglification? (Score:5, Informative)

      by jameson ( 54982 ) on Friday May 09, 2003 @02:08PM (#5920423) Homepage
      Hi,

      Well, generics remind me of C++ templates

      They're not quite the same; C++ templates are essentially glorified preprocessor macros with
      some relatively small checking and a rather baroque
      underlying functional language. Generics are more
      concrete than that.

      Not to mention that attached to variable name doesn't make code any more attractive to look at.

      It would be really neat to have type inference there ;-)

      It appears that Java's way to solve run time errors is to screw the bolts as tight a possible during compile time.

      That's the idea, and that's also what I try to do when writing programs. Why should I have to write half a dozen test suites for some simple program property if the type checker can tell me whether it'll work right?

      Remember: Compilers don't do type checking just to optimise, but also to catch programming errors. And Generics allow you to catch a much more interesting class of these.

      -- Christoph
  • Retro... (Score:3, Interesting)

    by dance2die ( 596340 ) on Friday May 09, 2003 @01:06PM (#5919769) Journal
    These new java features or shortcuts whatever reminds of C++... Is Java going to come with "Pointer" manipulation features later on? Will java become the next C++ and will be extremely tidious to program with? Overall, change is good... :)
  • by Anonymous Coward on Friday May 09, 2003 @01:06PM (#5919773)
    Java adds four new syntaxes, Python's for loop, Perl type checking at compile time, something called 'metadata', and C enumerations, all of which impove compile time type checking at the expense of making the source code look and feel like perl.
  • by cheezfreek ( 517446 ) on Friday May 09, 2003 @01:07PM (#5919785)
    As a compiler writer, I found this sentence to be particularly hilarious:

    Because the compiler, unlike the programmer, never makes mistakes, the resulting code is also more likely to be free of bugs.

    That's right, none of us has ever seen bad code generation or an internal compiler error. But, he does have a point. The compiler is less likely to make a mistake than a programmer.

  • not just sugar (Score:4, Interesting)

    by Anonymous Coward on Friday May 09, 2003 @01:09PM (#5919796)
    I think the new additions are great (except, perhaps, the autoboxing stuff). But I'm missing a fix for that extremely common javabean convention: get/set methods.

    To add a property, say a String called name you have to write:

    /**
    * The name of this object.
    */
    private String name;

    /**
    * The name of this object.
    */
    public String getName() {
    return name;
    }

    /**
    * The name of this object.
    */
    public void setName(String name) {
    this.name = name;
    }

    That's 16 lines of code for one property! This is tedious to write, and more importantly, very hard to read when you have many properties.

    This could easily be reduced to something like:

    /**
    * The name of this object.
    */
    property String name;

    expanded to exactly the same code as above by the compiler. Incredibly useful if you're, say, writing a lot of value objects in a j2ee scenario.
    • by MilesParker ( 572840 ) on Friday May 09, 2003 @01:29PM (#5920012)
      AC, I agree that the current approach is a PITA. I would also be very happy to see a more terse way to express properties. But what you are doing in your example, is throwing the baby out w/ the bathwater.

      Note that you now don't have anyway to specify access and protection! I had given a little thought to better ways to handle this, and even had an interesting brief email exchange w/ a C# engineer about it. For the protection aspects you could do something like [this is just a quick idea I cam up with:]

      property access String name;

      where access is one of {read, write, readwrite}

      But note taht right away you have a problem -- no way to assign protection levels to the various access, which is really a cross-product. What happens for example if you want the getter to be public, but the setter to be private?

      Also, note that you would also need semantics to handle overriding the property accessors. You could just say that the property access defines an equivalent to the getter and setter methods, but that can get weird and confusing very quickly. Think about the situation where you have an interface defining getters and setters and then you implement it by just providing the one-line property definition. That would not be very transperent TSTL.

      All this is just to say that it is a noble goal, but not as trivial as it sounds at first glance. IMO, the C# "solution" is particularly ugly, and qualifies strongly for the "syntactic sugar" label.

      FInally, as in my other note, good IDEs like IntelliJ provide very convenient ways to auto-generate these things. I care much less about this issue now that I am not having to type all this stuff out by hand!
    • Re:not just sugar (Score:3, Informative)

      That's 16 lines of code for one property! This is tedious to write, and more importantly, very hard to read when you have many properties.

      You really need to try a generating/refactoring IDE like Eclipse [eclipse.org]. I once held to the orthodoxy that if I needed more than emacs then something was broken in the language. I grew up on object systems like CLOS where if you wanted a getter or setter you just asked for it in the definition of a field. So at first C++'s lack of public read-only/private read-write vars ann

  • by Shamashmuddamiq ( 588220 ) on Friday May 09, 2003 @01:09PM (#5919798)
    Yes, I'd agree with that remark about shorthand programming. I thought it was funny when I was teaching classes at UIUC to see stuff like this from the students:

    #define FOREVER for(;;)
    #define BEGIN {
    #define END }
    #define ONE 1
    #define PUSHORT unsigned short *
    #define DONE goto end

    The first thing an amateur programmer does when assigned a new project in C/C++ is to go redefine the language and all the types. I scolded them for these kinds of things, knowing that once they were forced to read other people's code often that they would realize how stupid these kinds of things are. Unfortunately, once I started my career in embedded development, I quickly learned how stupid I must have been to think that people left these behaviors behind in college... (all the above examples are taken from "professional" code that I've seen in the last few weeks)

    • Redefining the language to better meet the problem is one of the hallmarks of good (artistic) programming. And it has other purposes. To give you one:

      #define NOTHING ;

      ...
      if ((flag & VAL1) || (flag & VAL2)
      NOTHING;
      else
      ...

      I know I can change this to eliminate the empty
      ';', but I choose not to, because I feel that the conditional reads better as a positive statement.

      [I also prefer to have the '<' or '>' in a compound conditional always point the same way:

      (5 <= x) && (x <= 1
      • by divec ( 48748 )

        As to BEGIN and END -- I have coded with C (pre-ansi) on machines whose keyboards didn't have '{' and '}'. I had to construct an include file to define BEGIN and END with a binary editor. But it worked.

        Interestingly, ISO C defines shorthands for people with crap keyboards. You can type <% instead of { and %> instead of }. Also:


        <: means [
        :> means ]

        %: means #
        %:%: means ##


        You get even more if you include iso646.h. Of course, the old compiler you were using may not have had thes

      • I know I can change this to eliminate the empty ';', but I choose not to, because I feel that the conditional reads better as a positive statement.

        At the cost of failing to compile

  • by Fnkmaster ( 89084 ) on Friday May 09, 2003 @01:15PM (#5919853)
    I gotta say, I'm positively impressed. C# and Java are feeding features off of each other. Iterators, enumerators and autoboxing/unboxing - hmm, I think I've seen those before. Java 1.5 starts to look more and more like C#.


    Some of this other stuff has been going on for ages - I'm curious about the metadata/declarative programming features. I've developed complete code generation systems for Java - the number of situations that require reams of very repetitive code in your average large-scale Java app is huge, and much of that can be automated. It would be great to see a consistent, standard system for doing this built in as a language feature rather than having hundreds of home-rolled systems everywhere, but the nature of many problems lends themselves to home-rolling. I can't tell you how many times I've written simple SAX parsers that spew out Java code, and rolled up an ant target to run it on some schema and package up the result. It's not clear from this brief example whether this is only for XML/RPC or whether there's an extensible metadata system that you can build on top of.


    Then again, we should be careful not to roll too much into the language itself. I think generics, autoboxing, and enumerators are fabulous. Iterators I could give less of a shit over. Other stuff is great, but I question whether extending the language is the right mechanism. Much of the power and flexibility of Java comes from its simplicity. And most importantly, the ease of reading other people's code - there's far less stylistic variation because there are only N ways to do a task, rather than N! ways to do it, like in C++ (don't get me wrong, for a lot of tasks, I'd never dream of doing them in Java, like 3D programming). But it takes me about 1/4 to 1/3 the time to assimilate and learn a new Java API or library as it does to learn your average C++ API or library, and that's the appeal of Java.


    Of course, I'll be thanking the gods that I never have to deal with the fugliness of casting and wrapping to move stuff between typed arrays and untyped Lists again.

  • Enumeration classes (Score:3, Informative)

    by coyote-san ( 38515 ) on Friday May 09, 2003 @01:23PM (#5919943)
    This isn't the forum for a detailed discussion, but I actually prefer enumeration classes now over simple enumerations. The basic idea is to write a class something like:

    final class Color {
    String c;

    private Color (String color) { c = color; }
    String toString() { return c; }

    static final Color RED = new Color("red");
    static final Color BLUE = new Color("blue");
    static final Color GREEN = new Color("green");
    }

    You can then treat this class like a type-safe enumeration. It doesn't have all of the nifty features that you'll see in languages like Ada, but it has the nice property of allowing you to attach whatever information you want to the enumeration class.

    You can also use this approach to create self-initializing classes, e.g., a list of states (including full name, postal abbreviations, shipping zone, etc.) from a database. You can access the enumerated values through a collection class, a "lookup" method, or even reflection.
  • by dood ( 11062 ) on Friday May 09, 2003 @01:23PM (#5919947)
    One of the coolest new features of JDK 1.5 is the completely reworked concurrency stuff (JSR 166). I just listened to Doug Lea (spec lead) give a talk on this very subject and I'm pretty convince this will rocket Java performance way up for a lot of the collections stuff, concurrent programming, etc.

    Bascially, the goal of JSR 166 is to do for concurrency programming what JDK 1.2 did for data structurs (Collections stuff). The gist is, you'll never need to use "new Thread()" or "synchronized" anymore, but rather you'll execute Runnables, use Locks and Semaphores, etc. Also, queues are *completely* reworked to be ultra scalable.

    JSR 166 is based on Doug's concurrency package:
    http://gee.cs.oswego.edu/dl/classes/EDU/ oswego/cs/ dl/util/concurrent/intro.html

    OH, and there will be classes like AtomicLong which guarantee atomic 'compare and set' options for primitives. :)

    Cheers!
  • by lkaos ( 187507 ) <anthony@codemonk ... s minus math_god> on Friday May 09, 2003 @01:28PM (#5920005) Homepage Journal
    Generics
    The new Java generics are really weak compared to C++ template support. This is probably partially due to difficult in compiler support and also complexity (templates are without a doubt the most complex feature of C++). I was disappointed though in Java generics mainly due to lack of any kind of specialization support and also about the strange paradigm used for Iterators (instead of an iterator being class defined with a consistant interface, it's an external class that just behaves that must wrap a behavior around the class).

    Enhanced for loop
    This is for_each() in C++. Now, with for_each, you have to use function objects which is arguable as to whether it's more readable. Fortunately, Boost has developed a boost::lambda class that allows for code to be used as the third parameter. This is _really_ neat.

    Autoboxing/unboxing
    I presume this means that primatives can't be used in generics.. That's kind of sad. This isn't a problem in C++.

    Typesafe enums
    This would be a nice linguistic pattern to have in C++. As it stands, the equivalent would be:

    struct Coin { enum { penny, nickel, dime, quarter }; };

    Static import
    This can be achieved via using in C++. Of course, Java doesn't even really have a namespace paradigm so it's not really a fair comparision.

    Metadata
    This is.. well.. strange. I didn't see the syntax for doing something like this. If it is just keyword/code replacing, then an #include directive would work just as well.
    • by TummyX ( 84871 ) on Friday May 09, 2003 @02:24PM (#5920578)

      Metadata
      This is.. well.. strange. I didn't see the syntax for doing something like this. If it is just keyword/code replacing, then an #include directive would work just as well.


      IMO, metadata is the coolest thing. It's a feature of C# which has had little recognition despite its coolness.

      In both Java and C# you can use reflection to find out information about a class (class name, method names, etc). Attributes/metadata allow you to attach information to just about every element of a class/struct so that it can be queried dynamically using the reflection apis.

      Imagine them as JavaDoc tags that aren't discarded at compile time but are instead compiled into a class's meta data. They'll do for source code what XML did for HTML -- give more meaning to the code.

      Here's an example of using attributes/metadata to simplify XML serialization:
      [XmlRoot("cat")]
      public class Cat
      {
      [XmlAttribute("id")]
      public string Name;

      [XmlElement("color")]
      public string Color;

      public Cat()
      {
      }

      public Cat(string name, string color)
      {
      this.Name = name;
      this.Color = color;
      }

      public static void Main()
      {
      Cat cat = new Cat("felix", "yellow");

      XmlSerializer serializer = new XmlSerialzer(typeof(Cat));

      serializer.Serialize(cat, Console.Out);
      }
      }

      The code yields the following output:

      <cat id="felix">
      <color>yellow</color>
      </cat>
      The C# XmlSerializer class dynamically generates the IL that will do the serialization so it is *very fast*. It knows how to map the field names to element/attribute names by inspecting the attributes.

      Some other obvious uses include object/relational mapping (no need for external XML mapping files) and XMLRPC (just mark a method as Remotable!) etc. You can imagine infinite other uses for attributes/metadata.

      I'm not sure how it works in Java but in C#, attributes are simply classes (usually with a name ending in 'Attribute'). You can define your own custom attributes and your own classes that work with them. It's very cool.
    • This would be a nice linguistic pattern to have in C++. As it stands, the equivalent would be:

      struct Coin { enum { penny, nickel, dime, quarter }; };


      Not equivalent, the Java version also supports writing as a String ... so the below statement produces the string "coin: PENNY" which is very, very handy.

      System.out.println("coin: " + Coin.PENNY);
  • by Q Who ( 588741 ) on Friday May 09, 2003 @01:36PM (#5920080)

    This is what he said about Java [att.com] and the [att.com] likes [att.com].

    Also here [eptacom.net].

  • by MarkWatson ( 189759 ) on Friday May 09, 2003 @01:51PM (#5920223) Homepage
    I have complained here before on this issue:

    One of things that makes older more mature languages like Common Lisp (and perhaps Smalltalk) nice to work with is a feeling of both having really solid implementations and not breaking legacy code.

    I like the idea of boxing and generics, but, these changes will affect old code (probably?) and the platform in general.

    My vote would be to freeze the Java language (perhaps after 1.5) and concentrate on the following:

    • memory footprint
    • runtime efficiency

    I would not like to see Java become a language designer's playground.

    Because of great infrastructure software like servelt/JSP containers, (perhaps EJBs :-), XML utilities, solid web services support, etc. Java is a great platform.

    Leave it alone (the sooner the better) except for improvements in the implementation.

    -Mark

    • by _fuzz_ ( 111591 ) <meNO@SPAMdavedunkin.com> on Friday May 09, 2003 @03:21PM (#5921179) Homepage
      My vote would be to freeze the Java language (perhaps after 1.5) and concentrate on the following:

      * memory footprint
      * runtime efficiency ...

      Leave it alone (the sooner the better) except for improvements in the implementation.


      This is a good idea. However, my vote is to concentrate on Java3. Screw backwards compatibility going forward and fix the standard library. Throw out the crap that has come along from JDK 1.0-1.1 and make the platform consistent. Why do we have both Enumerations and Iterators? Why are constants mostly UPPERCASE but sometimes lowercase (see java.awt.Color)? What about Thread.stop()?

      This cruft is never going to go away until Sun releases a version of Java that isn't backwards compatible. Perl and Python do it. Java should too. It makes for a much cleaner language for new projects. Old projects may get stuck on a Java2 platform until the owners invest the time to convert them, but that's the way things go. It's time to clean out the cobwebs in Java and make better use of the new features.

      Once all the old crap is gone, then it will be time to freeze the language and standard library.
  • by Henry Stern ( 30869 ) <henry@stern.ca> on Friday May 09, 2003 @01:52PM (#5920240) Homepage
    I've been using Java for most of my projects for years because it didn't let you get away with many of the confusing things that you can do with a preprocessor. I may sound like a big geek for this, but I was actually weeping while I read the article. JDK 1.4 broke the ice with the assert keyword and now everything bad about C++ is going to pollute Java.

    To the many cooks who spoiled the broth: "Thanks a lot, assholes."
  • by axlrosen ( 88070 ) * on Friday May 09, 2003 @01:54PM (#5920264) Homepage
    ... but man do I hate the enhanced for-loop syntax. At some point you have to give up perfect backwards-compatibility for readability. One or two new keywords would do a world of good.

    for (TimerTask task : c)
    task.cancel();

    becomes

    foreach (TimerTask task in c)
    task.cancel();

  • by mrpotato ( 97715 ) on Friday May 09, 2003 @02:30PM (#5920646)
    " I feel using programming shorthand leads to increased maintenance."

    False.

    Shorter code and more powerful idioms makes a program *easier* to debug.

    Too much code makes the purpose lost in the noise. Consider:

    foreach (@array) {foo $_};

    and

    my $i;
    for ($i = 0; $i < $#array; $i++)
    {
    foo $array[$i];
    }

    (I use Perl here since it is well known and I can show the 2 idioms, but really Perl isn't the clearest language of all). One form is much clearer and reveal much more eloquently what is the intent of the code.

    Of course, this doesn't mean that shorter code "at all cost" is easier to debug, it means that "less code" is better.

    Oh, and also it pisses me off when management tells me I need to use only certains idioms in case someone comes over my code and don't understand it. I hate to have to program like the next maintainer will be clueless and ignorant.
  • by autopr0n ( 534291 ) on Friday May 09, 2003 @02:33PM (#5920685) Homepage Journal
    It's interesting the problem they were having with unboxing. Right now a null pointer would return a int value of zero, rather then throwing an error.

    Actually, I think that's a bad idea, since you wouldn't be able to tell a zero you put in a collection with one that you didn't. Personally I'd like to see this as an option, somewhere. perhaps as a parameter to Integer, so you could do Integer<0> or Integer<null> to chose the behavior of the class. The problem there is that it's not obvious what a parameter to integer would do. Although I suppose you could use an if statement.

    Personally, I wished they would have thought up a more interesting way to do generics then the C++ model. I wonder if this is going to give us the full range and power of C++ templates in java.
  • by LogicHoleFlaw ( 557223 ) on Friday May 09, 2003 @02:49PM (#5920864) Homepage
    You know, I've just got to say this.

    Each and every point on this list of additions to the languages addresses problems that I have personally run into in my use of Java at work. These things will make the writing and maintenance of java projects small and large much, much easier.

    Generics: Thank you God, yes! Having to explicitly cast objects out of Containers is tedious and error-prone.

    Iterators/Enhanced 'for': Make iteration much easier to read and understand.

    Autoboxing/Unboxing: This helps alleviate the enormous kludge that is the Object/primitive dichotomy. Casting to and from wrapper types just to pass ints, etc. around really sucks.

    static import: Not having to fully specify tedious class names to access static members is a big boon for making stuff digestible and easy to read.

    Metadata: Writing boilerplate sucks the big one. How many hours have I lost writing boilerplate? Way too many. Having language support for generating code from the metadata cuts my implementation times way down.

    I could sit here and argue with folks about the 'new Java' versus C++ or C# or Smalltalk or whatever endlessly. But man, these things sure make Java a whole lot more pleasant to use.
  • In the old days when people talked about Linux, there was an expression "What about the big pink elephant in the middle of room" and it was referencing the fact that Linux did not support truetype fonts and font aliasing. Now some of that has been fixed, but Java still has its big pink elephant. Here are some of the things that people don't talk about.

    The memory foot print for loading Java is 20meg + and growing. I am part of a team that has been developing a complex Java application for the last few years and we have created about a 3meg library (and it probably does at least as much as the more popularily used Java classes). I have looked at some of the source code for the core Java libraries and it is clear that a good rewrite could reduce this footprint by a factor of 2 to 4. Currently, C# loads with a footprint of 2 meg to 4 meg. Most other scripting languages usually have engines that are about the same size. To put it simply, the base core Java libaries are unjustifiably large. Maybe if Java were truly open source this could be addressed, but of course Sun doesn't even believe in submitting Java to a standards board.

    You cannot load the Java VM once and run multiple processes (note "processes", not "threads") from the same Java VM memory footprint. I hear that such a thing is becoming possible for C# on Linux. You would have to build all the core Java classes into a "DLL" or ("so" on Linux), but that shouldn't be so difficult.

    You still cannot do basic OS operations in Java without writing your own JNI library. The one that stands out is the inability to get the ID for the current running process. The "nio" package has corrected some of these issues, but the "nio" package should be the "io" package instead of having two separate packages (similar to AWT vs. Swing).

    Window focus handling is still terrible. Ever have two frame windows up, have a modal dialog pop up on one frame while you were looking at the other? The frame window without the popop modal dialog becomes unresponsive and the other frame cannot be reached by tabbing through the windows. Only if you are lucky and that window is still visible on your desktop can you successfully reach it. Also, if a user clicks on a button that generates a modal dialog, the frame is only locked out from user input once the dialog manifests. This creates the infamous "double" clicking problem.

    Java's package management is still primitive. If you want to do anything more subtle then using the classpath to load in custom libraries, you have to write your own class loader. Having an auxillary file specifying parameterizable rules for class loading would be nice. It would also be nice if you could ask a running Java process what packages it had loaded (and metadata about them such as location and version). Compare this to C# (or the way some of the web server oriented scripting languages work).

    Some of the basic core library functions have some major weaknesses. For example, the Hashtable should be written as a native object when using String lookup keys and also allow you to dictate the algorithm for creating hashes (ex: use first 8 characters, last 8, or middle 8). There should also be a non thread safe version as well as a thread safe version. The lack of such a natively implemented primitive object is one of the big reasons why some less cleverly implemented scripting languages (such as python) can beat Java in performance on many web applications. In general, the core collection classes should be implemented in pure optimized (down to the actual chosen assembly code) native code.

    Many of the utility libraries are broken in fundamental ways. Send back a badly formed response to the HTTP library and you go into an infinite loop when it falls into its keep-alive/retry logic. Date parsing is still behind what is available in the C standard library. Locale specifications do not allow you to independently specify date formats, language, floating point format, currency format, and time zone. You get o

Love may laugh at locksmiths, but he has a profound respect for money bags. -- Sidney Paternoster, "The Folly of the Wise"

Working...