简体   繁体   中英

Java Generics - Best way to use generic interface and its implementation

I have an interface MessageHandler which takes a generic type T and an implementation MessageHandlerImpl which operates on concrete type CustomObject. And then I am using this in another client class as per shown below:

public interface MessageHandler<T> { 

    void validate(T t);
    
    void process(T t);
    
    default void handle(T t) {
        validate(t);
        process(t);
    }
}

public class MessageHandlerImpl implements MessageHandler<CustomObject> {

    @Override
    public void validate(CustomObject message) {}
        
    @Override
    public void process(CustomObject message) {}
}

public class AnotherClientClass {
    
    //option - 1
    MessageHandlerImpl handler = new MessageHandlerImpl();
    //option - 2
    MessageHandler<CustomObject> handler = new MessageHandlerImpl();

    public void getMessage() {
        String messageStr = getMessageFromAnotherMethd();
        CustomObject messageObj = convertToCustomObject(messageStr);
        
        handler.handle(messageObj);
    }
}

I have couple of questions here :

  1. Is option-1 good as per best development practices, I think no as we are using concrete type for reference variable ?
  2. Option-2 looks suitable but here I have to declare type (CustomObject) again which I feel like extra baggage as MessageHandlerImpl has already done that, am I missing something ?

Generics are irrelevant here. Use the same guidelines you'd use to select the appropriate declared variable type in general.

More broadly, you have a poor design by calling new at all . Instead, make the handler a constructor parameter. In this case, definitely use the supertype MessageHandler<CustomObject> (or, even better, MessageHandler<? super CustomObject> or even Consumer<? super CustomObject> ).

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM