Questions tagged [switch-statement]

The tag has no usage guidance.

Filter by
Sorted by
Tagged with
2 votes
3 answers
353 views

Should I still "replace conditional with polymorphism" if the condition is from dynamic load data?

I know there are already some questions about replacing if else with polymorphism, for example: Applying Replace Conditional with Composition in functional programming Is it wrong to use any type of ...
0 votes
1 answer
76 views

Avoiding repeating code when assigning pointer addresses based on branch

I have the following code in C that reads data off a char array and makes decisions on what variables should some pointers point to. char preset1[20]; char preset1Name[20]; int preset1Temp; int ...
12 votes
6 answers
91k views

Checking "instanceof" rather than value using a switch statement

Is there some syntax (other than a series of if statements) that allows for the use of a switch statement in Java to check if an object is an instanceof a class? I.e., something like this: switch (...
4 votes
3 answers
10k views

Enums in java switch-statements and completeness

I feel like I should be able to find an answer to this, but it turns out to be harder to search than expected... so: In C#, when we do something like: enum MyEnumClass { A, B }; static String Test(...
29 votes
7 answers
23k views

Refactoring Switch Statements and is there any real use for Switch Statements at all?

I was reading this article and was wondering, do we get rid of all switch statements by replacing them with a Dictionary or a Factory so that there are no switch statements at all in my projects. ...
5 votes
4 answers
30k views

Throw an exception in default case of a switch?

In my class I have a processor manager that contains a switch case. I have just changed the real name values to Ant, Parrot and Snake. switch (name) { case "ant": return new ...
64 votes
17 answers
37k views

Why use an OO approach instead of a giant "switch" statement?

I am working in a .Net, C# shop and I have a coworker that keeps insisting that we should use giant Switch statements in our code with lots of "Cases" rather than more object oriented approaches. His ...
3 votes
2 answers
625 views

How to use visitor pattern when objects change frequently

It is said that visitor pattern is applicable to problems where objects rarely change but we add actions on those objects more frequently. What if the objects are changing too though? For example we ...
1 vote
2 answers
756 views

Concept/Design question: Alternatives to switch/conditional statements and Enums

I am practicing design patterns and OO concepts such as inheritance in java and I'm writing an application that represents a vending machine. I have two questions focused on ideal structure and design ...
47 votes
12 answers
20k views

Avoiding the goto voodoo?

I have a switch structure that has several cases to handle. The switch operates over an enum which poses the issue of duplicate code through combined values: // All possible combinations of One - ...
28 votes
7 answers
7k views

How does this switch statement do "multiple things"?

This doubt is about Switch Statements from Chapter 3: Functions of the book named Clean Code Here we have a function: public Money calculatePay(Employee e) throws InvalidEmployeeType { switch (e....
8 votes
6 answers
10k views

Is there a way to speed up a big switch statement?

As a practice I'm working on a CPU simulator (runs at about 1.78MHz) and I'm using a switch statement to execute correct opcodes based on the value in the IR (instruction register) variable. This ...
11 votes
5 answers
4k views

Looking for an effective pattern to cope with switch statements in C#

I sometimes end up with services encapsulating the responsibility of doing some sort of business process for which there are several possible outputs. Typically one of those output is success and the ...
2 votes
2 answers
703 views

Large method with nested switch case(s) refactoring (Java)

Essentially I've got a bunch of formulas in two giant methods in a class designed to do math transformations and evaluations to multiple inputs. Where the inputs are actually lists of inputs (as there ...
0 votes
1 answer
547 views

Name of this enum-based design pattern to get the type

I have been using a pattern in a lot of places (mainly C#) that I would like to know the name of. Here is an example of it in C#: public enum ThingType { A, B, C } public interface ...
2 votes
2 answers
459 views

Why does C# type pattern matching use a different variable scoping behavior than traditional switch blocks?

Traditional switch blocks have one scope, so the following throws a compiler error "A local variable or function named 'message' is already defined in this scope": switch(value) { case 1: ...
1 vote
4 answers
654 views

How would I add up enumerator values such that any combination provides a unique number?

Backstory (You can skip) I am writing a pronunciation library for irregular words. Take something like the following: T1E1s // tee one E one es | tee one E ones 1994-1995// 1994 (minus|dash|to|) ...
40 votes
8 answers
24k views

Why does Clang/LLVM warn me about using default in a switch statement where all enumerated cases are covered?

Consider the following enum and switch statement: typedef enum { MaskValueUno, MaskValueDos } testingMask; void myFunction(testingMask theMask) { switch (theMask) { case ...
-1 votes
2 answers
1k views

How to get switch case values [closed]

I was wondering if there is a way to get the values of every case in a switch statement? When you provide a not implemented case, I would like to throw some exception and provide a list of available ...
9 votes
2 answers
263 views

fall-through switch for executing a sequence of steps

My program needs to execute a sequence of steps from start to end. But based on different input the start point will vary, e.g, some will run from the first step to end, some will run from the 2nd ...
4 votes
2 answers
387 views

Why do I need a game loop with states, instead of init the next state in current state directly?

For example, it is common to see games with game loop and states: stateChanged(){ switch(state){ STATE.PLAYER_SELECT_CHARACTER: this.currentController=new PlayerSelectCharacterController()...
1 vote
1 answer
513 views

Remove duplicated switch statements caused by not knowing type at compile time of opencv matrix?

I have a situation that occurs 5 times in my code, and continues to grow. Basically I have the same switch statement structure every time I need to perform an operation that involves my matrix and ...
1 vote
4 answers
2k views

What should be the last entry in a switch/case statement?

When writing a switch statement that only ever has to deal with a known set of values (imagine an implicit enumeration), I find myself wondering what should be the last entry in the construct. I'm ...
7 votes
2 answers
5k views

is switch(this) antipattern or bad practice in Java for Enums?

At work I bumped into a problem to see how enums are growing and storing business logics. As they grew, the constructors grew a lot. At one point I found out instead of putting in let's say the tenth ...
-1 votes
1 answer
712 views

Refactoring bad code switch statment without distort everything

Once in a while I’m stumbling on switch statements during a Code Review session. I would like to find a more elegant way of this code .... $istannceOfClass = $repository->loadFoo(); switch($...
4 votes
3 answers
13k views

Most efficient method for large switch statements

Let's say you have many paths that an application can take at a certain point based on the value of a specific input (for example a simple int). Is there a certain method that is most efficient for ...
6 votes
3 answers
31k views

How to use a switch statement with enum efficiently?

I would like to know how I can use a switch statement with enum values for the following scenarios: I am making a small program for a flight reservation system. The program is meant to enter certain ...
0 votes
1 answer
992 views

In Qt or C++, is there a good means for creating a switch with dynamically generated cases, or should I just use a for loop (or something else)?

Presume this situation: Max Number of 256 key slots. Key slots are defined by a struct, and a variable for each (256) has to exist. User defines which keys slots are active at initiation (in my ...
1 vote
1 answer
1k views

Is it standard to log each case of a switch statement?

Some code I wrote was sent back to me during peer review, telling me to add logging to the start of each case in a switch statement in a servlet (Java, if that matters), so if something goes wrong, we ...
5 votes
2 answers
2k views

OOP: Switching on polymorphic types and maintaining state throughout workflow

High level: I think my design pattern is flawed. Despite implementing Polymorphism, I find myself relying on large switch statements based on derived Type within my WPF application. As I'm adding more ...
100 votes
3 answers
110k views

Break on default case in switch

I am a bit puzzled on whenever or not to include break after the last case, often default. switch (type) { case 'product': // Do behavior break; default: // Do ...
25 votes
5 answers
27k views

Multiple arguments in function call vs single array

I have a function that takes in a set of parameters, then applies to them as conditions to an SQL query. However, while I favored a single argument array containing the conditions themselves: ...
12 votes
4 answers
2k views

Switch vs Polymorphism when dealing with model and view

I can't figure out a better solution to my problem. I have a view controller that presents a list of elements. Those elements are models that can be an instance of B, C, D, etc and inherit from A. So ...
15 votes
7 answers
16k views

Appropriate uses of fall-through switch statements

When is it appropriate to use a fall-through (classic) switch statement? Is such usage recommended and encouraged or should it be avoided at all costs?
11 votes
7 answers
2k views

Implementation of object state in an OO language?

I've been given some Java code to look at, which simulates a car race, of which includes an implementation of a basic state machine. This is not a classical computer science state machine, but merely ...
4 votes
1 answer
685 views

Is there something to be said for putting the "default" case of a switch statement first?

Like: switch (value) { default: something_common() case 1: niche_case() ... } etcetera. if-else statements require an "if" first and an "else" last, but switch statements are more flexible ...
44 votes
8 answers
64k views

Is it necessary to add the default case while using switch cases?

During a recent code review I was asked to put default cases in all the files wherever switch block is used, even if there is nothing to do in default. That means I have to put the default case and ...
1 vote
1 answer
1k views

How to structure huge conditional statement?

I'm creating some kind of a "personal assistant" application which is basically a web service that receives a message and then does something according to it. For example I send "what time is it?" ...
7 votes
2 answers
5k views

How is switch/case handled as to avoid comparisons to the case values?

I've read in multiple answers that switch/case avoids "unnecessary" comparisons, but I never learned this in college, and I'm a little stumped on how the program would figure out which case to jump to ...
2 votes
2 answers
3k views

Searching algorithm used in switch statement

What is the searching algorithm used in switch statement in C language? If the cases are not in order still it searches proper case which means it is not a binary search algorithm, can anybody ...
-4 votes
4 answers
516 views

Why aren't named switch statements a language feature? [closed]

I could imagine the below code being somewhat useful. Is there a reason this pattern hasn't made it into programming languages? To be clear the string was just what I chose as an example you could ...
9 votes
6 answers
9k views

How to reduce a switch in a switch statement?

So I'm making a method to create a salutation line based on two people from a database. There are four parameters: the two names (name1 and name2) and the two genders (gender and gender2). For every ...
1 vote
2 answers
1k views

Caveats of using String.hashCode() on a switch on java < 1.7

There are several cases when I want to switch over a String input. I decided for implementing something like: public Object doStuff(String param) { switch (param.hashCode()) { case 1234546: ...
7 votes
3 answers
41k views

Using "Return" over "Break" or a combination

When using the Switch statement, is using return instead of break or a combination of the two considered bad form? while (true) { var operation = Randomness.Next(0, 3); switch (operation) ...
4 votes
4 answers
12k views

Are `switch` statements generally used wrong? [closed]

I see most developers using switch statements with breaks in each and every case. Is this usage of switch statements inappropriate since a simple set of if-else statements would suffice? Is it OK for ...
6 votes
2 answers
3k views

How should I refactor switch statements like this (Switching on type) to be more OO?

I'm seeing some code like this in our code base, and want to refactor it: (Typescript psuedocode follows): class EntityManager{ private findEntityForServerObject(entityType:string, serverObject:any)...
38 votes
10 answers
54k views

Should I use switch statements or long if...else chains?

Often when I hear about the switch statement, its put off as a way to replace long if...else chains. But it seems that when I use the switch statement I'm writing more code that I would be just ...
0 votes
1 answer
639 views

Switch / select case etc. compared to If ... ElseIf ... Else [duplicate]

I don't understand why the switch or equivalent is so popular in languages. To me, it seems like it had a place back in the days when the alternative was lots of nested if statements in the else part ...
1 vote
3 answers
1k views

How to shorten the case statement from hades? [duplicate]

I'm refactoring code and have reached a horribly gigantic switch statement. Every single API method available to end users is represented as an enum and we have a switch statement iterating over the ...
8 votes
3 answers
33k views

If statements vs switch cases? in a JavaScript game and if to use a function [duplicate]

I am developing a game in JavaScript where you start with a user input, stored in the variable "controller". The options for the user consists of start to start the game or about to learn about the ...