Joshua Bloch on New Language Features in J2SE 1.5

Discussions

News: Joshua Bloch on New Language Features in J2SE 1.5

  1. Metadata, Enumerations, Generics, static import, and other new features slated for the Tiger (the J2SE 1.5) release late this year are explained and illustrated in a new interview with Joshua Bloch on java.sun.com. "Above all else, Tiger is a developer-focused release."

    Read A Conversation with Joshua Bloch on java.sun.com, published on May 8th (yesterday).

    Of course, TheServerSide brought it to you first with our Tech Talk with Joshua Bloch posted in April.

    Threaded Messages (48)

  2. Metadata[ Go to top ]

    The example they give:
    . . public class CoffeeOrder {
    . . @Remote public Coffee [] getPriceList() {
    . . ...
    . . }
    . . @Remote public String orderCoffee(String name, int quantity) {
    . . ...
    . . }
    . . }

    is fairly simple, but how does it handle more complex metadata? For instance, this XDoclet meta data example for EJB classes was taken from the XDoclet website:
    /**
     * This is the Account entity bean. It is an example of how to use the
     * EJBDoclet tags.
     *
     * @see Customer
     *
     * @ejb.bean
     * name="bank/Account"
     * type="CMP"
     * jndi-name="ejb/bank/Account"
     * local-jndi-name="ejb/bank/LocalAccount"
     * primkey-field="id"
     *
     * @ejb.finder
     * signature="java.util.Collection findAll()"
     * unchecked="true"
     *
     * @ejb.transaction
     * type="Required"
     *
     * @ejb.interface
     * remote-class="test.interfaces.Account"
     *
     * @ejb.value-object
     * match="*"
     *
     * @version 1.5
     */
    How would this be coded in the new metadata be coded in Java 1.5 metadata?
     * @ejb.bean
     * name="bank/Account"
     * type="CMP"
     * jndi-name="ejb/bank/Account"
     * local-jndi-name="ejb/bank/LocalAccount"
     * primkey-field="id"

    Would is look roughly like this?
    . . @EjbBean( name="bank/Account", type="CMP", jndi-name="ejb/bank/Account", local-jndi-name="ejb/bank/LocalAccount", primkey-field="id")
    . . @EjbTransaction(type="Required")
    . . @EjbInterface(remote-class="test.interfaces.Account")
    . . @EjbValueObject(match="*")
    . . public class Account {
    . . ...
    . . }

    Or could it be grouped into something more sane like this so you wouldn't have to worry about namespace issues?
    . . @Ejb{
    . . . Bean( name="bank/Account", type="CMP", jndi-name="ejb/bank/Account", local-jndi-name="ejb/bank/LocalAccount", primkey-field="id")
    . . . Transaction(type="Required")
    . . . Interface(remote-class="test.interfaces.Account")
    . . . ValueObject(match="*")
    . . }
    . . public class Account {
    . . ...
    . . }
  3. Metadata[ Go to top ]

    It would look like your first example.

    Keep in mind that the syntax we are trying to come up with has to be very close to Java's syntax.

    --
    Cedric
    http://beust.com/weblog
  4. Metadata[ Go to top ]

    Keep in mind that the syntax we are trying to come up with has to be

    > very close to Java's syntax.

    Then why are you using that butt ugly '@' sign syntax? wouldn't a keyword like 'meta' be much more Java-like?

    /T
  5. Metadata[ Go to top ]

    Then why are you using that butt ugly @ syntax? wouldn't a keyword like 'meta' be

    > much more Java-like?

    Absolutely, but I understand the reluctance to adding more keywords into the language. Every new keyword breaks code. The new "assert" keyword, for instance, would break all code that used custom assert.

    Personally, I feel that languages like Troff, Latex, Lisp, XML, and HTML have the right idea about keywords -- it's possible to distingish between what's a keyword (a.k.a. macro or command) and what's a identifier just by looking at the program. For Troff, you prefix all macros with a period. With Latex, you prefix them with a backslash. With Lisp, XML, and HTML, you specify that the first element in the "list" (although it's not called that in XML or HTML) is the keyword.

    If all new Java extentions used this keyword convention, then Java designers wouldn't have to worry about adding new keywords. Assert, for instance, would be written as one of:
    @assert expr1 : expr2
    :assert expr1 : expr2
    `assert expr1 : expr2
    \assert expr1 : expr2
    [assert] expr1 : expr2

    and the new foreach could be written as one of:
    @foreach(Object @in collection)
    :foreach(Object :in collection)
    `foreach(Object `in collection)
    \foreach(Object \in collection)
    [foreach](Object x [in] collection)

    and the new metadata proposal would be written as
    @meta Remote public Coffee [] getPriceList()
    :meta Remote public Coffee [] getPriceList()
    `meta Remote public Coffee [] getPriceList()
    \meta Remote public Coffee [] getPriceList()
    [meta Remote] public Coffee [] getPriceList()

    The above approach makes adding keywords ugly (so most likely it'll be avoided whenever possible, like in the case of the foreach), but when adding a keyword is the best solution, the above approach makes adding them possible without breaking old code.

    However, despite the advantages of this approach, it's unlikely it'll be adopted by any JSR because the look and feel is foreign to Java. Even if it were adopted, the syntax looks so alien (even it it's more readable) Java users would likely balk at it.

    So for better or worse, JSRs will have to live with the "don't add a keyword unless absolutely necessary" rule.
  6. Metadata[ Go to top ]

    With the new metadata approach, is the intention to do away with deployment descriptors for EJB's altogether?

    If so what will they be replaced with?

    Cedric tells me that ejbgen supports a properties file for runtime metadata, will the new metadata approach tackle the issue of euntime meta data. For example, the last place I want to put the JNDI name for a bean is in the implementation class, because I may want to deploy more than once with different settings - and so I'd need different JNDI names to distinguish between them.

    Where would stuff like weblogic sepcifc descriptor settings go?

    What does XDoclet do with runtime properties? From what I see all DD stuff gets placed in the implementation class in XDoclet, so what happens if you are support softwrae that gets deployed to many app servers, versions, ejb versions etc? Do you end up with an implementation class so full of metadata you can't see the code? Can ejbgen/XDoclet/metadata cope with multiple deployments across app servers, versions and EJB versions?

    How will the new metadata approach support app server specific deployment settings?

    What's the advantage of the properties files over the current deployment descriptor approach?

    Is the idea with metadata to generate component and home interfaces from the metadata as ejbgen and XDoclet do? If so, how will I tell metadata that I want to use the business interface pattern as opposed to placing my business interface methods directly in the component interface?

    I have so many questions, I wonder whether I'm completely missing the point. I would really appreciate an explanation.
  7. Metadata[ Go to top ]

    With the new metadata approach, is the intention to do away with deployment

    descriptors for EJB's altogether?

    This is outside the scope of JSR 175, so I can only give you my personal opinion.

    Obviously, all tools using JavaDoc tags to generate deployment descriptors will most likely switch to the JSR 175 syntax.

    > Where would stuff like weblogic sepcifc descriptor settings go?

    I don't think this has to do with the fact that a descriptor is proprietary, but rather its semantic: is it a runtime or a deployment time descriptor?

    As I already said in a previous thread, descriptors tied to a Java element should go in the source but anything else is better put in a separate file.
     
    --
    Cedric
    http://beust.com/weblog
  8. This scares me.[ Go to top ]

    <cedric>Obviously, all tools using JavaDoc tags to generate deployment descriptors will most likely switch to the JSR 175 syntax.</cedric>

    This scares me. It sounds like the death knell of java. Obviously all the existing programs should be broken or bent into shape to meet some theoretical committee compromized ideal of perfection. It's happening all over too. Core java wants to annex popular existing idioms, twists them to be something slightly different, poorly implements them, making mistakes by not understanding their full use. Asserts, logging, jstl, jdo, and meta data are all less than they could be--and already are, implemented in, yes, nonstandardized, but commonly used applications and libraries.

    They're scared to death about breaking some imagined foreach variable name in someone's obscure never-to-be-recompiled code, so they concoct a new punctuation syntax. Truly straining at a gnat and swalling a camel
  9. Metadata[ Go to top ]

    What does XDoclet do with runtime properties? From what I see all DD stuff gets placed in the implementation class in XDoclet, so what happens if you are support softwrae that gets deployed to many app servers, versions, ejb versions etc?

     
    XDoclet takes values from Ant script, which can get them from properties file. I suggest using several <release_name>.properties files to store release specific data, in this case doing multiple releases is a piece of cake: QA build
    ant build -Drelease=qa
     
    >>Do you end up with an implementation class so full of metadata you can't see the code?
    Use something more sophisticated than notepad( Intellij-IDEA for instance) and collapse javadoc comments.
     
    >>Can ejbgen/XDoclet/metadata cope with multiple deployments across app servers, versions and EJB versions?
    Yes.
  10. Adding new keywords[ Go to top ]

    Actually, sometimes adding new keyword doesn't have to break old code. foreach in 1.5 is a prime example.
    foreach(i in C) is unambiguously distinguishable (yuck, did I just write this?) from a method call foreach(i,c). It would require the parser to do a lookahed. While it would make the gramar a bit uglier, it would not be a major problem, and there's quite a few ugly things in Java grammar as it is.
    Regards,
    Vlad
  11. Metadata[ Go to top ]

    <thomas>
    Then why are you using that butt ugly '@' sign syntax? wouldn't a keyword like 'meta' be much more Java-like?
    </thomas>

    Maybe more Java-like but it would break a lot of Java programs.

    Adding a new keyword is unfortunately not an option.

    --
    Cedric
    http://beust.com/weblog
  12. Break Java -now![ Go to top ]

    <Cedric>
    Maybe more Java-like but it would break a lot of Java programs.

    Adding a new keyword is unfortunately not an option.
    </Cedric>

    Remember how HTML developed? Introducing tables and frames was easy, even moving to HTML 3.2. Moving to HTML 4.0 took years and XHTML creates more problems even with current browsers than it solves on the server side. Another example maybe worth looking at might be the rate of adaption of SQL:1999 features into existing SQL data bases.

    I think Java 1.5 will be the last chance to "break" the language. Because of .Net and lots of practical experience we know what needs to be fixed, how the language can be improved. If this requires breaking the JVM or adding new keywords then go for it. Otherwise all the deficiencies we think we could fix with Java 2 2.0 will stay forever until both Java and .Net get replaced in a couple of decades (think COBOL -> C/C++ -> Java/.Net).

    It might sound harsh, but at some point Java will have "to eat its own children" i.e. compatibility with previous language versions to keep the headstart it had when being introduced in May 1995. The only chance, in my oppinion, is to do it now - or never. The natural reflexes may tell us to stay compatible, but if we yield it will be the beginning of the end of Java instead of the next evolutionary step.

    Just my 2 cents - and please no Java vs. .Net flames as this is not the intended point of the posting, thanks.

    Valentin Richter
    Raytion GmbH
  13. I agree that now is the time to do some clean up in the language. I think the new <code>for</code> support for collections would have been much more readable if they introduced the new keyword <code>in</code>. I can understand the short term goal with not introducing new keywords because of compability, but this should be considered with the longterm gain of cleaning up the language syntax.

    So in the pragmatic programmer spirit: Don't live with these broken windows.

    ----Trond
  14. I agree that now is the time to do some clean up in the language.


    How about creating some catalog of Java’s broken windows?
    To start the list:

    - Classloader is a part of namespace ( myObj instanceof MyClass returns false if MyObj and MyClass were loaded by different classloaders);
    - Boolean.getBoolean(String name);
    - “some string”.(split|replace|matches);
    - (get|set)PropertyName – reliance on names to express semantic; IMO: ObjectPascal has much better way to deal with properties:
            property propertyName; read readFunction; write writeFunction;
    ……
  15. <Konstantin>
    - Boolean.getBoolean(String name);
    </Konstantin>

    Does exist.

    <Konstantin>
    - &#8220;some string&#8221;.(split|replace|matches);
    </Konstantin>

    String.{split,replaceAll,matches} do exist.

    Have you checked java 1.4 lately? You certainly should before posting in a java 1.5 related topic :-)
  16. <Konstantin>

    > - Boolean.getBoolean(String name);
    > </Konstantin>
    > Does exist.
    Since 1.x

    > <Konstantin>
    > - &#8220;some string&#8221;.(split|replace|matches);
    > </Konstantin>
    > String.{split,replaceAll,matches} do exist.
    Since 1.4

    Their existence is the problem!
    Did you check javadoc and know how Boolean.getBoolean(String name) works? If you think that it parses the given string and returns Boolean then you are very wrong….

    As for ‘string’.(split|replace|matches) – I do not feel that the method should exist on String class. I consider this to be a bad object design. Since there are others than RegExp based matches and splits are possible such methods should belong to specific libraries and do not pollute such core class as String. I would accept methods like split() on String class if I was able to subclass String and override such methods for my purposes.
  17. - Classloader is a part of namespace ( myObj instanceof MyClass returns false if MyObj and MyClass were loaded by different classloaders);

    That is correct, though. If you cast myObj to MyClass, you'll get a ClassCastException, thus instanceof SHOULD return false.

    Do you have a better solution? Particularly, since the JVM can load multiple versions of the same class which are potentially incompatible with each other?

    Peace,

    Cameron Purdy
    Tangosol, Inc.
    Coherence: Easily share live data across a cluster!
  18. - Classloader is a part of namespace ( myObj instanceof MyClass returns false if MyObj and MyClass were loaded by different classloaders);

    >
    > That is correct, though. If you cast myObj to MyClass, you'll get a ClassCastException, thus instanceof SHOULD return false.
    >
    > Do you have a better solution? Particularly, since the JVM can load multiple versions of the same class which are potentially incompatible with each other?
    >


    The problem is that the same class from the same library might be loaded by different classloaders in the same hierarchy and be incompatible with itself. Such things happen when a class gets instantiated dynamically (hibernate, commons-digester) and eventually gets compared with instance of the class, which was “statically” linked and loaded by another classloader.

    I do not have better solution, but have some idea:
    - this feature might be optional, same way as SecurityManager is optional.

    and feeling:

    - Classloading should be somehow standardized and simplified. Right now myObject.getClass().getClassloader().getResource() and , Thread.currentThread().getContextClassLoader().getResource() produce too much different results;
  19. Catalog of broken windows[ Go to top ]

    - Classloader is a part of namespace ( myObj instanceof MyClass returns false if

    > > MyObj and MyClass were loaded by different classloaders);

    > >
    > That is correct, though. If you cast myObj to MyClass, you'll get a
    > ClassCastException, thus instanceof SHOULD return false.
    >
    > Do you have a better solution? Particularly, since the JVM can load multiple versions
    > of the same class which are potentially incompatible with each other?
    >

    Essentially, what he's asking for it the equivalent of String.intern() for classloaders. Suppose X have the value "Foo". The comparison (X=="Foo") will return false if X wasn't internalized.

    If Classloaders had a way of internalizing a class (or importing it into a namespace, including the main classloader namespace), then ( myObj instanceof MyClass ) could return true if myObject was imported into the main class namespace. You raise a good point about versioning. If class internalization were possible, one of the requirements for success would be that the interfaces of all base classes and base interfaces cannot conflict with any other class in the classloader's namespace.

    Such a feature is pretty esoteric, but I suspect that it might help EJB container providers eliminate (or at least provide better diagnostics for) several of the issues that make using EJBs less obvious than they have to be.
  20. Class loading[ Go to top ]

    <robert>
    I suspect that it might help EJB container providers eliminate (or at least provide better diagnostics for) several of the issues that make using EJBs less obvious than they have to be.
    </robert>
    I agree. While the existing class loading approach has its own rationale, I think it can make developing EJB + WAR applications very hard at times, especially where Hibernate, Digester etc. need to load classes by name.

    Also, class loading behaviour varies widely between applications servers. This can pose portability problems, and it's a pity to have portability compromised for this reason.

    Rod Johnson, author of Expert One-on-One J2EE Design and Development
  21. Class loading[ Go to top ]

    Regarding diagnosing ClassLoader issues, see Application servers and that dreaded ClassCastException.

    Peace,

    Cameron Purdy
    Tangosol, Inc.
    Coherence: Easily share live data across a cluster!
  22. Break Java -now![ Go to top ]

    If I remember well, Java versions are labelled in the x.y.z style (J2SE 1.4.1 for ex.) and byte code compatibility is only guaranteed for releases of the same x version. So, what you propose would even not be again the spirit of Java, as thought out originally.

    Bertrand Fontaine
    INSPIRE IT - www.inspireit.biz
    JavaShelf.com: Your Java bookstore on the Web!
  23. Break Java -now![ Go to top ]

    Agree!!
  24. Break Java Now![ Go to top ]

    I think Java 1.5 will be the last chance to "break" the language. Because

    >of .Net and lots of practical experience we know what needs to be fixed, how
    >the language can be improved. If this requires breaking the JVM or adding new
    >keywords then go for it. Otherwise all the deficiencies we think we could fix
    >with Java 2 2.0 will stay forever until both Java and .Net get replaced in a
    >couple of decades (think COBOL -> C/C++ -> Java/.Net).

    I agree. Java has begun to show its warts and needs to be cleaned up. Too many lazy programmers at Sun have polluted the language and APIs with inconsistencies over the years.

    > It might sound harsh, but at some point Java will have "to eat its own >children" i.e. compatibility with previous language versions to keep the

    Wouldn't this really be "eating its own parents"? :-)

    -Jeff Smith
  25. Break Java -now![ Go to top ]

    No Dont. Dont break Java.

    Breaking Java, as any break with backwards compatibility, causes a lot of pain - and usually pisses off more people than it pleases.
    There is a balance between keeping up with the Jones's (CLR) and maintaining the stability that won Java its corporate adoption.

    Eventually, Java will be replaced by something better - and I think Java already has what it needs to survive until then. Adding new keywords is not going to lengthen its lifespan any appreciable amount.

    -Nick
  26. Metadata[ Go to top ]

    Better yet, why not use the C# notation?

    [remote]
    String sayHello(String name);

    -Nick
  27. Metadata[ Go to top ]

    It would look like your first example.

    >
    > Keep in mind that the syntax we are trying to come up with has to be very close to Java's syntax.
    >
    > --
    > Cedric
    > http://beust.com/weblog

    Are you on the expert committee? Why not keep the syntax the same as XDoclet. Why reinvent?
  28. Metadata[ Go to top ]

    Doesn't appear that it is going to look like this. Pain again with porting code from one platform to another?
  29. Metadata[ Go to top ]

    Doesn't appear that it is going to look like this. Pain again with porting code from

    > one platform to another?

    Well, J#'s Java JDK support remains frozen at Java 1.1.4 (see http://www.javaworld.com/javaworld/jw-11-2001/jw-1121-iw-jsharp.html). Since most Java apps depend on at least JDK 1.2, and most J# apps tend to call at least some of the .NET APIs or features (otherwise, why use J# instead of Java?), you'll already have compatibility problems.

    However, if you're happy limiting yourself to JDK 1.1.4 with no .NET API or .NET features other than J# attributes, you should be able to use an XDoclet-like tool to convert J# attributes into Java 1.5 attributes.
  30. Metadata[ Go to top ]

    I hardly doubt any development project would seriously consider porting Java code to J# or vice versa (jdk in its 1.1 version hardly meets current development requirements). However, I believe that with added metadata support, autoboxing, new for loop syntax in jdk1.5, tasks of porting Java code to C# will become somewhat easier.

    In most heterogeneous environments porting code is not as big of an issue as interoperability between both platforms (Java and .NET), ability to reuse knowledge, design principles, and system service APIs. It is more efficient to maintain one moderately sized development team that can easily support code bases for both platforms as opposed to two different teams for Java and .Net trying to resolve their differences on architectural, design, and coding levels.

    Regards,
    Dmitriy Setrakyan
    Fitech Labs, Inc.
    xNova™ - Service Oriented Architecture for Java and .NET
  31. Metadata[ Go to top ]

    I understand a draft will be available soon, but anyway some questions...

    - I'd like to know the format of @attribute parameters. Is it as ugly as C#? Something like @blabla(someParamValue)?

    - Is tag inheritance supported? Can you inherit automatically all attributes of a parent class, and attributes of an overriden method? What about inheriting parameters of attributes?

    - How is validation of @attributes and their parameters handled?

    - How rich is the runtime api? Can I do Class.getAllClassesWithTag("hibernate.class") for example?

    Really these are my biggest concerns about jsr175.

    Ara,
    your XDocleter fella
  32. EzJava[ Go to top ]

    How about a special syntax

    Have a look at http://innominds.com/anki/ezjava.html


    ///////////////////A Service////////////////////
    package com.me.service;

    /**
     * A simple RMI service
     */
    service <rmi> [id = "MyService"]
    public class MyRMIService {
        export String sayHello(String name) {
            return "Hello! " + name;
        }
    }

    ///////////////////A Client////////////////////
    package com.me.client;

    import com.me.service.*;
    /**
     * A simple client for MyService
     */
    public class MyClient uses MyRMIService {
        public void test() {
            try {
                String message = getMyRMIService().sayHello("World");
                System.out.println("Message from service is: " + message);
            } catch (java.rmi.RemoteException remoteException) {
                //
            }
        }
    }
  33. Are generics limited to what is built in to the standard libraries?
    Or will we be able to write our own templatized classes and methods?
  34. Hi there,

    Has anyone come across any comparison of the upcoming generics with the now-matured level of the standard based meta-programming in C++ ? We C++ developers either use the popular libraries like Boost (boost.org), Loki, Blitz++ and so on.

    As most would agree, it requires a rock-climbers preserverance to master and internalize the generics core concepts, be it c++, Java or even c-sharp. Just curious, after going thru' last 5 years of c++ standards evolution, with respect the notion of c++ templates. I am pretty sure the generics evolution in Java and/or c# will take the same route, if not shorter.

    For those curious about where C++ is going (-and it is still popular when it comes to runtime efficiency, even with designs that demand templates based metaprogramming), here is the c++ meta-programming post-GoF book: "Modern C++ Design: Generic Programming and Design Patterns Applied", by Andrei Alexandrescu.

    Regards,
    /Ravi Tadwalkar
    An unbiased "Standard C++" specialist
  35. Given the runtime efficiency of C++ STL, why not use STL based metaprogramming instead for generics?
    After all, why should we learn yet another way to deal with member templates and template functions and templates of templates ;-)

    Here is why I am asking this question ot the Java developers at large, your humbly included:

    The upcoming C++ standard C++0x has one issue to deal with: Compile to bytecodes for JVM based execution. (Managed C++ already does this for the CLR platform.) You can check more about this on Herb Sutter's website (http://www.gotw.ca/). Herb is convener of the ISO C++ standards committee.


    It took the C++ standards community and the compiler vendors good 5 years to get this straight! The C++ programmers such as myself were even more unlucky due to little compiler support thus far!

    So why not use the now-matured C++ generics and metaprogramming support in the standard template library full of excellent and runtime efficient design patterns? There is a growing community of C++ gurus like http://www.thecppseminar.com/ that have already done inspiring work of mentoring.

    I think we Java developers can ask the C++ compiler community, who writes platform-specific as well as platform independent compilers, proactively for the JVM bytecode compilation feature, instead of waiting for the C++0x standard, and you will get it soon. Just put in a request to the open source C++ compiler developers such as gcc (and/or MingW) team, the multi-platform compiler such as the Dev-C++ or digital mars C++ comipler...or even Microsoft for that matter! Currently, their is the most standards compliant C++ comiler. But it a matter of choice. I like Dev-C++ as well.
  36. I don't quite like the for loop enhancement. Its too much syntactic sugar for the Java language. Java dangerously seems to start resembling C++...
  37. Runtime attributes[ Go to top ]

    Hi PPL,

    I was of the opinion that the new metadata facility would enable attributes to be "used" (i.e. by the JVM) at runtime. But from the interview it seems that they only standardise a way for tools to generation code or DDs? Or am I missing something...?

    Cheers

    Smythe
  38. Runtime attributes[ Go to top ]

    <smythe>
    I was of the opinion that the new metadata facility would enable attributes to be "used" (i.e. by the JVM) at runtime. But from the interview it seems that they only standardise a way for tools to generation code or DDs? Or am I missing something...?
    </smythe>

    JSR 175 does not mandate how the attributes will be used. All it does is define a syntax, a persistence specification and an API so that these attribute can be accessed once you have the .class file.

    --
    Cedric
    http://beust.com/weblog
  39. It is better than what we have now, true, but it is still not OO. Wouldn't it be better to have blocks and a "do" method java.util.Collection? That is, instead of:

    void cancelAll(Collection<TimerTask> c) {
        for (TimerTask task : c)
            task.cancel();
    }

    we could have something like:
    void cancelAll(Collection<TimerTask> c) {
        c.do( [ TimerTask task | task.cancel(); ] );
    }

    It seems to me that that would be much more straightforward. Java has too many control structures as it is -- it doesn't need any new ones.
  40. It is better than what we have now, true, but it is still not OO. Wouldn't it be better to have blocks and a "do" method java.util.Collection? That is, instead of:

    >
    > void cancelAll(Collection<TimerTask> c) {
    >     for (TimerTask task : c)
    >         task.cancel();
    > }
    >
    > we could have something like:
    > void cancelAll(Collection<TimerTask> c) {
    >     c.do( [ TimerTask task | task.cancel(); ] );
    > }
    >
    > It seems to me that that would be much more straightforward. Java has too
    > many control structures as it is -- it doesn't need any new ones.

    FWIW - The Jakarta Commons Collections library addresses this issue with the Closure interface and the Collections.forAllDo method. Then the method would look something like this:

    void cancelAll(Collection<TimerTask> c) {
        CollectionUtits.forAllDo(c, new CancelTaskClosure());
    }


    http://jakarta.apache.org/commons/collections/api/index.html

    Ryan
  41. "FWIW - The Jakarta Commons Collections library addresses this issue with the Closure interface and the Collections.forAllDo method. Then the method would look something like this:
    "

    Looks like C++ function objects. Very powerful. Ver cool.

    Function objects/delegates/function poinnters is something that Java could use (amnong a million other things).

    Unfortunately, the powers that be are slow to move.

    So what if a new language feature breaks old code. As long as it produces compiler errors I see no problemt with extending the language.
  42. More features for Java[ Go to top ]

    I am still missing the following features in Java:

    1. C#-style properties.
    2. Polymorphic static methods.


    1. C#-style properties.

    The quickest way to define a data-containing structure is to define a class with a set of field variables, for example:

    public class Employee {
    public String lastName;
    public String firstName;
    public String position;
    public float salary;
    }


    However, if you later need to control the setting or getting the values of those fields, you will need to rewrite your class

    to add JavaBeans properties and hide (make private or protected) the data fields, something like:

    public class Employee {
    private String lastName;
    private String firstName;
    private String position;
    private float salary;

    public String getLastName() {
    return lastName;
    }

    pubic void setLastName( String newLastName ) {
    //Adding some logic
    if( newLastName == null || newLastName.trim().length() == 0 )
    throw new IllegalArgumentException( "Last name cannot be null or empty!" );
    this.lastName = newLastName;
    }

    public String getFirstName() {
    return firstName;
    }

    pubic void setFirstName( String newFirstName ) {
    this.firstName = newFirstName;
    }

    public String getPosition() {
    return position;
    }

    pubic void setPosition( String newPosition ) {
    this.position = newPosition;
    }

    public float getSalary() {
    return salary;
    }

    public void setSalary( float newSalary ) {
    this.salary = newSalary;
    }


    }

    Notice how much bigger the class has become. You can imagine how much bigger it would have become if you use some 20

    properties! However, the main problem here is that you need to rewrite all methods and classes that use this class. Well, a

    possible workaround here is to use JavaBeans-style properties when first designing such a class, so that it you would not

    need to change its clients later.

    But this is what it be could be like if we use C#-style properties:

    public class Employee {
    private String _lastName;

    public String lastName {
    get{
    return _lastName
    }
    set{
    if( value == null || value.trim().length() == 0 ) {
    throw new IllegalArgumentException( "Last name cannot be null or empty!" );
    }
    }
    }
    public String firstName;
    public String position;
    public float salary;
    }

    Looks much more elegant and cleaner. There two issues with this, however:

    a. There should be some way to define checked exceptions for property getters and setters.
    b. It will be necessary to extend interface syntax definition to include properties.



    2. Polymorphic static methods.


    I have encountered many times the problem when I need to override a static method, but there seem to be no way to do that.

    Consider the following situation. I have defined a class Parent and a class Child as follows:

    public class Parent {

    private Parent instance;

    protected Parent() {
    ...
    }

    ...

    public static void initClass() {
    ....
    }

    public Parent getInstance() {
    if( instance == null ) {
    instance = new Parent();
    }
    return instance;
    }


    }

    public class Child extends Parent {

    private Child instance;


    protected Child() {
    super();
    }

    public static void initClass() {
    staticSuper.initClass();
    }

    public Parent getInstance() {
    if( instance == null ) {
    instance = new Child();
    }
    return instance;
    }



    }

    This would enable code reuse on the class level, in addition to the code reuse on the instance level.

    This will require additional keywords, similary to this and super (staticSuper in the above example).

    Sincerely,
    Sergei Batiuk.
  43. More features for Java[ Go to top ]


    > I am still missing the following features in Java:
    > 1. C#-style properties.
    >
    Actually, is there *really* a difference between:

    private String m_lastname;
    String lastname {
      get {
         return m_lastname ;
      }
      set {
         m_lastname = value ;
      }
    }

    and

    private String m_lastname;
    String getLastname() {
         return m_lastname ;
    }
    void setLastname(String value) {
         m_lastname = value ;
    }

    Personally, I find the Java approach simpler (even people with a C background can understand it without explanation), more readable (you don't have to deal with nested scopes and you don't have implicit variables like "value"), and shorter (7 lines versus 9 lines).

    Okay, *using* Java "properties" is a bit more explicit and verbose (compare foo.setLastname(bar.getLastname() with foo.lastname=bar.lastname), but honestly, I prefer knowing what's going on, especially during maintenance and code reviews. With a Java assignment (a=b), I know there are no side effects (i.e. an assignment is an assignment). With C#, I'm not sure since I could be dealing with a property that is a function that calls a routine to start World War III.

    The main reason for properties is to help GUI builders implement property sheets. But Java's "get/set" conventions and reflection has allowed Java GUI builders to implement this feature without the need to extend the language.

    >
    > 2. Polymorphic static methods.
    >

    I'm a bit confused what you're asking for here. If you're trying to ensure that the static portions of Parent and Child are initialized, then aren't static initializers (a.k.a. static constructors) enough? If you're trying to have a static member call a parent's static member via "super" (not necessarily for initialization), yes I agree that Java doesn't allow you to do it without explicitly calling the parent class's static member. But there's no need for a new keyword "staticSuper"; the semantics of "super" should be changed so that static members can call static members in their parent class via "super".
  44. More features for Java[ Go to top ]

    Hi Robert,

    Thanks for a good reply!

    > Actually, is there *really* a difference between:
    >
    > private String m_lastname;
    > String lastname {
    >   get {
    >      return m_lastname ;
    >   }
    >   set {
    >      m_lastname = value ;
    >   }
    > }
    >
    > and
    >
    > private String m_lastname;
    > String getLastname() {
    >      return m_lastname ;
    > }
    > void setLastname(String value) {
    >      m_lastname = value ;
    > }
    >
    > Personally, I find the Java approach simpler (even people with a C background can understand it without explanation), more readable (you don't have to deal with nested scopes and you don't have implicit variables like "value"), and shorter (7 lines versus 9 lines).



    Well, Java approach might be simpler there is no big difference when you use a single property. But take a look at, at least, my previous example (class Employee), and compare the JavaBeans-style approach and the C#-style approach (42 vs 17 lines). In that case, I had 4 properties, and I needed to control what's going on in only a single setter (public void setLastName( String name ) {...} ). All other properties are pure setters and getters, no additional logic behind. Again, imagine what would be the difference with some 20 properties. New java syntax could omit a get/set method to make sure the is not available.


    I love Java, but I value my time and keep my eyes and mind open. This feature saves time dramatically. In my opinion, the C#-style properties have a clean and exressive syntax.




    >
    > Okay, *using* Java "properties" is a bit more explicit and verbose (compare foo.setLastname(bar.getLastname() with foo.lastname=bar.lastname), but honestly, I prefer knowing what's going on, especially during maintenance and code reviews. With a Java assignment (a=b), I know there are no side effects (i.e. an assignment is an assignment). With C#, I'm not sure since I could be dealing with a property that is a function that calls a routine to start World War III.




    I think that hiding what's going on behind a property is a feature. Java uses interfaces to achieve the same effect, i.e. to hide functionality (implementation) you don't need to care about behind a set of method signatures (interfaces). When you use a collection, and use collectionInstance.iterator() method or Object obj = collectionInstance.get( 3 ), you don't know what's going on behind the scenes, because the implementation has been hidden away from you. What if someone's implementation of the Collection's iterator() method uses the same function to start World War III? C#-style properties is simply a new level of abstraction.

    In C#-style property you do know what's going on. Simply each 'get' is a method, and each 'set' is a method.


    Specific examples are necessary to see where this might be a problem.




    >
    > The main reason for properties is to help GUI builders implement property sheets. But Java's "get/set" conventions and reflection has allowed Java GUI builders to implement this feature without the need to extend the language.




    I agree. The most important reason to have C#-style properties is to save the time necessary to develop classes with many setters/getters.





    >
    > >
    > > 2. Polymorphic static methods.
    > >
    >
    > I'm a bit confused what you're asking for here. If you're trying to ensure that the static portions of Parent and Child are initialized, then aren't static initializers (a.k.a. static constructors) enough? If you're trying to have a static member call a parent's static member via "super" (not necessarily for initialization), yes I agree that Java doesn't allow you to do it without explicitly calling the parent class's static member. But there's no need for a new keyword "staticSuper"; the semantics of "super" should be changed so that static members can call static members in their parent class via "super".





    I'll try to clarify.

    What I am asking for is to implement inheritance and polymorphism for static fields and methods.

    1. Concerning static initializers, I am asking to add the ability to invoke parents' static initializer from a child, if necessary. The word 'super' with static context seems to be ok,
    2. Concerning static methods, yes, I am asking to add the ability to extend a parent's static method implementation via the 'super' keyword with a static context; to invoke peer static methods using keyword 'this', again with static context.
    3. I am also asking to add static method to the interface definition. Interfaces are necessary to implement the idea of polymorphism. If static methods can be polymorphic, than interfaces can have static methods, right?
    4. I am also asking to make it possible to define a static method as 'abstract', see 3 for explanation.



    Sincerely,
    Sergei Batuk.
  45. More features for Java[ Go to top ]

    I think that hiding what's going on behind a property is a feature. Java uses interfaces to achieve the same effect, i.e. to hide functionality (implementation) you don't need to care about behind a set of method signatures (interfaces).


    Yes, but that's simple object oriented design. The problem with the C# approach is that it uses the same syntax for two entirely different operations. You may find it more convenient, but developer convenience should be a secondary goal to creating robust code. And when you can not tell exactly what a particular syntax might be doing simply by looking at it, creating robust code becomes more difficult. Your argument goes on at some length about how methods abstract away the exact behavior. They certainly do, and when I see a method being used, I know right off the bat that I am not necessarily privy to what is happening behind the scenes. However, when I see an assignment, in Java, I know that there is a simple assignment going on, with no possible side effects. C# removes that sort of certainty. Without going and examining the object itself, I have no way to know by looking at usage whether I'm dealing with a case of assignment or a property ('method'). C# has methods, they give the benefit of allowing the developer to abstract behaviour away. So does Java. What, then, is the *true* need for a "special" method syntax that does the same thing as regular methods but in such a way that it can easily be confused with non-method operations?

    > I agree. The most important reason to have C#-style properties is to save the time necessary to develop classes with many setters/getters.

    I still maintain that convenience is not a very good argument for making code less clear. Use an IDE that allows you to edit "bean properties" and that can autogenerate the getters and setters if you're worried about time.


    > > > 2. Polymorphic static methods.

    I understand your interest in this, but...I think it is not difficult to show why this doesn't make sense. The reason is that static methods simply can not be used in a polymorphic fashion. It would be nice, from an architectural standpoint, but when it comes to actually using the methods? Static methods are inherently tied to a specific class, not an instance. That class doesn't know who its decendants are. So, supposing I defined an abstract static method on Foo, and Bar extends Foo, I would still have to call Bar.methodName() and couldn't call Foo.methodName() b/c Foo would have nothing to delegate that call to. That, however, is not what polymorphism is all about. In polymorphism, I call a method on an object of a given type, but I don't know if the particular implementation I'm using is provided by that object itself, or if the object I'm dealing with is actually a special (sub) type of the object I have with a different implementation. This just can't be done with static methods. Static methods in general are not and can not be truly object oriented. Whatever specific programming needs you have where you find yourself wanting this, you would be better served by using a more flexible and object oriented design pattern (such as Factory or Singleton).
  46. More features for Java[ Go to top ]

    I agree with you that C# way of properties is elegant. However, as any young language feature, it has certain disadvantages and cannot be applied in all cases (some of which you listed in your post).

    It is currently not possible in C# to define public getter and internal or protected setter. Such design may be useful when a user should not be allowed to change object's state. In Java it is very easily accomplished since getter may be a public scope method and setter may be a package scope method. However, in C# you will be forced to write a public getter *property* and a internal or protected setter *method* which is kind of clumsy and creates a mixed approach of properties and methods.

    Regards,
    Dmitriy Setrakyan
    Fitech Labs, Inc.
    xNova™ - Service Oriented Architecture for Java and .NET
  47. More features for Java[ Go to top ]

    It is currently not possible in C# to define public getter and internal or protected setter.


    There are two issues here, that should probably be separated:

    1. Declaration of simple "properties" in Java is very, very verbose for the
    common case of

    private Type foo;

    public Type getFoo() {
    return foo;
    }

    public void setFoo(Type newFoo) {
    foo = newFoo;
    }

    compared to C#. That needs to be fixed.

    2. You may, or not, like the C# way of making bar.setFoo(x) look like
    bar.foo = x. I don't really care myself - it's just a convention.

    But even if you don't like (2) there's no reason (in my mind) to not fix (1). This could be done easily by introducing some form of shorthand for this very
    common pattern. For example: the compiler could expand, say,

    @property Type foo;

    into *exactly* the same code as above. If you need more control (over what the
    accessors do, or over their visibility) you just use the verbose good old
    way of defining properties.

    That way you can get perfect backward compatibility at the same time as a
    less insanely verbose way of declaring "properties".
  48. More features for Java[ Go to top ]

    <dan>
    Declaration of simple "properties" in Java is very, very verbose … compared to C#. That needs to be fixed.
    </dan>

    Agree, Java way is more verbose and C# way more elegant.

    <dan>
    You may, or not, like the C# way of making bar.setFoo(x) look like bar.foo = x. I don't really care myself - it's just a convention.
    </dan>

    Just one correction: in C# it’s *bar.Foo*, not *bar.foo* and again I do not disagree with you.

    I think you misunderstood the point I was trying to convey. I merely pointed out that in C# it is not possible to have getter as *public* and setter as *internal* or *protected*. So what looks quite natural in Java:

    public int getFoo() { return foo; } // public visibility
    void setFoo(int foo) { this.foo = foo; } // package visibility

    in C# will look like following:
    public int Foo { get { return foo; } } // public visibility
    internal void SetFoo(int foo) { this.foo = foo; } // assembly visibility


    Note, that in C# field foo is *gotten* using property syntax and is *set* using method syntax and I believe this asymmetry was overlooked by C# designers. Java way may be more verbose, but in this case it is more readable and usable. I do hope that future releases of .NET will address this and some other issues and will improve syntax of property declarations in C#.

    Hope this helps,
    Dmitriy Setrakyan
    Fitech Labs, Inc.
    xNova™ - Service Oriented Architecture for Java and .NET
  49. More features for Java[ Go to top ]

    I think you misunderstood the point I was trying to convey. I merely pointed out that in C# it is not possible to have getter as *public* and setter as *internal* or *protected*.


    I fully agree that C# is a bad example here. Just to make my point clear:

    a) For the common case of a private field that is publically set/getable, Java is currently very verbose. This is very easy to fix. C# is also, incidentally, quite good at this.

    b) For more "advanced" needs (restricted visibility of setter/getter, bounds checking in setter, or what have you), the current way of doing things in Java works very well. No need to fix that. C# is, again incidentally, worse than Java in this respect.

    As a side note:

    Evidently, lots of people think that the current way to declare a property is tedious: just look at the number of templates and "wizards" in Java IDEs, value object generation in XDoclet, etc. that does this for you. Unfortunately, they won't help you to read all that generated code...