I now break the longstanding tradition of not posting code on this blog. I just wanted to share what I believe to be a somewhat unusual pattern in Java:
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 | public IMethod findMethod(String name, String[] types) { outer: for (IMethod m: m_methods) { if (m.getName().equals(name)) { int i = 0; for (IType t: m.getArgList().getTypes()) { if (! t.getName().equals(types[i])) { continue outer; } i++; } return m; } } return null; } |
On line 2, there’s a label outer: which identifies a location in the code. Normally this feature is used with keywords like the hotly debated goto in C. Java has goto as a keyword, but doesn’t support the feature. However, you can still use the labels with statements like continue above (line 12), which in this case starts a new iteration of the outer loop rather than the inner one.
I can’t remember ever having had to use this feature of any C-like language before (perhaps once) so it was intriguing when it popped up. It’s possible that a neater implementation of this would put the inner loop in a matchesSignature method in the IMethod interface instead.
Comments 2
Surely even cleaner would simply be to override equals in IMethod, and you could even pass an IMethod into the function.
Posted 29 Jul 2009 at 11:32 pm ¶Rich, this would indeed be a nice solution, but there are problems; 1) this code snippet looks for methods with identical signatures, but for equality, I may want a stricter condition than just that eventually, and 2) this snippet is called from a context where such an IMethod is not available, and creating it just to use it as an argument seems silly. But… it is not a bad suggestion.
Posted 30 Jul 2009 at 12:17 am ¶However I’m now rewriting a lot of this stuff in Scala, and I think it’ll end up having a much more compact form when that’s finished.
Post a Comment