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?
Whenever you want to restrict the type parameter to subtypes of a particular class you can use the bounded type parameter. If you just specify a type (class) as bounded parameter, only sub types of that particular class are accepted by the current generic class.
Well, if a method has five or more parameters, then you should consider refactoring that method and decreasing the number of parameters. This is where Introduce Parameter Object refactoring comes into play. In short, this refactoring is a way of replacing a method's argument list with a single parameter object.
In Java, you can pass an argument of any valid Java data type into a method. This includes simple data types such as doubles, floats and integers as you saw in the computePayment() method above, and complex data types such as objects and arrays. Here's an example of a method that accepts an array as an argument.
The number of method parameters is limited to 255 by the definition of a method descriptor (§4.3. 3), where the limit includes one unit for this in the case of instance or interface method invocations.
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.
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) {
// ...
}
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With