Questions tagged [switch-statement]
The switch-statement tag has no summary.
60 questions
-1
votes
1
answer
20
views
In dynamic programming, do switch-case statements perform worse than function tables?
The reason I wanted to ask is because of some code from Undertale that is responsible for choosing which dialogue set to use. It works something like this:
switch (id) {
case 0:
msg[0] = &...
2
votes
3
answers
977
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
86
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 ...
3
votes
2
answers
861
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
1k
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 ...
28
votes
7
answers
8k
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....
2
votes
2
answers
1k
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
666
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 ...
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 ...
5
votes
4
answers
35k
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 ...
7
votes
6
answers
13k
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 ...
2
votes
2
answers
550
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
1k
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|) ...
47
votes
12
answers
21k
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 - ...
-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
286
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
429
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
559
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
3k
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 ...
-1
votes
1
answer
724
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($...
0
votes
1
answer
1k
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 ...
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
3
answers
15k
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
1
answer
1k
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 ...
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
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 ...
-4
votes
4
answers
557
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 ...
10
votes
6
answers
10k
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 ...
4
votes
3
answers
14k
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(...
1
vote
2
answers
2k
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
43k
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 ...
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 ...
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)...
0
votes
1
answer
660
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 ...
19
votes
8
answers
9k
views
What is the benefit of switching on Strings in Java 7?
When I was starting to programme in Java, the fact that switch statements didn't take strings frustrated me. Then on using Enums, I realised the benefits that you get with them rather than passing ...
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 ...
26
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:
...
101
votes
3
answers
113k
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
6
answers
20k
views
Map of functions vs switch statement
I'm working on a project that processes requests, and there are two components to the request: the command and the parameters. The handler for each command is very simple (< 10 lines, often < 5)....
13
votes
6
answers
95k
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
2
answers
6k
views
Is it possible to avoid enormously big switch in that case? [duplicate]
I'm writing a simple chess-related code with intention to write it clearly (performance doesn't matter at all). And this method I have doesn't look clean to me at all:
public static Piece ...
43
votes
8
answers
67k
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 ...
40
votes
8
answers
27k
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 ...
8
votes
5
answers
4k
views
If-Else V.S. Switch end of flow
I was wondering the if if-else statements, is like a switch statement that does have a break statement.
if( boolean_expression_1 )
statement_1
else if( boolean_expression_2 )
statement_2
else ...
20
votes
2
answers
4k
views
Why don't languages use explicit fall-through on switch statements?
I was reading Why do we have to use break in switch?, and it led me to wonder why implicit fall-through is allowed in some languages (such as PHP and JavaScript), while there is no support (AFAIK) for ...