jeudi 11 juin 2020

Validate a condition in default method in interface in Java

I had a method in my interface that was implemented by many classes :

public interface MyInterface {
    Message createMessage(List<String> rawStrings);
}

There is a Validate condition I am adding to all the createMessage implementations :

public Message createMessage(List<String> rawStrings) {
    Validate.isTrue(!rawStrings.isEmpty(), "No rawstrings present");
    .....
}

I have been suggested to move the validate condition to the interface - but by doing so, I will be losing out on enforcing the class implementing my interface to implement this method.

Does this look like a good idea?

default Message createMessage(List<String> rawStrings) {
    Validate.isTrue(!rawStrings.isEmpty(), "No rawstrings present");
    return null;
}

Is this a good use of the default method in interfaces? How can I still ensure that the class implementing MyInterface also implements the method createMessage?

Aucun commentaire:

Enregistrer un commentaire