@zarch said:
Premature optimization is a really bad thing.
I don't like that traverse code though, all you need is:
[java]Spatial search = *found geometry*
while (search != null && search.getControl(*whatever*)!=null) {
search =search .getParent();
}
[/java]
At the end of the loop x is either null or the required spatial.
while(true) is generally (not always, but often) a bad sign in code.
Zarch's version is exactly right and very straight-forward. I just thought I'd provide a small alternative that keeps the looping logic together because for() is a preferred idiom for me:
[java]
// To me "for" is just slightly more self-documenting because it indicates
// "looping over something" and not just "doing things while some condition"
// It also has the loop condition and advance all together.
for( ; search != null; search = search.getParent() ) {
if( search.getControl( ... ) != null ) {
break;
}
// The nice thing now is that the loop exit logic can be as complicated as
// required in cases where "does it have this control" is not a good enough
// question. Maybe you also want to stop at a certain spatial... or you are
// looking for a control with a certain parameter... or... whatever.
}
[/java]
For similar reasons, I will often invert the logic in the loop, also:
[java]
// To me "for" is just slightly more self-documenting because it indicates
// "looping over something" and not just "doing things while some condition"
// It also has the loop condition and advance all together.
for( ; search != null; search = search.getParent() ) {
if( search.getControl( ... ) == null )
continue;
if( someOther control-specific condition )
continue;
break;
}
[/java]
It allows flatter arrangement of multiple AND'ed loop exit requirements since the NOT versions can just do continue.