from Hacker News

How many lines of Java would this take?

by ighost on 2/4/10, 1:54 AM with 23 comments

  • by ZitchDog on 2/4/10, 2:47 AM

        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;
            }
        }
  • by jerf on 2/4/10, 2:29 AM

    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.

    I'm not speaking to whether dynamic/duck typing is good or bad here, just pointing out that the question is flawed.

  • by patio11 on 2/4/10, 2:30 AM

    [Disclaimer: I don't read Python, but I think the question here is "Which methods from this list does this object implement?" If I'm wrong please correct me.]

    My gut check was this should take about eight lines, plus imports and the class boilerplate. Let's try:

    http://www.pastie.org/808727

    Yep, eight.

    [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.]

  • by efsavage on 2/4/10, 3:30 AM

    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.
  • by brehaut on 2/4/10, 2:39 AM

    The snippet is imprecise. it should be something like

        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
  • by jashkenas on 2/4/10, 2:14 AM

    In CoffeeScript, it's a few lines less:

        has_methods: (obj, meth_names) ->
          name for name in meth_names when obj[name] and obj[name].call
  • by pyman on 2/4/10, 4:54 PM

    Idiots count lines, programmers write them