Nested functions in Java


2 декабря 2009

The task was to write a method to check some internal data structure recursively and return the answer (42 :) ). Naturally, anybody would write something like:


boolean validate() {
   return check(_struct);
}
private boolean check(Struct struct) {
   if (!struct.valid()) return false;
   for(Struct child : struct.children()) {
     if (!check(child)) return false;
   }
   return true;
}

According to the spirit of the idiom of code locality that private method should be moved to validate(). But what the heck — no nested functions in Java :???: So here is the decent workaround:


boolean validate() {
   return new Object() {
     boolean check(Struct struct) {
       if (!struct.valid()) return false;
       for(Struct child : struct.children()) {
         if (!check(child)) return false;
       }
       return true;
     }
    /* Here we can have more local methods… */
   }.check(_struct);
}

If we don't need a function but procedure, the code will be shorter:


void foo() { new Object() {
  { bar(_struct); }
  void bar(Struct struct) {
    struct.makeMeFeelGood();
    for(Struct child : struct.children()) bar(child);
  }
};}

Plz comment if this applicable for .NET cuz I can't recall, getting older khe-khe :smile:

google.com bobrdobr.ru del.icio.us technorati.com linkstore.ru news2.ru rumarkz.ru memori.ru moemesto.ru

8 Комментариев на “Nested functions in Java”

  1. Glad сказал:

    btw, what is minimum jdk version required to run this code?

  2. zeroreturn сказал:

    starting from jdk 1.1 the code should work just fine

  3. zeroreturn сказал:

    um, sorry, i forgot that those fancy for()'s appeared in jdk 1.5, but the main idea isn't about for()'s after all, but in anonymous inner classes

  4. Glad сказал:

    sometimes I find something beautiful in such heavy PL :wink:

  5. Rayan сказал:

    почему сложно это все написать на русском?

  6. zeroreturn сказал:

    specially for Rayan


    логический проверить () {
      возврат проверка(_структ);
    }
    закрытый логический проверка(Структ структ) {
      ежели (!структ.кошерная()) возврат ложь;
      для(Структ дитя : структ.дети()) {
        ежели (!проверка(дитя)) возврат ложь;
      }
      возврат истина;
    }

  7. zeroreturn сказал:

    kinda wacky, isn't it? :grin:

  8. Rayan сказал:

    блять...





Оставте свое мнение