[PRL] Of course our programming language can do this

Doug Orleans dougorleans at gmail.com
Wed Aug 2 16:09:53 EDT 2006


Viera K. Proulx writes:
 > On Aug 2, 2006, at 2:05 PM, Doug Orleans wrote:
 > > I don't think it's as painful in Java as Spolsky makes it sound.
 > 
 > You really like to write this???

No, Java is not my first choice of language, but if I were writing in
Java and I needed to do function objects, I wouldn't think it was that
big a deal.  (Especially compared to all the other verbose/tedious
things one has to do in Java, like accessor methods and constructors.)

 > - and explain it to freshmen???

No, I would not want to teach object orientation (let alone parametric
polymorphism) to freshmen in a language with static type declarations
(and somewhat broken ones at that, considering the "type erasure" mess
with generics in Java 5).  If I had to teach freshmen (like if someone
held a gun to my head...) I'd probably ease them in gently with OO
patterns in Scheme, then maybe a lightweight OO language like
ECMAScript or Ruby, before hitting them with Java or C#.  And probably
not all in the freshman year.

 > boolean andMap(ArrayList alist, Selector<T> s){
 >     int i = 0;
 >     int size = alist.size();
 >     while (i < size){
 >       if (!(s.select(alist.get(i))))
 >         return false;
 >       i = i + 1;
 >     }
 >     return true;
 > }

I haven't actually written a Java 5 program yet, but I would probably
try out the new "enhanced for statement":

http://java.sun.com/docs/books/jls/third_edition/html/statements.html#14.14.2

which would give you something like this:

  <T> boolean andMap(List<T> alist, Selector<T> s) {
    for (T obj: alist) if (!s.select(obj)) return false;
    return true;
  }

 > boolean cheapBooks = andMap(myBookList,
 >                              new Selector<Book>(){
 >                                    boolean select(Book b){
 >                                      return b.price < 10;
 >                                    }
 >                               });

For simple loops like this I probably wouldn't even bother making a
function object.  But in the cases where you really want higher-order
programming (event listeners, for instance), the extra layer of
declaration isn't a huge deal.

--dougorleans at gmail.com



More information about the PRL mailing list