2

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?

Belen
  • 673
  • 2
  • 10
  • 25
  • 3
    No. Java doesn't have unsigned integer types - and even if it did, you'd still have to reject 0. – Jon Skeet Dec 08 '17 at 19:53
  • 1
    What is wrong with throwing an exception? That is perfectly valid. – OldProgrammer Dec 08 '17 at 19:53
  • 2
    ...and avoid the exception? What do you mean by "reject"? What you've coded is a great way to check for step > 0. – Buzz Moschetti Dec 08 '17 at 19:53
  • You could add [Compile time validation](https://stackoverflow.com/questions/42644170/compile-time-validation-of-method-arguments), but that's generally more effort that it's worth. – azurefrog Dec 08 '17 at 19:54
  • 1
    If the exception is not what you want, could you just return an empty array or null if step <= 0? – Michael McKay Dec 08 '17 at 19:58
  • If Spring then use AOP and check beforeProcessing, if normal java then you are doing the right thing.( For normal java program, If you really don't wan't to invoke the method unless all things are right then I would suggest _you to check the argument's validity before calling the method_ ) – RAHUL ROY Dec 08 '17 at 20:39

1 Answers1

2

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

bhspencer
  • 13,086
  • 5
  • 35
  • 44