Replacing switch statement Java - java

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.

Related

How to create child class with parant reference with java reflection and without switch

I have a class A which is parant of classes AB, AC, AD. Also class A have enum field "type" which
can be "A" \ "AB" \ "AC" \ "AD".
So, how can i replace this switch with java reflections?
public A f(Type type){
A a;
switch (type){
case A:
a = new A();
break;
case AB:
a = new AB();
break;
case AC:
a = new AC();
break;
case AD:
a = new AD();
break;
}
}
```
Apperently, your switch statement is supposed to create a new object of the given type (of aa). To support this, you don’t need Reflection at all. You could use, e.g.
public class A {
public final Supplier<A> factory;
protected A(Supplier<A> factory) {
this.factory = Objects.requireNonNull(factory);
}
public A() {
this(A::new);
}
}
public class AB extends A {
public AB() {
super(AB::new);
}
}
public class AC extends A {
public AC() {
super(AC::new);
}
}
public class AD extends A {
public AD() {
super(AD::new);
}
}
Then, you can easily create a new object like
A aa = new AB();
A a = aa.factory.get();
// verify our assumption
if(a.getClass() != aa.getClass())
throw new AssertionError();
For completeness, you can use Reflection, like
A a = aa.getClass().getConstructor().newInstance();
but the compiler will force you to deal with several potential exceptions, as there’s a lot that can go wrong at runtime, which can’t be checked at compile-time.

Best way execute code according enum value

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.

Is it possible to restrict switch to use particular cases only in kotlin/JAVA?

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")
}
}

Java casting interface but using object methods

I have a question on how to call an objects base member when instantiated through an interface.
Suppose I have the following interface and concrete classes in a framework I am trying to build:
public interface UsedClass {
public boolean getBool();
}
public class User implements UsedClass {
private String userName;
private String userRole;
public User(String userName, String userRole){
this.userName = userName;
this.userRole = userRole;
}
public boolean getBool() {
// some code
}
public int getUserName() {
return userName;
}
public int getUserRole() {
return userRole;
}
And an implementing class:
public class Run implements UsedClass {
private String runName;
private int runNumber;
public Run(String runName, int runNumber){
this.runName = runName;
this.runNumber = runNumber;
}
public boolean getBool() {
// some code
}
public String getRunName() {
return runName;
}
public int getRunNumber() {
return runNumber;
}
}
But I cannot put methods getRunName() or getUserRole() into the interface!
The end goal is to create a FactoryClass to handle the objects passed from a database GUI.
I would like to know if there is a better way then using class reference be able to safely call methods of Run or User such as:
public class EntityFactory {
public static Object getValueAt(int rowIndex, int columnIndex, UsedClass usedClass) {
if (usedClass.getClass().getSimpleName().equals("User")) {
switch (columnIndex) {
case 0:
return ((User) usedClass).getUserName();
case 1:
return ((User) usedClass).getUserRole();
default:
return null;
}
} else if (usedClass.getClass().getSimpleName().equals("Run")) {
switch (columnIndex) {
case 0:
return ((Run) usedClass).getRunName();
case 1:
return ((Run) usedClass).getRunNumber();
default:
return null;
}
}
I have read several SO posts
type casting when objects are of interface references in Java and Java cast interface to class
where it is implied that reference casting is not advised, but since I cannot put all methods into the interface, what would be advised?
static interface ColumnSource<T> {
String getColumn(T value, int index);
}
static Map<Class, ColumnSource> map = new HashMap();
static {
map.put(User.class, new UserNameAndRoleSource<User>() {
public String getColumn(User user, int index) {
switch (index) {
case 0: return user.getUserName();
case 1: return user.getUserRole();
default: throw new RuntimeException();
}
}
});
map.put(Run.class, new ColumnSource<Run>() {
public String getColumn(Run run, int index) {
switch (index) {
case 0: return run.getRunName();
case 1: return run.getRunNumer();
default: throw new RuntimeException();
}
}
});
}
public static Object getValueAt(int rowIndex, int columnIndex, Object o) {
Class type = o.getClass();
ColumnSource source = map.get(type);
if (source == null) throw new RuntimeException(type.getName() + " not supported");
return source.getColumn(o, columnIndex);
}
You should use instanceof rather than looking at the simpleName of the class.
Beyond that you are correct. You either need to have an interface containing the common methods which you can then call them in or you need to identify that the object is an instance of a specific class and then do the cast and make the method call.
You could consider using a Map<Class<? extends UsedClass>, Map<Integer, Function<___>>> handlers.
Then your processing would be
handlers.get(usedClass.getClass()).get(columnIndex).apply(usedClass);
Obviously you would want to consider how to handle the unexpected class/index case. The inner Map<Integer,... could potentially be a List<...> depending on how it is being used.
Two things:
if at all, you use instanceof instead of string / class name comparison
you build your interfaces / classes to be helpful. They are the base of all the things you are doing. If you start with broken abstractions, you are broken. Simple as that.
What I mean is: if there is "common" behavior; then you should express that using a common interface. If not, you start your efforts on an already broken base; and you will be need to create "creative workarounds" all over the place in order to fight the symptoms of that disease.
Maybe one small solution could be to have at least multiple interfaces, like
interface UsedClass { ...
interface SpecialUsedClassA extends UsedClass { ...
interface SpecialUsedClassB extends UsedClass { ...
than you can at least return UsedClass instead of Object.

Alternative to Switch Case in Java

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.

Categories

Resources