 |
Article:
 |
 |
(Not So) Stupid Questions 7: >>, >>>, <<, and ?: operators
|
| Subject: |
Otherwise known as a ternary operator |
| Date: |
2006-01-17 13:49:46 |
| From: |
phuego |
|
Response to: Well they are quite intuitive i think...
|

|
The ? and : chars are correctly known when used together as a 'ternary operator'.
I find them particularly useful for refactoring a block of code that does this, or that, based on a boolean.
For example you have a method that filters a List.
The way the List is filtered depends on a GUI setting, for arguments sake 'include zero'.
So you might code like this:
public List filterListOfIntegersToPositives(List original, boolean inclZero) {
List ret = new ArrayList(original.size());
if (inclZero) {
// code that does filtering
for(int i=0; i<original.size(); i++){
Integer thisInt = originals.get(i);
if (thisInt.compareTo(Integer.valueOf(0)) > -1) {
ret.add(thisInt);
}
}
// end code that does filtering
} else {
// code that does filtering
for(int i=0; i<original.size(); i++){
Integer thisInt = originals.get(i);
if (thisInt.compareTo(Integer.valueOf(0)) > 0) {
ret.add(thisInt);
}
}
// end code that does filtering
}
return ret;
}
Now you look at that code, and you think to yourself - the code that does filtering (as commented) is duplicated, and that violates "Don't repeat Yourself" and so I need to refactor that to a better design. good thought.
So we look and we see that the only part that changes in the duplicated code is the value of the int we compare to (it changes from -1, to 0)
So, using a ternary operator, we could refactor that method as follows:
public List filterListOfIntegersToPositives(List original, boolean inclZero) {
List ret = new ArrayList(original.size());
for(int i=0; i<original.size(); i++){
Integer thisInt = originals.get(i);
if (thisInt.compareTo(Integer.valueOf(0)) > (inclZero? -1 : 0)) {
ret.add(thisInt);
}
}
return ret;
}
Much cleaner.
Now, i have to admit, I've never used bitshifting either! So I'm looking forward to the "why you'd actually do this" post on that.
Hope that helps to clarify ternary operators and why you'd use them just a little.
Adrian |
|