The Artima Developer Community
Sponsored Link

Weblogs Forum
Will Closures Make Java Less Verbose?

70 replies on 5 pages. Most recent reply: Apr 10, 2008 12:09 PM by Mark Thornton

Welcome Guest
  Sign In

Go back to the topic listing  Back to Topic List Click to reply to this topic  Reply to this Topic Click to search messages in this forum  Search Forum Click for a threaded view of the topic  Threaded View   
Previous Topic   Next Topic
Flat View: This topic has 70 replies on 5 pages [ « | 1 2 3 4 5 | » ]
Morel Xavier

Posts: 73
Nickname: masklinn
Registered: Sep, 2005

Re: Will Closures Make Java Less Verbose? Posted: Apr 1, 2008 3:02 AM
Reply to this message Reply
Advertisement
> Ugh. If I was feeling like making the code re-usable, I
> could get crazy and put it in some reusable function that
> takes an anonymous inner class:
>
Map<User, List<Claim>> claimsByUser =
> ListUtils.partition(someListOfClaims, new
> Partitioner<Claim, User>() {
> public User partition(Claim c) {
> return c.getUser();
> }
> });

> That's maybe a little clearer and it's marginally less
> code, but still pretty verbose.

Just wanted to mention that there are already libs that allow you to do this over many collections e.g. Google Collections (http://code.google.com/p/google-collections/).

And it is still horribly verbose (but oftentimes better than complex for loops).

Plus static import does have some use as it allows you to remove the redundant and repetitive class namings

Mark Thornton

Posts: 275
Nickname: mthornton
Registered: Oct, 2005

Re: Will Closures Make Java Less Verbose? Posted: Apr 1, 2008 4:23 AM
Reply to this message Reply
> > To me, J3K would be:
> > - drop primitives
> > - make operators become methods
>
> Scala did both, reducing so much complexity. Its really
> too bad that Java has primivites from the start, as it
> seems to be just a little bit more work for the compiler.

My understanding is that Scala hasn't eliminated primitives, rather they have been renamed and made extensible. You still have two categories of 'object' (value and regular objects), unlike Smalltalk which really is all regular objects.

If eliminating primitives means adding value types (which subsume primitives) then fine, but my work would be crippled by eliminating them altogether in the SmallTalk fashion. As far as I know we still don't have the technology to do that without a performance hit for some types of code.

Perhaps this illustrates one of the problems with evolving Java. It is currently useful for a very wide range of applications. Some of the proposed evolution directions would prune some of its applicability.

Vincent O'Sullivan

Posts: 724
Nickname: vincent
Registered: Nov, 2002

Re: Will Closures Make Java Less Verbose? Posted: Apr 1, 2008 5:19 AM
Reply to this message Reply
> I’d much rather write something like:
var claimsByUser = someListOfClaims.partition(\ claim -> claim.User)

> To me that's a huge gain in clarity...
>
> In the common Java case (just a for loop) the code is much
> more opaque, since it looks like every other for loop in
> Java...

I haven't taken much interest in the Java closures arguments to date (having gotten by fine without them) but, to me, this seems like a pretty strong argument in their favour.

Most mainstream computing languages are just different syntaxes for expressing the same old loops and switches with far fewer differences between then than their adherants would have us believe. The snippet above is a good example of how a low level mechanical construct, such as a loop, might be abstracted away with the right higher level construct. If that's a typical benefit of closures then I'm all for them.

Morgan Conrad

Posts: 307
Nickname: miata71
Registered: Mar, 2006

Re: Will Closures Make Java Less Verbose? Posted: Apr 1, 2008 11:06 AM
Reply to this message Reply
Carson and Alan, thanks for your posts - they did help me understand a lot better some "pretty good" cases for closures. Most of the other examples I've seen were really lame; yours make good sense and are a reasonable argument for adding them.

Carson Gross

Posts: 153
Nickname: cgross
Registered: Oct, 2006

Re: Will Closures Make Java Less Verbose? Posted: Apr 1, 2008 12:44 PM
Reply to this message Reply
> If that's a typical benefit of closures then I'm all for them.

Abstracting operations over data structures is 95% of the benefit of closures for most of us coding dregs. That's what makes some of the BGGA discussion so maddening: they are focused on the less useful syntax-extension aspect of closures, without talking about how they are going to make sorting a friggen' List not a nightmare in java.

From my post over on our DevBlog (http://guidewiredevelopment.wordpress.com/2008/02/09/gscript-java/)

Sorting a list of employees by salary in java:

   List<Employees> someEmployees = getEmployees();
   //make a copy, so we don't mutate the original list
   List<Employees> sortedEmployees = new ArrayList<Employees>(someEmployees);
   Collections.sort( sortedEmployees, new Comparator<Employee>(){
    public int compare( Employee e1, Employee e2 ) {
      return e1.getSalary().compareTo( e2.getSalary() );
    }
  });


Yikes.

In GScript:

   var sortedEmployees = getEmployees().sortBy( \ e -> e.Salary )


That is what us code monkeys need first. Let's get that right and then we can start talking about syntax extensions.

Cheers,
Carson

Carson Gross

Posts: 153
Nickname: cgross
Registered: Oct, 2006

Re: Will Closures Make Java Less Verbose? Posted: Apr 1, 2008 12:56 PM
Reply to this message Reply
I should mention that the gscript above is statically typed using type inference. It isn't like ruby or python. The compiler knows that sortedEmployees is a List<Employee> and that the type of e is Employee.

Bill Venners

Posts: 2251
Nickname: bv
Registered: Jan, 2002

Re: Will Closures Make Java Less Verbose? Posted: Apr 1, 2008 2:44 PM
Reply to this message Reply
> > > Java3k == Scala.
> >
> > Nah, Scala is a research language without an IDE and
> with
> > bad documentation. Granted, it's the best bid currently
> > but it is far too academic for the average corporate
> > developer.
> >
>
> Can we imagine a "Blue Collar" subset of Scala? There is
> some IDE support in Eclipse and arguably features such as
> advanced refactoring are quite doable in a static
> language. A more pragmatic question may be: given how far
> JRuby has come is there still a chance for Scala to catch
> up?

I've lately heard multiple people say that Scala was "too academic," and also have heard a few people suggest perhaps a Scala subset would make sense. I'm not sure what people mean by too academic, but I suspect they may feel that there are features of the language that don't have much practical use. Scala has a lot of features. I think I'm aware of all of them, and I don't really know of any that don't have a practical use. If I were to have to subset, I can't really think of anything I'd take out. We could potentially do without XML literal support, I guess. That feels a bit like it doesn't fit. But people like it, and it is certainly practical for a lot of real-world applications.

What I do think makes sense is that people will use their own subsets of Scala, and for different people they will be different subsets. I don't currently plan to use existential types, for example, except to connect to wildcard types in Java. Maybe someday I will, if I need to, but in general I'd try first to use one of the other approaches to type abstraction. The "recommended" style for existential types is to do just that, but I've seen many posts go across the Scala mailing lists of people using existential types for things that have nothing to do with Java wildcards. (Oh, and the practical reason for existential types is so we can see Java generics from Scala code. I would not want to do without that. It's an important feature.)

Mark Thornton

Posts: 275
Nickname: mthornton
Registered: Oct, 2005

Re: Will Closures Make Java Less Verbose? Posted: Apr 1, 2008 3:33 PM
Reply to this message Reply
> Abstracting operations over data structures is 95% of the
> benefit of closures for most of us coding dregs. That's
> what makes some of the BGGA discussion so maddening: they
> are focused on the less useful syntax-extension aspect of
> closures, without talking about how they are going to
And yet is not the absence of RAII in Java a frequent moan? How often do see the pattern where acquire and use are present, but the release has been accidentally omitted.

Morgan Conrad

Posts: 307
Nickname: miata71
Registered: Mar, 2006

Re: Will Closures Make Java Less Verbose? Posted: Apr 1, 2008 3:43 PM
Reply to this message Reply
Carson, regarding your sort by salary example, I have some comments / questions.

If Employee implements Comparable, and uses the salary to compare, then it's also just one line of Java code. In general, for any *one* "natural" way of sorting, Java is just as easy. (And same for the other "organize me" example) It's when you have multiple ways you want to sort/organize that it gets icky, and closures have an edge.

For sorting, what we have done is write various Comparators for the class (usually as static instances, but they could be little classes) like

Employee.COMPARATOR_NAME, Employee.COMPARATOR_SALARY, etc.

Yes, it's extra work. But it's nicely localized and hopefully reuseable / extensible.

1) What if you ship your software to China where names sort differently? In our case, you change one small section of code. Not sure in your case. How would closures handle this?

