I need to create a series of transformer classes that transform an object into an other one.
They are of the form
class Transformer1 {
public static AnotherClass transform(MyClass source) {
return AnotherClass.newBuilder()
.setName(source.getName())
// etc
.build();
}
}
I have about 15 of them.
These transformers for now assume that the parameter is not null. Otherwise I would get an NullPointerException.
I would like to add a null check, ie:
class Transformer1 {
public static AnotherClass transform(MyClass source) {
if(source == null)
return null;
return AnotherClass.newBuilder()
.setName(source.getName())
// etc
.build();
}
}
but I don't want to write this null check on every transformer class. I was thinking of factoring it in a super class or interface.
abstract class BaseTransformer {
public static AnotherClass transform(MyClass source) {
return source == null ? null : transformNonNull(source);
}
public abstract AnotherClass transformNonNull(MyClass source);
}
and all my subclasses could implement the transformNonNull
method.
Now that doesn't work because we are dealing with static methods and transformNonNull
would need to be static. But it can't be static and abstract.
I could make my transformers non static, but really they have no state and are more like utilities, so I would like to keep them static.
I already encountered this issue in the past and didn't really come up with a solution. Waht would be the best approach here?
EDIT:
Object A has fields a1, a2, ... Ax and I want to transform it into an object B with fields b1, b2, ... bx
My transformers are transformers for these fields into one another.
In my case, a2
could be null, and that would be perfectly acceptable. I don't want to through an exception if a2
is null and I can't build b2
from it. In this case I want to set b2
to null also