How can I use goto in a switch statement in Objective-C? - iphone

In my code I need to be able to jump (goto) a different case within the same switch statement. Is there a way to do this?
My code is something like this: (There is a lot of code I just left it all out)
switch (viewNumber) {
case 500:
// [...]
break;
case 501:
// [...]
break;
.
.
.
.
.
case 510:
// [...]
break;
default:
break;
}
Thank you for your time!
-Jeff

It's generally very bad practice to unconditionally jump like you're asking.
I think a more readable/maintainable solution would be to place the shared code in a method and have multiple cases call the method.
If you really want to, you can use goto to do something like:
switch(viewNumber) {
case 500:
// [...]
goto jumpLabel;
case 501:
// [...]
break;
case 502:
// [...]
jumpLabel:
// Code that 500 also will execute
break;
default:break;
}
Note: I only provided the code example above to answer your question. I now feel so dirty I might have to buy some Bad Code Offsets.

Instead of using goto, refactor your code so that the two (or more) cases that use common code instead call it in a common method.
Something like:
switch (value) {
case (firstValue):
// ...
break;
case (secondValue):
[self doSharedCodeForSecondAndThirdValues];
break;
case (thirdValue):
[self doSharedCodeForSecondAndThirdValues];
break;
default:
break;
}
// ...
- (void) doSharedCodeForSecondAndThirdValues {
// do stuff here that is common to second and third value cases
}
It wouldn't be the end of the world to use goto, though it is bad practice.
The practical reason for avoiding use of goto is that you have to search through your swtich-case tree to find that goto label.
If your switch logic changes, you'll have a messy situation on your hands.
If you pull out common code to its own method, the code is easier to read, debug and extend.

You should probably try rewrite your code, like a recursive call or just factor out common stuff and call a separate function. But as a fix and quick answer to your question you could put a label before your switch and goto it, like so
switchLabel:
switch(viewNumber) {
case 500: {
viewNumber = 501;
goto switchLabel;
}
}
Not sure of the Objective-C syntax here, but you could also try a variation thereof
int lastView = 0;
while (lastView != viewNumber)
switch(lastView = viewNumber) {
case 500: {
viewNumber = 501;
break;
}
}
which will keep on looping until the viewNumber doesn't change any more. This is still pretty much just a pretty-looking goto though.
And since we're doing gotos you could just goto into another case, as pointed out already. You could also do fancy stuff similar to Duff's device, by putting cases inside of other blocks. But that's just mad.. :)

[I'm making this answer community wiki because this doesn't actually answer the question per se]
As others have said, this is very bad style, and makes for unreadable code...
Alternatives:
Factor the common code into a separate function, and call that in 2 places.
Use fallthroughs, leave off the the break on a case and it falls through to the next one (remember, cases don't have to be in numerical order!)
if you only want part of a case to be done in the other case, protect it with an if:
as in
case 500:
.
.
.
case 501:
if(viewNumber == 501) {
.
.
.
}
.
.
.
break;

Related

Class Not Updating when useing case in javascript

I don't know why the class does not be udpated in following script using the (case):
if (favorite !== null) {
switch (favorite) {
case 'cat':
document.getElementById("one").className = "favBlue";
//document.getElementById('one').className ='favRed';
//document.createAttribute('class','favRed')
break;
case 'dog':
document.getElementsByName('dog').className = 'favBlue';
break;
case 'gerbil':
document.getElementsByName('gerbil').className = 'favYellow';
break;
case 'gopher':
document.getElementsByName('gopher').className = 'favWhite';
break;
}
}
Please click on this link in order to see the complete script http://jsfiddle.net/gu8u6eoc/6/
Your case statement is working. But I think you should use document.getElementById(id) instead of document.getElementsByName(name) to change the class values. Also, you are applying the classnames to the checkboxes which won't change their colors. You should apply the classnames to the texts instead.
According to MDN, getElementsByName have different behavior per browser (e.g. sometimes it will work on elements with a similar id attribute to name). Also, getElementsByName() returns a NodeList instead of an Element object.
BTW, here is a simplified working JSFiddle. This contains both the usage of getElementById and getElementsByName.

How to get page context in MOODLE

How do we get the context of the current page opened in moodle
i.e., the context could be either system/course/coursecat etc.,
I would appreciate your help
Really simple :)
$context = $PAGE->context;
And to check the type of context, use the context constants
switch ($context->contextlevel) {
case CONTEXT_SYSTEM:
break;
case CONTEXT_USER:
break;
case CONTEXT_COURSECAT:
break;
case CONTEXT_COURSE:
break;
case CONTEXT_MODULE:
break;
case CONTEXT_BLOCK:
break;
}
Make sure you have the following set before you call $PAGE:
GLOBAL = $PAGE;

Use of "if/elseif/else" versus "if/else{if/else}"

