开发者

Limit Variable Value - best way

开发者 https://www.devze.com 2023-03-25 18:14 出处:网络
quick question, what is the best and most effective way to limit a variable in range of, say开发者_如何学C, 534 and -840.

quick question,

what is the best and most effective way to limit a variable in range of, say开发者_如何学C, 534 and -840.

Do I use Math.max methods here too?


if (variable < -840 || variable > 534)
   throw new IllegalArgumentException(variable + " is out of range");

If you want to be able to turn this off at runtime, take a look at the assert keyword.


I'm not very clear what you are asking but if it's a general scenario like a class variable, best and easiest way is to encapsulate your variable, and in the setter method check the variable and throw an exception if it's out of the range.


Math.max will a little bit more expensive, but more importantly will not very very straightforward to the reader.

if(number > MIN && number < MAX) is the most straightforward, and the best way of checking this.


None of the existing answers helped me, so here is what I found (in case someone else is looking for the same):

Rather than throwing an error, this solution accepts input above and below the limits and simply outputs the clipped value.

Math.max and Math.min can be helpful for doing this:

Math.max(Math.min(input, MAX), MIN)

Here are the three basic cases; one integer within the limit, one above, and one below:

static final int MIN= -840;
static final int MAX = 534;

int inputX = -892; // less than minNumber
int inputY = 290; // within range
int inputZ = 1234; // greater than maxNumber

System.out.println( Math.max(Math.min(inputX, MAX), MIN) ); // -840
System.out.println( Math.max(Math.min(inputY, MAX), MIN) ); // 290
System.out.println( Math.max(Math.min(inputZ, MAX), MIN) ); // 534

This graph shows how the input (x) and output (y) are related.

Limit Variable Value - best way


define two constants one for MIN one for MAX, and check always that your variable is inside them


Old question. I'll leave it in case anyone else needs it

I solved it with the annotations

@Max(value = 534)
@Min(value = -840)
private Short digits;
0

精彩评论

暂无评论...
验证码 换一张
取 消