TE
TechEcho
Home24h TopNewestBestAskShowJobs
GitHubTwitter
Home

TechEcho

A tech news platform built with Next.js, providing global tech news and discussions.

GitHubTwitter

Home

HomeNewestBestAskShowJobs

Resources

HackerNews APIOriginal HackerNewsNext.js

© 2025 TechEcho. All rights reserved.

How many lines of Java would this take?

8 pointsby ighostover 15 years ago

7 comments

ZitchDogover 15 years ago
<p><pre><code> class ObjectUtil { static boolean hasMethod(Object obj, String... methodNames) { for(String methodName : methodNames) if(!hasMethod(obj, methodName)) return false; return true; } static boolean hasMethod(Object obj, String methodName) { for(Method method : obj.getClass().getMethods()) if(method.getName().equals(methodName)) return true; return false; } }</code></pre>
jerfover 15 years ago
None. Even with Java's typesystem you can know whether the thing or things you have in your hand implements some interface or not ("callable" in this case) at compile time. You can't ask this question because you can't not already know the answer.<p>I'm not speaking to whether dynamic/duck typing is good or bad here, just pointing out that the question is flawed.
评论 #1099610 未加载
评论 #1099634 未加载
评论 #1099643 未加载
patio11over 15 years ago
[Disclaimer: I don't read Python, but I <i>think</i> the question here is "Which methods from this list does this object implement?" If I'm wrong please correct me.]<p>My gut check was this should take about eight lines, plus imports and the class boilerplate. Let's try:<p><a href="http://www.pastie.org/808727" rel="nofollow">http://www.pastie.org/808727</a><p>Yep, eight.<p>[Edit: It occurs to me the Python code might answer "Does this implement all specified methods?" That also takes eight lines in Java. I've appended the implementation above.]
评论 #1099622 未加载
efsavageover 15 years ago
I don't really care how many lines of Java this takes, if someone commits a garbage scenario like this I'm concerned with how many lines of comments they have explaining why they're doing it instead of solving the problem correctly.
brehautover 15 years ago
The snippet is imprecise. it should be something like<p><pre><code> def hasmethod(obj, meth_name): """If it calls like a method it's a method.""" return callable(getattr(obj, meth_name)) if hasattr(obj, meth_name) else False</code></pre>
评论 #1099636 未加载
jashkenasover 15 years ago
In CoffeeScript, it's a few lines less:<p><pre><code> has_methods: (obj, meth_names) -&#62; name for name in meth_names when obj[name] and obj[name].call</code></pre>
评论 #1099586 未加载
pymanover 15 years ago
Idiots count lines, programmers write them