2) What happens if you want to include tips in the salary sometimes? In our case you could do something like
Employee.COMPARATOR_SALARY_PLUS_TIPS or, if it were a class, new Employee.SalaryComparator(true). In the closure case, you'd do something like

var sortedEmployees = getEmployees().sortBy( \ e -> e.SalaryPlusTips )

So we add a comparator, you would add a method. Seems like roughly similar work. Whether adding a comparator or a new method is "better" is a matter of taste (BTW, does salaryPlusTips have to be public?)


3) What if you want to sort by name and salary? We'd add a comparator, Employee.COMPARATOR_NAME_THEN_SALARY. I guess closures would go something like

var firstSort = emps.sortby(e.Name);
var finalSort = firstSort.sortBy(e.Salary)

I actually prefer the look of the closures here better, but there could be efficiency issues.

Thanks again for your good examples.

Carson Gross

Posts: 153
Nickname: cgross
Registered: Oct, 2006

Re: Will Closures Make Java Less Verbose? Posted: Apr 1, 2008 5:10 PM
Reply to this message Reply
> Carson, regarding your sort by salary example, I have some
> comments / questions.
>
> If Employee implements Comparable, and uses the salary to
> compare, then it's also just one line of Java code. In
> general, for any *one* "natural" way of sorting, Java is
> just as easy. (And same for the other "organize me"
> example) It's when you have multiple ways you want to
> sort/organize that it gets icky, and closures have an
> edge.

