Reputation: 4595
Suppose I have a method that takes one int
as a argument,
suppose the method expects only the values 0, 1, 2 and not other int.
Is there a way to "force" the method to accept only 0, 1, 2?
Upvotes: 7
Views: 4559
Reputation: 22025
As @JonSkeet commented, you can throw an instance of IllegalArgumentException
. I can't find the way to translate the way to force
, though.
void giveMeZeroOneOrTwo(final int value) {
if (value != 0 && value != 1 && value != 2) {
throw new IllegalArgumentException("unacceptable value: " + value);
}
// now you can read the method name, huh?
}
Or Bean Validation
may work for you.
void giveMeZeroOneOrTwo(@Min(0) @Max(2) final int value) {
}
Well, using enum maybe good approach, and I would to like this.
enum Magic {
ONE(1),
TWO(2),
THREE(3);
public static Magic valueOf(int value) {
for (final Magic v : values()) {
if (v.value == value) {
return v;
}
}
throw new IllegalArgumentException("undefined value: " + value);
}
private Magic(int value) {
this.value = value
}
private final int value;
}
Now the method which takes an int
can be verified.
void giveMeOneTwoOrThree(final int value) {
// still throws an IllegalArgumentException
final Magic magic = Magic.valueOf(value);
}
Upvotes: 1
Reputation: 421310
You would have to create a custom data type that can only take the values 0
, 1
and 2
. You can't use an ordinary int
.
In this case you could use an enum
:
enum ZeroOneOrTwo {
ZERO(0),
ONE(1),
TWO(2);
public final int val;
private ZeroOneOrTwo(int val) {
this.val = val;
}
}
and use it as follows:
void myMethod(ZeroOneOrTwo arg) {
System.out.println("Int value: " + arg.val);
}
If you're forced to take an int
as argument (if you're implementing an interface for instance) you can resort to throwing an IllegalArgumentException
if the given value is out of range. But generally you would want to let the compiler catch the problem rather than having to deal with it at runtime.
Upvotes: 8
Reputation: 554
Maybe not applicable in every case (but you didn't specify further what you're trying to accomplish, so maybe it's worth a shot), but maybe you might consider creating three methods instead of one? Or using inheritance, since you're using an OOP language?
For example, instead of coding some information into an int
, it might be better coding style to change it.
So instead of ...
void addEmployee(int type) {
switch(type) {
case 0: // add regular eymploee
case 1: // add manager
case 2: // add CEO
}
}
... consider this ...
void addRegularEmployee() {
// ...
}
void addManager() {
// ...
}
void addCEO() {
// ...
}
... or even ...
void add(Employee e) {
// ...
}
Upvotes: 2