The following code is an example of my problem.
I would like to simplify the code without having to repeat the call for the same methods, on different switch statements.
public void simulate(String given, Status status) {
switch (status){
case A:
simulateA(given);
break;
case B:
simulateA(given);
simulateB(given);
break;
case C:
simulateA(given);
simulateB(given);
simulateC(given);
break;
}
PS 1: The order of the calling methods matters!
PS 2: I am not looking for another way of doing the switch, I am looking for another way of modelling the problem, maybe using some kind of class composition with the methods.
I do not know the nature of your enum but if you have many simulation calls you could forgo the switch statement and do it like this. But there is nothing wrong with your current approach. This would also change slightly if your methods were static and not instance. The one advantage of this is that it has the potential to scale.
There are many other ways to to this. You could have a list of method references and the enum arguments could be variable arrays of which methods to call by index.
public class Simulations {
static List<BiConsumer<Simulations, String>> sims =
List.of(Simulations::simulateA, Simulations::simulateB,
Simulations::simulateC);
enum Status {
A(1), B(2), C(3);
private int val;
private Status(int v) {
this.val = v;
}
public int getVal() {
return val;
}
}
public static void main(String[] args) {
Simulations simulation = new Simulations();
simulation.simulate("A", Status.A);
System.out.println();
simulation.simulate("B", Status.B);
System.out.println();
simulation.simulate("C", Status.C);
}
public void simulate(String given, Status status) {
for (int i = 0; i < status.getVal(); i++) {
sims.get(i).accept(this, given);
}
}
public void simulateA(String s) {
System.out.println(s);
}
public void simulateB(String s) {
System.out.println(s);
}
public void simulateC(String s) {
System.out.println(s);
}
}
In this case, the order of simulations always cascades "downwards", e.g. Simulating an B is simulating an A plus some extra's. This matches an inheritance pattern, e.g. a Mammal is an Animal with some extras. Thus, letting simulations inherit from each other fixes the pattern:
interface Simulation
{
void simulate( final String given );
}
class ASimulation implements Simulation
{
#Override
public void simulate( String given )
{
// simulate this given!
}
}
class BSimulation extends ASimulation
{
#Override
public void simulate( String given )
{
super.simulate( given );
// simulate this given some more!
}
}
class CSimulation extends BSimulation
{
#Override
public void simulate( String given )
{
super.simulate( given );
// simulate this given even more!
}
}
Note that this is fragile, as all inheritance trees are. Another solution can be achieved with composition and delegation. This is called a chain:
class LeafSimulation
implements Simulation
{
#Override
public void simulate( String given )
{
// simulate this given!
}
}
class ChainedSimulation
implements Simulation
{
private final Simulation delegate;
ChainedSimulation( final Simulation delegate )
{
this.delegate = delegate;
}
#Override
public void simulate( String given )
{
delegate.simulate( given );
// simulate this given some more!
}
}
To instantiate the chain, use the following order:
final var aSimulation = new LeafSimulation();
final var bSimulation = new ChainedSimulation( aSimulation );
final var cSimulation = new ChainedSimulation( bSimulation );
This code approaches the problem statement more naturally and eliminates the repetition, but it is not concise.
Once you have set up a mapping of status values to method calls, you can use a SortedSet or EnumSet.range to get the enum values after a particular value:
Map<Status, Consumer<String>> simulators = new EnumMap<>(Map.of(
Status.A, this::simulateA,
Status.B, this::simulateB,
Status.C, this::simulateC));
if (!simulators.keySet().equals(EnumSet.allOf(Status.class))) {
throw new RuntimeException(
"Not all Status values have simulators defined.");
}
// ...
SortedSet<Status> all = new TreeSet<>(EnumSet.allOf(Status.class));
Collection<Status> remainingValues = all.tailSet(status);
// Or:
//Status[] allStatuses = Status.values();
//Status lastStatus = allStatuses[allStatuses.length - 1];
//Collection<Status> remainingValues = EnumSet.range(status, lastStatus);
for (Status s : remainingValues) {
simulators.get(s).accept(given);
}
Another option to consider, which avoids switch / if. Declare a map of actions per Status value which can be used with a getOrDefault lookup default for unhandled values:
Consumer<String> simA = this::simulateA;
Map<Status, Consumer<String>> actions = new EnumMap<>(Map.of(
Status.A, simA,
Status.B, simA.andThen(this::simulateB),
Status.C, simA.andThen(this::simulateB).andThen(this::simulateC)
));
actions.getOrDefault(status, s -> {}).accept(given);
If you want to guard against missing / unhandled mappings you should validate the map (as in #VGR answer) or swap the no-operation default with an exception handler:
actions.getOrDefault(status,
s -> { throw new RuntimeException("Missing action for status: "+status); }
).accept(given);
Assuming your first status is A you can do something like this:
public void simulate(String given, Status status) {
if (status != Status.A) {
int indexOfStatus = status.ordinal();
simulate(given, Status.values()[indexOfStatus - 1]);
}
switch (status){
case A:
simulateA(given);
break;
case B:
simulateB(given);
break;
case C:
simulateC(given);
break;
// here you still need to put all your "simulateX" calls but without repetitions
}
}
you don't need to write simulateA(given) to all your cases, just moved it to top
public void simulate(String given, Status status) {
simulateA(given);
switch (status){
case C:
simulateC(given);
case B:
simulateB(given);
break;
case A:
break;
}}
You can try the fallthrough mechanism of switch statement. refer to this
In your example, the code can be(not tested):
Edited:
public void simulate(String given, Status status) {
switch (status){
case C:
simulateC(given);
case B:
simulateB(given);
case A:
simulateA(given);
}
}
Original(Wrong):
public void simulate(String given, Status status) {
switch (status){
case A:
simulateA(given);
case B:
simulateB(given);
case C:
simulateC(given);
}
}
When the reader has the fallthrough concept in mind, the code above is cleaner and easier to read than the code in question. But that is not always the case. My recommendation would be to restructure your code so as to eliminate both the repetitive calls and the fallthroughs.
Related
I've been wondering if there is a way for me to replace the current switch statement I have. Below is an example of the code I have, although the statement I have is a lot longer and will only get larger. The switch method gets called through a file reader so it reads a line then calls this function with values assigned.
public static void example(String action, String from, String to){
switch (action) {
case ("run"):
runTo(from,to);
break;
case ("walk"):
walkTo(from,to);
break;
case ("hide"):
hideAt(to);
break;
}
}
edit:
I was curious if there is a better way instead of using a switch statement like the above scenario.
I've updated the example a bit to make a little more sense. Some of the method calls dont need to use all of the parameters.
For Java 7 and below we can declare an interface for function implementation.
for Java 8+ we can use Function interface.
Interface:
public interface FunctionExecutor {
public Object execute(String from,String to);
}
Function Context:
public class FunctionContect {
HashMap<String, FunctionExecutor> context=new HashMap<String, FunctionExecutor>();
public void register(String name,FunctionExecutor function){
context.put(name, function);
}
public Object call(String name,String from,String to){
return context.get(name).execute(from, to);
}
public FunctionExecutor get(String name){
return context.get(name);
}
}
Function Implementations:
public class RunFunctionImpl implements FunctionExecutor{
#Override
public Object execute(String from, String to) {
System.out.println("function run");
return null;
}
}
// OTHER FUCNTIONS
Register Function:
FunctionContect contex = new FunctionContect();
contex.register("run", new RunFunctionImpl());
contex.register("walk", new WalkFunctionImpl());
contex.register("hide", new HideFunctionImpl());
Call Function
context.call(action, from, to);
or
context.get(action).execute(from,to);
I am not completely sure what you want to achieve.
If you don't want to keep adding new
case ("ccc"):
Lmn(b,c,i);
break;
blocks.
You can hash the methods in a HashMap<string, method> and get the method from the map using the key and execute it.
If you have a repetion of switch cases on the same variable, say in method f, g and h. Then you can turn things inside out:
void f(String a) {
switch (a) {
case "aaa": ... ; break;
...
}
}
void g(String a) {
switch (a) {
case "aaa": ... ; break;
case "bbb": ... ; break;
case "ccc": ... ; break;
...
}
}
void h(String a) {
switch (a) {
case "aaa": ... ; break;
...
}
}
Can be handled object orientedly as:
class C {
public f() { }
public g() { }
public h() { }
}
class Aaa extends C {
#Override
public f() { test3(b,c); } // Or even just the body of test3
#Override
public g() { }
#Override
public h() { }
}
class Bbb extends C {}
class Ccc extends C {}
Then once one has to provide a specific C:
C c;
switch (a) {
case "aaa": c = new Aaa(); break;
case "bbb": c = new Bbb(); break;
case "ccc": c = new Ccc(); break;
...
}
c.f(...);
c.g(...);
c.h(...);
This looks circumstantial, but in effect delivers an improvement on development quality.
Adding a new case does not mean searching all switch cases.
The code of one case ("aaa") is all in one class, with its own dedicated fields.
That can simplify things and deliver a better overview.
One possible option to get rid of switch is to use hashmap of functions:
private String stringMethod(final String action, final String source) {
final Function<String, String> toLowerFunction = String::toLowerCase;
final Function<String, String> toUpperFunction = String::toUpperCase;
final HashMap<String, Function<String, String>> stringFunctions = new HashMap<>();
stringFunctions.put("toLower", toLowerFunction);
stringFunctions.put("toUpper", toUpperFunction);
return stringFunctions.get(action).apply(source);
}
Replacing a switch with method calls is definitely not utter nonesense #Stultuske. Usually you use method inheritance, so different child classes with the same parent class override a general method and you don't have to check for the subclass's type.
Your case on the other hand looks like a factory method, but parameters are a bit wildly mixed. I would suggest a Map with String to a wrapper constructor function. For the "ccc" case you have to think about something else (e. g. default arguments) or you always have the unused parameter i.
Is it possible to restrict switch for using particular case.
Here is my scenario :
class XYZ {
public static final String DEFAULT = "DEFAULT";
public static final String BIG_TEXT = "BIG_TEXT";
public static final String BIG_PICTURE = "BIG_PICTURE";
public static final String CAROUSEL = "CAROUSEL";
public static final String GIF = "GIF";
#Retention(RetentionPolicy.SOURCE)
#StringDef({DEFAULT, BIG_TEXT, BIG_PICTURE, CAROUSEL, GIF})
public #interface NotificationStyle {}
#NotificationStyle
public String style() {
if (CollectionUtils.isNotEmpty(carouselItems)) {
return CAROUSEL;
}
if (CollectionUtils.isNotEmpty(gifItems)) {
return GIF;
} else {
return DEFAULT;
}
}
}
So here I have define one StringDef interface and restricting style() just to return #NotificationStyle specified values and here is my switch case
// Some other class
XYZ obj = new XYZ()
switch (obj.style()) {
case XYZ.BIG_PICTURE:
//Something something
break;
case XYZ.BIG_PICTURE:
//Something something
break;
case "Not available to execute":
//Something something
break;
default : //Something something
}
I know obj.style() will only return restricted values but I want to somehow restrict switch case to even provide this case here
case "Not available to execute":
//Something something
break;
As this will be unreachable code always.
*Please do not look for the code and syntax , just looking for concept here.
Thanks.
You're doing a switch over a String, right? That's why you can, of course, add cases, that won't really happen (like "Not available to execute"). Why don't you just change your possible Strings to an enum and make obj.style return a constant from that enum? This is how you can restict those Strings.
fun style(): XYZValues {
if (true) {
return XYZValues.BIG_TEXT
}
return XYZValues.DEFAULT
}
enum class XYZValues(desc: String) {
DEFAULT("DEFAULT"),
BIG_TEXT("BIG_TEXT")
//more }
}
fun main(args: Array<String>) {
when (style()) {
XYZValues.BIG_TEXT -> println("1")
XYZValues.DEFAULT -> println("2")
}
}
I have an enum FileType
public static enum FileType {
CSV, XML, XLS, TXT, FIXED_LENGTH
}
FileType fileType = FileType.CSV;
Is there a better (cleaner) way to check fileType for multiple values than the following (like "myString".matches("a|b|c");)?
if(fileType == FileType.CSV || fileType == FileType.TXT || fileType == FileType.FIXED_LENGTH) {}
Option 1: Add a boolean field to your enum.
public static enum FileType {
CSV(true), XML(false), XLS(false), TXT(true), FIXED_LENGTH(true);
private final boolean interesting;
FileType(boolean interesting) {
this.interesting = interesting;
}
public boolean isInteresting() {
return this.interesting;
}
}
...
if (fileType!=null && fileType.isInteresting()) {
...
}
Option 2: use an EnumSet.
EnumSets use bitfields under the hood, so they are very fast and low memory.
Set<FileType> interestingFileTypes = EnumSet.of(FileType.CSV, FileType.TXT, FileType.FIXED_LENGTH);
...
if (interestingFileTypes.contains(fileType)) {
...
}
Option 3: use a switch, as kocko suggests
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".
I ended up writing a method:
public static enum FileType {
CSV, XML, XLS, TXT, FIXED_LENGTH;
// Java < 8
public boolean in(FileType... fileTypes) {
for(FileType fileType : fileTypes) {
if(this == fileType) {
return true;
}
}
return false;
}
// Java 8
public boolean in(FileType... fileTypes) {
return Arrays.stream(fileTypes).anyMatch(fileType -> fileType == this);
}
}
And then:
if(fileType.in(FileType.CSV, FileType.TXT, FileType.FIXED_LENGTH)) {}
Nice and clean!
Adding a different example:
public class JavaApplication {
public enum CustomerStatus {
ACTIVE("Active"),
DISCONNECTED("Disconnected"),
PENDING("Pending"),
CANCELLED("cancelled"),
NEW("new");
}
public static void main(String[] args) {
EnumSet<CustomerStatus> setA = EnumSet.of(CustomerStatus.ACTIVE, CustomerStatus.NEW);
EnumSet<CustomerStatus> setB = EnumSet.of(CustomerStatus.PENDING, CustomerStatus.CANCELLED);
if (setA.contains(CustomerStatus.ACTIVE)) {
System.out.println("ACTIVE : customer active");
}
if (setB.contains(CustomerStatus.ACTIVE)) {
System.out.println("ACTIVE: Customer is no longer active");
}
if (setB.contains(CustomerStatus.CANCELLED) {
System.out.println("CANCELLED: Customer is no longer active");
}
}
}
**Output**:
ACTIVE : customer active
CANCELLED: Customer is no longer active
I have to check each and every condition with this repetitive if else loop. How to simplify with for loop or any other method?
if(color.equals("1")&&id.equals("pant"))
{
}
else if(color.equals("2")&&id.equals("pant"))
{
}
else if(color.equals("3")&&id.equals("pant"))
{
}
else if(color.equals("4")&&id.equals("pant"))
{
}
else if(color.equals("5")&&id.equals("pant"))
{
}
else if(color.equals("6")&&id.equals("pant"))
{
}
if(color.equals("1")&&id.equals("shirt"))
{
}
else if(color.equals("2")&&id.equals("shirt"))
{
}
else if(color.equals("3")&&id.equals("shirt"))
{
}
else if(color.equals("4")&&id.equals("shirt"))
{
}
else if(color.equals("5")&&id.equals("shirt"))
{
}
else if(color.equals("6")&&id.equals("shirt"))
{
}
You can use two for loops for this purpose,
first get a list which contains two elements that is "shirts" and "pants" something like
string [2] cloths = {"pants","shirts"};
and a variable like i and set that to 1 first
int i = 1;
and then
for (string cloth : cloths)
{
for (i = 1; i < 7 ; i++)
{
if(color.equals(i.toString())&&id.equals(cloth))
{
System.out.println(i.toString()+"&"+cloth);
}
}
}
The whole idea is like this but There maybe some minor syntax errors since I didn't compile the code
switch (Integer.parseInt(color))
{
case 1:
if (id == "pant")
{
// 1:pant
}
else if (id == "shirt")
{
// 1:shirt
}
break;
case 2:
if (id == "pant")
{
// 2:pant
}
else if (id == "shirt")
{
// 2:shirt
}
break;
// etc ...
}
You can use inner if statements to achieve a slightly simpler.
if (id.equals("pant")) {
if (color.equals("1")) {
//code
}
else if (color.equals("2")) {
//code
}
//etc
}
else if (id.equals("shirt")) {
if (color.equals("1")) {
//code
}
else if (color.equals("2")) {
//code
}
//etc
}
There may be ways to further simplify it, but we'd really need to know what is in the if blocks. For example, if you're just outputting the value, it could get really simple.
If you can create a common Command interface and encapsulate color & id into a Key class you can have a Map of <Key, Command> pairs.
public class Key {
private final String color; // "6" as a color? why not "blue"?
private final String name;
public Key(String color, String name) {
this.color = color;
this.name = name;
}
public String getColor() { return this.color; }
public String getName() { return this.name; }
}
public interface Command {
void execute(Object...args);
}
Map<Key, Command> noSwitch;
for (Key key : noSwitch.keyValues()) {
noSwitch.get(key).execute();
}
Or, better yet, embed that behavior into a polymorphic StockItem class that knows what to do.
Yours looks like a brittle, non-object-oriented design. You can do better.
What you can do, is to create an interface:
interface Do {
whatever()
}
Along with a bunch of implementations for whatever you do inside the different if branches.
Then have a Map of Lists to store and find them:
Map<String, List<Do>> dos = new HashMap();
// put lots of Do implementations in Lists and put them in the map.
After the setup your if monster would be reduced to:
dos.get(id).get(color).whatever
If whats inside the braces is different you can't easily replace it with a for loop (we'd need to see whats inside the braces to be definitive). A switch statement would at least make things look nicer (assuming you use color as an int not a string of an int
if (id.equals("pant")){
switch(color){ //note color should be an int, not a string of an int for this to work
case 1:
//whatevers in the braces
break;
case 2:
//whatevers in the braces
break;
etc
default:
break;
}
}
You could build a map that maps the combinations you are interested in to a function to perform.
Something like:
interface Function {
void f();
}
public void test() {
String color = "1";
String id = "pant";
// Map the string to a function.
Map<String,Function> functions = new HashMap<String,Function>();
// As many of these as you have different processes.
// You could name them too.
functions.put("1|pant",new Function() {
#Override
public void f() {
// What to do when we see color=1 id=pant
System.out.println("1|pant");
}
});
// Pull the function out of the map.
Function f = functions.get(color+"|"+id);
// If it was there.
if ( f != null ) {
// Do it.
f.f();
}
}
I would use the color-tag as an Integer-value-switch:
switch (color){
case 1:
if (id.equals("pant"){}
else if (id.equals("shirt"){}
break;
case 2:
if (id.equals("pant"){}
else if (id.equals("shirt"){}
break;
.
.
.}
easiest way imo.
Is there any alternative way to implement a switch case in Java other than if else which is not looking good. A set of values will be there in combination, according to the selection corresponding method has to be executed.
If you have plenty of switch/case statements around your code and they are driving you crazy.
You could opt for the Refactoring: Replace conditional with polymorphism.
Let's say you have a piece of software that is used to save information to different devices: 4 persistence operations are defined: fetch, save, delete, update, which could be implemented by N number of persistence mechanism ( flat files, network, RDBMS, XML, etc ) .
Your code have to support them all so in 4 different places you have this:
BEFORE
class YourProblematicClass {
....
public void fetchData( Object criteria ) {
switch ( this.persitanceType ) {
case FilePersistance:
// open file
// read it
// find the criteria
// build the data
// close it.
break;
case NetWorkPersistance:
// Connect to the server
// Authenticate
// retrieve the data
// build the data
// close connection
break;
case DataBasePersistace:
// Get a jdbc connection
// create the query
// execute the query
// fetch and build data
// close connection
break;
}
return data;
}
Same for save/delete/update
public void saveData( Object data) {
switch ( this.persitanceType ) {
case FilePersistance:
// open file, go to EOF, write etc.
break;
case NetWorkPersistance:
// Connect to the server
// Authenticate
// etc
break;
case DataBasePersistace:
// Get a jdbc connection, query, execute...
break;
}
}
And so on....
public void deleteData( Object data) {
switch ( this.persitanceType ) {
case FilePersistance:
break;
case NetWorkPersistance:
break;
case DataBasePersistace:
break;
}
}
public void updateData( Object data) {
switch ( this.persitanceType ) {
case FilePersistance:
break;
case NetWorkPersistance:
break;
case DataBasePersistace:
break;
}
}
Using switch/case statement becomes problematic:
Each time you want to add a new type you have to insert new switch/case in each section.
Many times, some types are similar, and they don't need a different switch/case ( you could cascade them )
Some other they are, and some times they differ slightly
You may even need to load different type at runtime ( like plugins )
So the refactoring here would be to add an interface or abstract type and have the different types implement that interface and delegate the responsibility to that object.
So you would have something like this:
AFTER
public interface PersistenceManager {
public void fetchData( Object criteria );
public void saveData( Object toSave );
public void deleteData( Object toDelete );
public void updateData( Object toUpdate );
}
And different implementations
public class FilePersistence implements PersistanceManager {
public void fetchData( Object criteria ) {
// open file
// read it
// find the criteria
// build the data
// close it.
}
public void saveData( Object toSave ) {
// open file, go to EOF etc.
}
public void deleteData( Object toDelete ){
....
}
public void updateData( Object toUpdate ){
....
}
}
And the other types would implement according to their logic. Network would deal with sockets, and streams, DB would deal with JDBC, ResultSets etc. XML with node etc.etc.
public class NetworkPersistence implements PersistanceManager {
public void fetchData( Object criteria ) {
// Socket stuff
}
public void saveData( Object toSave ) {
// Socket stuff
}
public void deleteData( Object toDelete ){
// Socket stuff
}
public void updateData( Object toUpdate ){
// Socket stuff
}
}
public class DataBasePersistence implements PersistanceManager {
public void fetchData( Object criteria ) {
// JDBC stuff
}
public void saveData( Object toSave ) {
// JDBC stuff
}
public void deleteData( Object toDelete ){
// JDBC stuff
}
public void updateData( Object toUpdate ){
// JDBC stuff
}
}
And finally you just have to delegate the invocations.
Later:
public YouProblematicClass { // not longer that problematic
PersistamceManager persistance = // initialize with the right one.
public void fetchData( Object criteria ) {
// remove the switch and replace it with:
this.persistance.fetchData( criteria );
}
public void saveData( Object toSave ) {
// switch removed
this.persistance.saveData( toSave );
}
public void deleteData( Object toDelete ){
this.persistance.deleteData( toDelete );
}
public void updateData( Object toUpdate ){
this.persistance.updateData( toUpdate );
}
}
So, you just have to create the correct instance for the persistence manager according to the type only once. Then all the invocations are resolved by polymorphism. That's one of the key features of Object Oriented Technology.
If you decide you need another persistence manager, you just create the new implementation and assigned to the class.
public WavePersistance implements PersistanceManager {
public void fetchData( Object criteria ) {
// ....
}
public void saveData( Object toSave ) {
// ....
}
public void deleteData( Object toDelete ){
// ....
}
public void updateData( Object toUpdate ){
// ....
}
}
Presumably you're struggling with the requirement of case's being constant. Typically this is a code-smell, but there are things you can do. You might want to raise and link to another question that details why you're trying to switch.
Map<String,Object> map = new HasMap<String,Object>();
// ... insert stuff into map
// eg: map.add("something", new MyObject());
String key = "something";
if (map.contains(key)) {
Object o = map.get(key);
}
In the example above, you might want to map to 'handlers', something like
interface Handler {
public void doSomething();
}
which then makes this all turn into a lookup.
if (map.contains(key)) { map.get(key).doSomething(); }
Again, it's a bit of a smell, so please post a question which illustrates the reasoning.
Refactoring your code to use polymorphism could get rid of the need for a switch statement. However, there are some legitimate uses for switch so it depends on your situation.
a ugly series of if,else if,else ?
or one could imagine a kind of dynamic switch case:
public interface Task<T>
{
public void doSomething(T context);
}
public Class SwitchCase<T>
{
Map<Integer,Task<T>> tasks;
Task<T> defaultTask;
public void choose(int choice, T context)
{
Task<T> t= this.tasks.get(choice);
if(t!=null) { t.doSomething(context); return;}
if(defaultTask!=null) { defaultTask.doSomething(context);}
}
}
I guess "Clean Code" has a nice chapter according switch/case vs. if/else.
Besides: I think it makes sense to decide whether you can reduce "noise" and make the code cleaner by using switch case, polymorphism or even a good ol' if/else. The number of cases plays a major role here, I guess.
I post a typical case how I replaced switch case with enum.
before refactor I have enum PatternTypes:
public enum PatternTypes {
ALPHA_CHAR, ALPHANUMERIC_CHAR, ADDITIONAL_CHAR, UNICODE_BMP_CHARS
}
and function:
private static final String ALPHA_CHAR = "[a-zA-Z]+";
private static final String ALPHANUMERIC_CHAR = "[a-zA-Z0-9\\_]+";
private static final String ADDITIONAL_CHAR = "[a-zA-Z0-9\\_\\-\\,\\.\\s\\!\\#\\$\\&\\(\\)\\*\\+\\;\\:\\=\\?\\#\\|\\[\\]\\{\\}\\~]+";
private static final String UNICODE_BMP_CHARS = "[a-zA-Z0-9\\_\\-\\,\\.\\s\\!\\#\\$\\&\\(\\)\\*\\+\\;\\:\\=\\?\\#\\|\\[\\]\\{\\}\\~\u00A0-\uD7FF\uF900-\uFFFD]+";
/*
* Match given classAbbr with given RegEx pattern
*/
private void checkInvalidClassAbbr(String classAbbr,
PatternTypes classAbbrPattern) {
switch (classAbbrPattern) {
case ALPHA_CHAR:
checkUnmatched(classAbbr, ALPHA_CHAR, CLASS_ABBR_VAR_NAME);
break;
case ALPHANUMERIC_CHAR:
checkUnmatched(classAbbr, ALPHANUMERIC_CHAR, CLASS_ABBR_VAR_NAME);
break;
case ADDITIONAL_CHAR:
throw new MalFormedDNException("Not support Pattern Type:"
+ classAbbrPattern);
case UNICODE_BMP_CHARS:
throw new MalFormedDNException("Not support Pattern Type:"
+ classAbbrPattern);
}
}
After refactor PatternTypes modified to:
public enum PatternTypes {
/**
* RegEx patterns divided by restriction level
*/
ALPHA_CHAR("[a-zA-Z]+"),
ALPHANUMERIC_CHAR("[a-zA-Z0-9\\_]+"),
ADDITIONAL_CHAR("[a-zA-Z0-9\\_\\-\\,\\.\\s\\!\\#\\$\\&\\(\\)\\*\\+\\;\\:\\=\\?\\#\\|\\[\\]\\{\\}\\~]+"),
UNICODE_BMP_CHARS("[a-zA-Z0-9\\_\\-\\,\\.\\s\\!\\#\\$\\&\\(\\)\\*\\+\\;\\:\\=\\?\\#\\|\\[\\]\\{\\}\\~\u00A0-\uD7FF\uF900-\uFFFD]+");
public String getPatternContent() {
return patternContent;
}
private String patternContent;
PatternTypes(String patternContent) {
this.patternContent = patternContent;
}
}
and function simplify to:
/*
* Match given classAbbr with given RegEx pattern
*/
private void checkInvalidClassAbbr(String classAbbr, PatternTypes classAbbrPattern) {
if (PatternTypes.ADDITIONAL_CHAR.equals(classAbbrPattern) || PatternTypes.UNICODE_BMP_CHARS.equals(classAbbrPattern)){
throw new MalFormedDNException("RegEx pattern:" + classAbbrPattern.name() + "is not allowed for Class Abbr");
}
checkUnmatched(classAbbr, classAbbrPattern.getPatternContent(), CLASS_ABBR_VAR_NAME);
}
Hashmap is considered not to be memory friendly, so you can use Enum for this purpose.
Example:
class EnumExample4{
enum Season{
WINTER(5), SPRING(10), SUMMER(15), FALL(20);
private int value;
private Season(int value){
this.value=value;
}
}
public static void main(String args[]){
System.out.println(Season.WINTER.value); //This gives you 5
}}
This will sve you from writing Switch Case or if statements.
For an alternate to switch statement, I think the best solution will be using an enum. For example: Consider the case below:-
public enum EnumExample {
OPTION1{
public double execute() {
Log.info(CLASS_NAME, "execute", "The is the first option.");
return void;
}
},
OPTION2{
public double execute() {
Log.info(CLASS_NAME, "execute", "The is the second option.");
return void;
}
},
OPTION3{
public double execute() {
Log.info(CLASS_NAME, "execute", "The is the third option.");
return void;
};
public static final String CLASS_NAME = Indicator.class.getName();
public abstract void execute();
}
The above enum can be used in the following fashion:
EnumExample.OPTION1.execute();
Hopefully this helps you guys.
What do you want to do? Why is not Switch-Case good enough?
The fast answer is: use if-else
if () {}
else if () {}
...
else if () {}
?
But I wouldn't say it is better...
How about an if (along with else if and else) statement? While switch will only allow you to switch using equality against integer or Enum types, if lets you use any boolean logic.
You could always replace a switch with if-else if-else if-else if..., though I don't see why you'd want to. Depending on the context switchs can also sometimes be replaced by arrays or hashmaps.
If the strings are static, You can make an ENUM.
and do a switch on it.