ResultTransformer interface in java

223 Views Asked by At

There's the following interface in hibernate.

package org.hibernate.transform;

public interface ResultTransformer extends Serializable {
    public Object transformTuple(Object[] tuple, String[] aliases);

    public List transformList(List collection);
}

In my project, I need to perfrom some transformation of the result, which is not tied with hibernate or a database. I would like to create an interface like

public interface ResultTranformer<T>{
    public T transform(T t);
}

and implement it.

In order to not create yet another interface, is it possible to implement the interface hibernate provides us with? Could it misliead another developer?

2

There are 2 best solutions below

0
On

You could use the java.util.function.Function interface for this purpose, it was meant to transform something:

Function<YourType, YourType> transformer = new Function<YourType, YourType>() {
    @Override YourType apply(YourType input) {
        // perform transformation
    }
}

Or simply by a lambda expression

Function<YourType, YourType> transformer = (YourType input) -> {
    // perform transformation
}

Having an interface with the same name, as something from a library, might confuse others.

0
On

Except for general purpose libraries, such as Guava or Apache Commons (and of course most parts of the Java API), you should not use their classes outside of the context where the library is used by your application.

This keeps the dependency on your libraries, in this case Hibernate, small and local. Meaning if you want to change the library used for a specific purpose to another version or a different library. You only need to change that code that actually has to do with the task that library fulfills.

Also you will not confuse the readers of your code (other developers) into thinking your class will be used with Hibernate later on.

Finally, making an interface is not too much work. If the interface is not used very locally, you should always create a full interface with proper explanations of what goes in and out. Your interface will probably have different requirements on error handling than Hibernate does, or if not now, you might want to be able to change that in future.