Reputation: 43508
In Java, I find the following code much cleaner and easier to maintain than the corresponding bulky switch
statement:
try {
selectedObj = new Object[] {
objA,
objB,
objC,
objD,
}[unvalidatedIndex];
} catch (ArrayIndexOutOfBoundsException e) {
selectedObj = objA;
}
opposed to
switch (unvalidatedIndex) {
case 0:
selectedObj = objA;
break;
case 1:
selectedObj = objB;
break;
case 2:
selectedObj = objC;
break;
case 3:
selectedObj = objD;
break;
default:
selectedObj = objA;
}
Is the former considered an acceptable practice? I am aware that it's not the most efficient one as it involves allocating an array and catching an exception. Would it cause something undesirable when unvalidatedIndex
is out of range (although the exception is handled)?
If possible, would you suggest something cleaner?
Upvotes: 2
Views: 501
Reputation: 240908
How about
if(index < arr.length && index >= 0){
obj = arr[index];
}else{
obj = defaultValue;
}
Upvotes: 1
Reputation: 64036
Personally, though I have no doubt some will disagree, I would do:
switch (unvalidatedIndex) {
case 0 : selectedObj = objA; break;
case 1 : selectedObj = objB; break;
case 2 : selectedObj = objC; break;
case 3 : selectedObj = objD; break;
default: selectedObj = objA; break;
}
It's clean, compact, efficient, and really easy to understand.
I would hesitate to include the case 0
, that being the default
case.
Upvotes: 1
Reputation: 310957
Both are antipatterns. Just test the index for range membership yourself. There might be a way to use an enum
in many actual cases.
Upvotes: 1
Reputation: 1744
It is not an acceptable practice. Exceptions are for errors handling, not for program flow. Also exceptions are VERY SLOW.
Upvotes: 2
Reputation: 9382
int index = 4;
ArrayList<String> myObjects = Lists.newArrayList("a", "b", "c", "d");
Object o = index < myObjects.size() && index >= 0 ? myObjects.get(index) : null;
System.out.println(o);
Lists comes from Guava.
Upvotes: -1
Reputation: 887489
Your first approach is fine.
However, it is better to check the index first:
Object[] arr = new Object[] { ... };
if (i < 0 || i >= arr.length)
i = 0;
selectedObj = arr[i];
Upvotes: 5