Regarding sorting a list on its natural order, yeah, they are both one liners, although in GScript if you have a List of Comparable objects you can just say:

  myListOfComparables.sort()


The method isn't available on lists of non-Comparable objects through some magic that we call enhancements.

> For sorting, what we have done is write various
> Comparators for the class (usually as static instances,
> but they could be little classes) like
>
> Employee.COMPARATOR_NAME, Employee.COMPARATOR_SALARY,
> etc.
>
> Yes, it's extra work. But it's nicely localized and
> hopefully reuseable / extensible.

That's the key question: how useful it the localization and reuse? Depending on your app it might be very useful. For most of the code I write a "find usages" function in my IDE would be good enough. Since I end up deleting half my code anyway, not committing to a complicated heavyweight code artifact like a class is worth the cost.

Even though I'm kind of an ass about this sometimes, I don't think it's a cut and dry "this way is always better" question. Both approaches definitely have their virtues.

> 1) What if you ship your software to China where names
> sort differently? In our case, you change one small
> section of code. Not sure in your case. How would
> closures handle this?

It would be more work in the closures case but with a "find usages" function I don't see it being too bad. Seems like it just depends.

> 2) What happens if you want to include tips in the salary
> sometimes? In our case you could do something like
> Employee.COMPARATOR_SALARY_PLUS_TIPS or, if it were a
> class, new Employee.SalaryComparator(true). In the
> closure case, you'd do something like
>
> var sortedEmployees = getEmployees().sortBy( \ e ->
> e.SalaryPlusTips )
>
> So we add a comparator, you would add a method. Seems
> like roughly similar work. Whether adding a comparator or
> a new method is "better" is a matter of taste (BTW, does
> salaryPlusTips have to be public?)

You could also do the sum directly in the sortBy expression:

  var sortedEmployees = getEmployees.sortBy( \ e -> e.Salary + e.Tips ) 


Extracting a new property or method should probably depend on how often you access that functionality, and the clarity gained by doing so.

> 3) What if you want to sort by name and salary? We'd add
> a comparator, Employee.COMPARATOR_NAME_THEN_SALARY. I
> guess closures would go something like
>
> var firstSort = emps.sortby(e.Name);
> var finalSort = firstSort.sortBy(e.Salary)

So here the closure story isn't as compelling in my opinion. You can use the more general but less attractive sort() method which is almost exactly like the logic you would have in the comparator:

  var sortedEmployees = getEmployees.sort( \ e1, e2 ->
                                            if(e1.Name > e2.Name){ 
                                              return true
                                            } else {
                                             return e1.Salary > e2.Salary
                                            })


