Why not use a switch
:
switch(fileType) {
case CSV:
case TXT:
case FIXED_LENGTH:
doSomething();
break;
}
This does the same as your if statement check, but it's more readable, imho.
But the problem with this code is not the switch
or the if/else
statement(s). The problem is that it breaks the Open-closed principle.
In order to fix that, I would completely remove the enum
and create an interface:
interface FileType {
boolean isInteresting();
}
Then, for each enum constant we used to have, I would create a separate interface implementation:
public class Txt implements FileType {
@Override
public boolean isInteresting() {
return false;
}
}
How does the switch
statement change? We used to pass a fileType
parameter, on which we checked the value. Now, we will pass an instance of FileType
.
public void method(FileType fileType) {
if (fileType.isInteresting()) {
doSomething();
}
}
The advantage of this is that when you introduce a new FileType
(which you would introduce as a new enum constant), you don't have to modify the switch
/if/else
statement to handle the case when this new file type is interesting or not. The code will simply work here without modification, which is the essence of the Open-closed principle: "Open for extensions, closed for modifications".
EnumSet
? Or a boolean field on yourFileType
enum? – Toucan