I find myself very commonly using a pattern like this:
if (a > b) {
foo();
}
elseif (c > d) {
bar();
}
else {
baz();
}
The point here being that the second condition is not obviously connected to the first, unless you're carefully following the program logic. Is this a very bad thing? Would it be preferable to phrase the above as
if (a > b) {
foo();
}
else {
if (c > d) {
bar();
}
else {
baz();
}
}
for maintainability reasons? Is there a better pattern that I'm missing entirely? The "not obviously connected" bit seems to be one of the more common sources of bugs in my code.
It doesn't really matter.
I prefer the Leaky Rowboat* pattern:
if (a > b)
{
foo();
return;
}
if (c > d)
{
bar();
return;
}
baz();
which is even better when you are returning something:
if (a > b)
return foo();
if (c > d)
return bar();
return baz();
*bail early, bail fast
I think the first is definitely preferable. The only time I would use the second is to put code in the outer else that isn't in the inner if/else.
When I see an else if, I immediately look for the if. So I would say it is obviously connected.
I think this is a code smell. It's not very obvious what you are doing here, or why you are doing it. The fact that you think both that they aren't obviously connected and that they are a frequent source of bugs is telling you not to be doing this this way.
Rewrite this code so that the reason you are branching on these conditions is clear. Ideally you would be able to read the code and have it express your intent and/or your specifications.
taller_than_wide = a > b;
more_expensive_than_normal = c > d;
if (taller_than_wide) {
foo();
}
elseif (more_expensive_than_normal) {
bar();
}
else {
baz();
}
I avoid using the second approach since it leads to lot of indentation for large conditionals.
I would certainly use the first as it's much much readable than the second.
The second option will force the reader to keep in mind which conditions has to be true to get to the nested if where it reads at each moment and in the third or fourth nested if this becomes really annoying and very vulnerable and logically hard to follow.

How to make a big switch control structure with variable check values?

For example, I have a huge switch control structure with a few hundred checks. They're an animation sequence, which is numbered from 0 to n.
Someone said I can't use variables with switch. What I need is something like:
NSInteger step = 0;
NSInteger i = 0;
switch (step) {
case i++:
// do stuff
break;
case i++:
// do stuff
break;
case i++:
// do stuff
break;
case i++:
// do stuff
break;
}
The point of this is, that the animation system calls a method with this big switch structure, giving it a step number. I want to be able to simply cut-copy-paste large blocks and put them in a different position inside the switch. for example, the first 50 blocks to the end.
I could do that easily with a huge if-else structure, but it would look ugly and something tells me switch is much faster.
How to?
By not doing it this way. A case label has to be a constant.
Here's one way to do this that might be better:
Define a selector for each thing you want to do e.g.
-(void) doOneThing;
-(void) doAnotherThing;
// etc
Put them in an array:
SEL anArray[] = { #selector(doOneThing), #selector(doAnotherThing) /* other selectors */, NULL };
And then you can just iterate through them.
SEL* selPtr = anArray;
while (selPtr != NULL)
{
[self performSelector: *selPtr];
selPtr++;
}

How can I cleanly handle error checking in Perl?

I have a Perl routine that manages error checking. There are about 10 different checks and some are nested, based on prior success. These are typically not exceptional cases where I would need to croak/die. Also, once an error occurs, there's no point in running through the rest of the checks.
However, I can't seem to think of a neat way to solve this issue except by using something analogous to the following horrid hack:
sub lots_of_checks
{
if(failcond)
{
goto failstate:
}
elsif(failcond2)
{
goto failstate;
}
#This continues on and on until...
return 1; #O happy day!
failstate:
return 0; #Dead...
}
What I would prefer to be able to do would be something like so:
do
{
if(failcond)
{
last;
}
#...
};
An empty return statement is a better way of returning false from a Perl sub than returning 0. The latter value will actually be true in list context:
sub lots_of_checks {
return if fail_condition_1;
return if fail_condition_2;
# ...
return 1;
}
Perhaps you want to have a look at the following articles about exception handling in perl5:
perl.com: Object Oriented Exception Handling in Perl
perlfoundation.com: Exception Handling in Perl
You absolutely can do what you prefer.
Check: {
last Check
if failcond1;
last Check
if failcond2;
success();
}
Why would you not use exceptions? Any case where the normal flow of the code should not be followed is an exception. Using "return" or "goto" is really the same thing, just more "not what you want".
(What you really want are continuations, which "return", "goto", "last", and "throw" are all special cases of. While Perl does not have full continuations, we do have escape continuations; see http://metacpan.org/pod/Continuation::Escape)
In your code example, you write:
do
{
if(failcond)
{
last;
}
#...
};
This is probably the same as:
eval {
if(failcond){
die 'failcond';
}
}
If you want to be tricky and ignore other exceptions:
my $magic = [];
eval {
if(failcond){
die $magic;
}
}
if ($# != $magic) {
die; # rethrow
}
Or, you can use the Continuation::Escape module mentioned above. But
there is no reason to ignore exceptions; it is perfectly acceptable
to use them this way.
Given your example, I'd write it this way:
sub lots_of_checks {
local $_ = shift; # You can use 'my' here in 5.10+
return if /condition1/;
return if /condition2/;
# etc.
return 1;
}
Note the bare return instead of return 0. This is usually better because it respects context; the value will be undef in scalar context and () (the empty list) in list context.
If you want to hold to a single-exit point (which is slightly un-Perlish), you can do it without resorting to goto. As the documentation for last states:
... a block by itself is semantically identical to a loop that executes once.
Thus "last" can be used to effect an early exit out of such a block.
sub lots_of_checks {
local $_ = shift;
my $all_clear;
{
last if /condition1/;
last if /condition2/;
# ...
$all_clear = 1; # only set if all checks pass
}
return unless $all_clear;
return 1;
}
If you want to keep your single in/single out structure, you can modify the other suggestions slightly to get:
sub lots_of_checks
{
goto failstate if failcond1;
goto failstate if failcond2;
# This continues on and on until...
return 1; # O happy day!
failstate:
# Any clean up code here.
return; # Dead...
}
IMO, Perl's use of the statement modifier form "return if EXPR" makes guard clauses more readable than they are in C. When you first see the line, you know that you have a guard clause. This feature is often denigrated, but in this case I am quite fond of it.
Using the goto with the statement modifier retains the clarity, and reduces clutter, while it preserves your single exit code style. I've used this form when I had complex clean up to do after failing validation for a routine.