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 ![]()



декабря 2, 2009 в 1:22 pm
btw, what is minimum jdk version required to run this code?
декабря 2, 2009 в 1:32 pm
starting from jdk 1.1 the code should work just fine
декабря 2, 2009 в 5:36 pm
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
декабря 2, 2009 в 6:41 pm
sometimes I find something beautiful in such heavy PL
декабря 7, 2009 в 4:56 am
почему сложно это все написать на русском?
декабря 7, 2009 в 10:21 pm
specially for Rayan
логический проверить () {
возврат проверка(_структ);
}
закрытый логический проверка(Структ структ) {
ежели (!структ.кошерная()) возврат ложь;
для(Структ дитя : структ.дети()) {
ежели (!проверка(дитя)) возврат ложь;
}
возврат истина;
}
декабря 7, 2009 в 10:25 pm
kinda wacky, isn't it?
декабря 7, 2009 в 10:44 pm
блять...