1

I was going through the picasso source code and came across this chunk in lines 80-94:

    public interface RequestTransformer {
    /**
     * Transform a request before it is submitted to be processed.
     *
     * @return The original request or a new request to replace it. Must not be null.
     */
    Request transformRequest(Request request);

    /** A {@link RequestTransformer} which returns the original request. */
    RequestTransformer IDENTITY = new RequestTransformer() {
      @Override public Request transformRequest(Request request) {
        return request;
      }
    };
  }

From my understanding, it's somewhat declaring a variable in the interface with a static constructor. Can someone explain what is that code supposed to be doing? I read through a similar post regarding constructors in interfaces (Constructor in an Interface?) but I still don't see why this case does not apply there.

Thanks

Community
  • 1
  • 1
AndroidP
  • 751
  • 1
  • 10
  • 19

1 Answers1

1

This actually is not a variable. This is constant with anonymous implementation. Within interface it is compiled to:

public interface RequestTransformer {
    Request transformRequest(Request request);

    public static final RequestTransformer IDENTITY = new RequestTransformer() {
        @Override
        public Request transformRequest(Request request) {
            return request;
        }
    };
}

And this is a bad practice (to have implementation within interface) :)

Gaskoin
  • 2,469
  • 13
  • 22
  • So if it's a bad practice, what would you suggest instead? – laalto Feb 12 '15 at 11:17
  • @laalto - I would suggest factory for that. In general you want to separate implementation from interface, so why giving implementation in interface? Look for example to java ExecutorService. It is an interface, but implementation can be retrieved from Executors factory. Please see http://docs.oracle.com/javase/7/docs/api/java/util/concurrent/ExecutorService.html and http://docs.oracle.com/javase/7/docs/api/java/util/concurrent/Executors.html – Gaskoin Feb 12 '15 at 11:19
  • Thank you, I won't use a similar coding style then. – AndroidP Feb 12 '15 at 11:30