Should I define interfaces in Duck Typed languages?

前端 未结 4 2000
清酒与你
清酒与你 2021-02-05 13:31

I\'m just about to write my first application in a duck typed language (Groovy).

If I was to write the same application in a static typed language then I would need to d

4条回答
  •  佛祖请我去吃肉
    2021-02-05 13:57

    In some cases yes. I have an example where I'm creating a Groovy class that gets injected into a Java class by Spring. I created an interface using generics like this:

    //interface injected to a java class
    public interface SomeInterface {
         T getSomething(int version, Long id);
    }
    

    Then the groovy implementation looks like this:

    //Groovy impelentation
    class SomeInterfaceImpl implements SomeInterface {
        def getSomething(int version, Long id) {
            //use duck typing to create similar objects based on version
        }
    }
    

    My example is that I'm using JAXB and XJC to create objects from an XML schema and using them in a Jersey restful web service. I'm versioning the web service and the changes are enough to version, but there's still a lot of code that can be reused. Using interfaces proved to be problematic, so I used Groovy instead and moved all the similar logic to the above mentioned Groovy class with duck typing. The objects are mostly the same with some some changes so duck typing with an interface to inject in the Java class works perfectly.

提交回复
热议问题