javaintnegative-zero

Java int argument not negative


I'm writting a method in Java with 3 argumens, the last one (int step) cannot be 0 or negative. At the moment I have it like this:

public static int[] createMonotoneIncreasingArray(int start, int end, int step) {
    if (step <= 0) throw new IllegalArgumentException("Step cannot be lower than 1 in a monotone increasing array");

    int[] resultArray = new int[(end - start) / step];

    for (int i = 0; i < resultArray.length; i++) resultArray[i] = i * step + start;

    return resultArray;
}

Is there any more elegant way to reject a non positive int in a method and avoid the exception?


Solution

  • Yes there is a way. Instead of passing in an int you can pass in a instance of a class. In this case you could create a class called Step. You would still have to check the correctness of values that step has in Steps constructor. But after doing that you can know that if you have an instance of a Step that its value is greater than 0;

    public class Step {
    
       private int value;
    
       public Step(int value) {
          if (value <= 0) throw new IllegalArgumentException("Step cannot be lower than 1");
          this.value = value;
       }
    
       public int getValue() { return value; }
    }
    
    
    public static int[] createMonotoneIncreasingArray(int start, int end, Step step) {
        int[] resultArray = new int[(end - start) / step.getValue()];
        for (int i = 0; i < resultArray.length; i++) resultArray[i] = i * step.getValue() + start;
        return resultArray;
    }
    

    This is a fairly common pattern for restricting value of an int. See this question for another example of this pattern Setting a limit to an int value