Nitika
Nitika

Reputation: 215

Relace switch with modular way of implementation

I have two strings s1, s2. They can have data of any type int,float,list,map,etc. And need to be compared on the basis of the type. The strings could be like "1","two","one,two,three","{one=1, two=2}",etc. And we will also know the datatype of which the string is.

Currently, I have written a switch statement

switch(datatype)
{  
   case A: 
   case B:
   default: 
}

But, I need to convert into modular way and call the appropriate function on the basis of type eliminating switch and if else.

How to convert strings to the particular datatype dynamically and make the according call? Or any other way by witch switch or if else could be eliminated.

Upvotes: 0

Views: 91

Answers (1)

Hoopje
Hoopje

Reputation: 12942

If I understand you correctly, you have data stored as strings but they can represent data of different types. Now you want to compare them in type-dependent way, but you don't like your switch solution because it requires all comparison logic to be in the same method.

I see two possible solutions.

First, if the datatype belongs to a custom class under your control, you could add a compare method to it:

abstract boolean compare(String a, String b); // or whetever return type you need

which you then need to implement in all the subclasses. Then you can call that:

result = datatype.compare(a, b)

Note that you can do this also if the datatype is an enum.

Second, if your datatype is not a custom class under control, you can use a map:

Map<DataType, ComparisonFunction> comparisonFunctions = ...;

where ComparisonFunction is a class or (functional) interface. For each data type you support you create an implementation of it. Then you obtain the needed comparison function from the map:

ComparisonFunction function = comparisonFunctions.get(datatype);
if (function == null) {
    throw new IllegalArgumentException("Unknown datatype: " + datatype);
}
result = function.apply(a, b);

The second solution has the property that the map may be changed at run-time. (Whether this is an advantage or a disadvantage depends on your specific requirements.)

Upvotes: 1

Related Questions