which in my opinion is ugly. C# 3.0 has an elegant syntax for just this case:

  var sortedList = emps.sortby( \ e -> e.Name ).thenBy( \ e -> e.Salary )


I think that internally they end up sorting the list twice, but I haven't looked at whether the implementation is lazy or not. Making that work in GScript would be a bit tricky so we haven't done so yet.

Anyway that's a case, right now, where I would say a Comparator might be a better approach.

> Thanks again for your good examples.

Sure. Thanks keeping me honest. I definitely see your points on the advantages of Comparator objects.

Cheers,
Carson

Carson Gross

Posts: 153
Nickname: cgross
Registered: Oct, 2006

Re: Will Closures Make Java Less Verbose? Posted: Apr 1, 2008 5:18 PM
Reply to this message Reply

And yet is not the absence of RAII in Java a frequent moan? How often do see the pattern where acquire and use are present, but the release has been accidentally omitted.


Totally, which is why I favor adding a with(){} statement and Disposable interface to the language as a first-class construct. It gives us poor java developers a "C++ stack variable constructor/destructor"-like way to manage resources, which we definitely need.

I just don't think that needs to be baked into the closures proposal so that everyone can start getting all wacky designing new DSLs.

Sorry, I don't mean to post so much, but this is a topic near and dear to my heart.

Cheers,
Carson

Morel Xavier

Posts: 73
Nickname: masklinn
Registered: Sep, 2005

Re: Will Closures Make Java Less Verbose? Posted: Apr 1, 2008 6:13 PM
Reply to this message Reply
>
>   var sortedEmployees = getEmployees.sort( \ e1, e2 ->
> if(e1.Name >
>                                if(e1.Name > e2.Name){ 
>                                               return true
>                                             } else {
> return
> return e1.Salary >
>                    return e1.Salary > e2.Salary
>                                             })
> 

>
How about the simpler:
var sortedEmployees = getEmployees.sort(
    \e1, e2 -> return (e1.name > e2.name) || (e1.salary > e2.salary))

?

And for arbitrary expressions or using existing comparator, a fold-based combinator could be used fairly easily.

Carson Gross

Posts: 153
Nickname: cgross
Registered: Oct, 2006

Re: Will Closures Make Java Less Verbose? Posted: Apr 1, 2008 7:24 PM
Reply to this message Reply
Heh. I got my original logic totally wrong, which demonstrates how much credence you all should give my opinions. You have to test if the names are equal before you compare the salary or it won't be a stable sort.

Morel, you are right that it can be reduced to a single expression though:

  var sortedEmployess = getEmployees().sort( \ e1, e2 -> e1.Name > e2.Name or ( e1.Name == e2.Name and e1.Salary > e2.Salary ) )


Still, kinda ugly. Not exactly a poster child for why I want closures.

Cheers,
Carson

Morgan Conrad

Posts: 307
Nickname: miata71
Registered: Mar, 2006

Re: Will Closures Make Java Less Verbose? Posted: Apr 1, 2008 7:34 PM
Reply to this message Reply
Carson - what if name and salary are equal? (which is admittedly hard to imagine, but for other sorts like Name and State they could well match) Java Comparators have a three way -,0,+ return (long live FORTRAN computed GOTO statements!). The closure examples given don't seem to handle equals.

Carson Gross

Posts: 153
Nickname: cgross
Registered: Oct, 2006

Re: Will Closures Make Java Less Verbose? Posted: Apr 1, 2008 7:59 PM
Reply to this message Reply
Well you've stumbled on a dirty implementation secret of our sort() method. We might do the comparison *twice* to establish the stable order to sort the elements with. It was decided that the performance hit was worth the conceptual clarity: "Return true if the first element should come before the second, false otherwise"

Maybe that was the wrong decision, especially with nicer methods like sortBy() around to handle the 95% case. I'll have to think about it some more.

Cheers,
Carson

Flat View: This topic has 70 replies on 5 pages [ « | 1  2  3  4  5 | » ]
Topic: Will Closures Make Java Less Verbose? Previous Topic   Next Topic Topic: Refactoring addicts and dynamic languages


Sponsored Links



Google
  Web Artima.com   

Copyright © 1996-2014 Artima, Inc. All Rights Reserved. - Privacy Policy - Terms of Use - Advertise with Us