This week's giveaway is in the EJB and other Java EE Technologies forum.
We're giving away four copies of EJB 3 in Action and have Debu Panda, Reza Rahman, Ryan Cuprak, and Michael Remijan on-line!
See this thread for details.
The moose likes Java in General and the fly likes Have you even wanted to do this in Java: ${x.a.b.c} Big Moose Saloon
  Search | Java FAQ | Recent Topics | Flagged Topics | Hot Topics | Zero Replies
Register / Login


Win a copy of EJB 3 in Action this week in the EJB and other Java EE Technologies forum!
JavaRanch » Java Forums » Java » Java in General
Bookmark "Have you even wanted to do this in Java: ${x.a.b.c}" Watch "Have you even wanted to do this in Java: ${x.a.b.c}" New topic
Author

Have you even wanted to do this in Java: ${x.a.b.c}

Jeff Albertson
Ranch Hand

Joined: Sep 16, 2005
Posts: 1780
In JSP and JSF you can write expressions like ${x.a.b.c} or #{x.a.b.c} which translates to roughly x.getA().getB().getC(), except that if x or any method in that chain return null, the whole expression is null. Have you ever wanted that in Java? Right now I'm writing code that does a lot of drill down into structures, with short circuits at null. So tedious

I've love to be able to write either of the following in Java (note clever new syntax)

x..a..b..c

x..getA()..getB()..getC() //I can live without the first's syntactic sugar.

What do you think? or


There is no emoticon for what I am feeling!
Ernest Friedman-Hill
author and iconoclast
Marshal

Joined: Jul 08, 2003
Posts: 24166
    
  30

That could be handy, I agree.

People have argued that returning "null" should be avoided, in general, and this kind of mess is one of the reasons. Google for the "Null Object Pattern" to get an idea of some of the alternatives.


[Jess in Action][AskingGoodQuestions]
Jeff Albertson
Ranch Hand

Joined: Sep 16, 2005
Posts: 1780
I dig the Null Object pattern . Unfortunately, the object I'm drilling into is from a third party library (Apache XMLBeans)
Ernest Friedman-Hill
author and iconoclast
Marshal

Joined: Jul 08, 2003
Posts: 24166
    
  30

Then the other solution -- following the Law of Demeter -- is also right out.
Jeff Albertson
Ranch Hand

Joined: Sep 16, 2005
Posts: 1780
Originally posted by Ernest Friedman-Hill:
-- following the Law of Demeter --

I learned that back in C++. That was a confusing time for me: ... don't talk to strangers ... friends can touch your privates ...
Alan Moore
Ranch Hand

Joined: May 06, 2004
Posts: 262
Have you looked at [url=http://jakarta.apache.org/commons/jxpath/]JXPath[/ur]? I know it doesn't use the syntax you're talking about, but it might be helpful.
 
It is sorta covered in the JavaRanch Style Guide.
 
subject: Have you even wanted to do this in Java: ${x.a.b.c}
 
Similar Threads
CMR assignment rules...
designing for multiple layers
Parent class n derived class
Initialization of static "constant" field with a non-static value
Inheritance problem in Eclipse