javaooppreconditions

Is there a way to require a particular value as a parameter in an abstract Interface method in Java?


I'm writing a little functional Interface and the method that it contains, takes an int as parameter. I was wondering if there's any way to check that when this method will be called, the value passed to the method, will not exceed a certain value and if it does, throw an error. Is there maybe an annotation I can add?

This is what my interface looks like

public interface DrawCardHandler{
    void onDrawCard(int slot);
} 

Solution

  • Define a class

    Rather than pass around a mere int primitive, define a class to represent your specific meaning.

    public final class Slot {
        private int value;
        public Slot(int value) {  // Constructor.
            if(/** your check goes here **/) {
                throw new IllegalArgumentException("...");
            }
            this.value = value;
         }
         // getter etc. goes here.
    }
    

    In Java 16 and later, use the records feature. A record is a brief way to write a class whose main purpose is to communicate data transparently and immutably. The compiler implicitly creates the constructor, getters, equals & hashCode, and toString. We can choose to write an explicit constructor to validate the input.

    public record Slot (int value) {
        public Slot(int value) {  // Constructor.
            if(/** your check goes here **/) {
                throw new IllegalArgumentException("...");
            }
            this.value = value;
        }
        // The getters, equals & hashCode, and toString are implicitly created by compiler.
    }
    

    Then your interface could look like:

    public interface DrawCardHandler{
        void onDrawCard(Slot slot);
    } 
    

    Define an enum

    In general, if you know all possible slots in advance, you can create an enum for Slot instead of a class like I've shown - it will be even more expressive.