Switch statement indentation - switch-statement

Just out of curiosity, I was wondering why the indentantation on switch statements are the way they are. I'd expect that break; should be written on the same column as case: like we do with curly brackets on an if statement.
So why do we do it like this:
case 1:
//do stuff
break;
case 2:
case 3:
//do stuff
break;
And not like this:
case 1:
//do stuff
break;
case 2:
case 3:
//do stuff
break;

There is no difference in either of those two ways of writing switch statements. If I wanted I could also write a switch statement like this
case 1: /*do stuff*/ break;case 3: case 2: /*do stuff*/ break;
The whitespaces you add will not be read by the compiler.
We add the spaces and the indentation so as to make our code easily readable to others.
In 4 words: no blocks, no indentation.
Cases are not opening a block. In C or C++ you can even put variables declarations (but the initializers are not called, except for static variables, that's a pitfall) at the beginning of the switch block.
Hence, as cases are just labels, indenting them does not seem that intuitive, and not indenting is the style chosen by most styles.

IMHO, the first example is more clear, you can see each case without barriers. The second example is more difficult because in the same level there are case and break and you can't divide blocks so easy.

Related

multiple conditions in one if statement loaded from a file

I have an if statement in my code that has multiple conditions, like this: if(cond1 || cond2 || cond3 || cond4). These conditions may vary with time and I don't want to edit my code each time they change.
I'd like to store them in a file which would be easier to edit. something like this:
file conditions.txt:
cond1
cond2
cond3
cond4
and then in my code if(loadedFile). My idea was to load the file into an array (\n separator) and then do if(arr[1] || arr[2] || arr[3] || arr[4]) but that can't work since there is an unknown number of conditions.
I don't get it. Why is it easier to edit the conditions in a separate file, rather than the one that is executed?
To answer your question, if you really want to do this, look into eval for executing strings in node.
Seriously though, this is a very bad habit to get yourself.
If the conditions are evaluated in an array already, you can just make sure that none are false: if (array.every(element => element)) { To get them to be evaluated in the array, though, you'd need to use something like eval, which is quite unsecure. If you really want to keep them separate, I'd say you should refactor such that your conditions file is JS that simply exports the array itself for use in conditions later. Then you can import that array with require() in your main file.

In Haxe switch/case, is there a way to mix a case 'xx': with the default:?

I like to use switch/case a lot but I've been wondering if it's possible to mix a default with a case in Haxe (version 2 or 3)?
This is an example of what I'm trying to achieve, except it doesn't compile:
switch(s) {
case 'reset': trace("...");
case 'stat','stats': trace("..."); // This compiles ok in case some people don't know
case 'help', default: trace("..."); // This doesn't compile
}
Do you know if this possible? I sometimes would prefer it this way because even though it's equivalent to just using a default, the code is sometimes more precise to the reader this way (no ambiguity or confusion).
I just managed to figure out a working solution for Haxe 3. Unfortunately it doesn't compile in Haxe 2.10, the version that I'm using right now. (Edit: I found a way for Haxe 2, see the other answer below).
The documentation here (http://haxe.org/manual/lf-pattern-matching-introduction.html) says that that " a _ pattern matches anything, so case _: is equal to default: ".
So similarly to writing case 'stat', 'stats': I tried to write case 'help', _: and it compiles.
So a short for Haxe 3 is:
switch(s) {
case 'reset': trace("...");
case 'stat','stats': trace("...");
case 'help', _: trace("...");
}
I compiled an example here : http://try.haxe.org/#A8D15
Here is an easy way that will work with Haxe 2.xx:
switch(s) {
case 'reset': trace("...");
case 'stat','stats': trace("...");
case 'help', s /*!default!*/: trace("...");
}
So for Haxe 2.xx, all we have to do is repeat the expression inside the switch inside the final case and it will match anything. I recommend adding a comment just after for readability.
Strangely enough, this notation won't compile in Haxe 3.

Ternary operator should not be used on a single line in Node.js. Why?

Consider the following sample codes:
1.Sample
var IsAdminUser = (User.Privileges == AdminPrivileges)
? 'yes'
: 'no';
console.log(IsAdminUser);
2.Sample
var IsAdminUser = (User.Privileges == AdminPrivileges)?'yes': 'no';
console.log(IsAdminUser);
The 2nd sample I am very comfortable with & I code in that style, but it was told that its wrong way of doing without any supportive reasons.
Why is it recommended not to use a single line ternary operator in Node.js?
Can anyone put some light on the reason why it is so?
Advance Thanks for great help.
With all coding standards, they are generally for readability and maintainability. My guess is the author finds it more readable on separate lines. The compiler / interpreter for your language will handle it all the same. As long as you / your project have a set standard and stick to it, you'll be fine. I recommend that the standards be worked on or at least reviewed by everyone on the project before casting them in stone. I think that if you're breaking it up on separate lines like that, you may as well define an if/else conditional block and use that.
Be wary of coding standards rules that do not have a justification.
Personally, I do not like the ternary operator as it feels unnatural to me and I always have to read the line a few times to understand what it's doing. I find separate if/else blocks easier for me to read. Personal preference of course.
It is in fact wrong to put the ? on a new line; even though it doesn’t hurt in practice.
The reason is a JS feature called “Automatic Semicolon Insertion”. When a var statement ends with a newline (without a trailing comma, which would indicate that more declarations are to follow), your JS interpreter should automatically insert a semicolon.
This semicolon would have the effect that IsAdminUser is assigned a boolean value (namely the result of User.Privileges == AdminPrivileges). After that, a new (invalid) expression would start with the question mark of what you think is a ternary operator.
As mentioned, most JS interpreters are smart enough to recognize that you have a newline where you shouldn’t have one, and implicitely fix your ternary operator. And, when minifying your script, the newline is removed anyway.
So, no problem in practice, but you’re relying on an implicit fix of common JS engines. It’s better to write the ternary operator like this:
var foo = bar ? "yes" : "no";
Or, for larger expressions:
var foo = bar ?
"The operation was successful" : "The operation has failed.";
Or even:
var foo = bar ?
"Congratulations, the operation was a total success!" :
"Oh, no! The operation has horribly failed!";
I completely disagree with the person who made this recommendation. The ternary operator is a standard feature of all 'C' style languages (C,C++,Java,C#,Javascript etc.), and most developers who code in these languages are completely comfortable with the single line version.
The first version just looks weird to me. If I was maintaining code and saw this, I would correct it back to a single line.
If you want verbose, use if-else. If you want neat and compact use a ternary.
My guess is the person who made this recommendation simply wasn't very familiar with the operator, so found it confusing.
Because it's easier on the eye and easier to read. It's much easier to see what your first snippet is doing at a glance - I don't even have to read to the end of a line. I can simply look at one spot and immediately know what values IsAdminUser will have for what conditions. Much the same reason as why you wouldn't write an entire if/else block on one line.
Remember that these are style conventions and are not necessarily backed up by objective (or technical) reasoning.
The reason for having ? and : on separate lines is so that it's easier to figure out what changed if your source control has a line-by-line comparison.
If you've just changed the stuff between the ? and : and everything is on a single line, the entire line can be marked as changed (based on your comparison tool).

lexer/parser ambiguity

How does a lexer solve this ambiguity?
/*/*/
How is it that it doesn't just say, oh yeah, that's the begining of a multi-line comment, followed by another multi-line comment.
Wouldn't a greedy lexer just return the following tokens?
/*
/*
/
I'm in the midst of writing a shift-reduce parser for CSS and yet this simple comment thing is in my way. You can read this question if you wan't some more background information.
UPDATE
Sorry for leaving this out in the first place. I'm planning to add extensions to the CSS language in this form /* # func ( args, ... ) */ but I don't want to confuse an editor which understands CSS but not this extension comment of mine. That's why the lexer just can't ignore comments.
One way to do it is for the lexer to enter a different internal state on encountering the first /*. For example, flex calls these "start conditions" (matching C-style comments is one of the examples on that page).
The simplest way would probably be to lex the comment as one single token - that is, don't emit a "START COMMENT" token, but instead continue reading in input until you can emit a "COMMENT BLOCK" token that includes the entire /*(anything)*/ bit.
Since comments are not relevant to the actual parsing of executable code, it's fine for them to basically be stripped out by the lexer (or at least, clumped into a single token). You don't care about token matches within a comment.
In most languages, this is not ambiguous: the first slash and asterix are consumed to produce the "start of multi-line comment" token. It is followed by a slash which is plain "content" within the comment and finally the last two characters are the "end of multi-line comment" token.
Since the first 2 characters are consumed, the first asterix cannot also be used to produce an end of comment token. I just noted that it could produce a second "start of comment" token... oops, that could be a problem, depending on the amount of context is available for the parser.
I speak here of tokens, assuming a parser-level handling of the comments. But the same applies to a lexer, whereby the underlying rule is to start with '/*' and then not stop till '*/' is found. Effectively, a lexer-level handling of the whole comment wouldn't be confused by the second "start of comment".
Since CSS does not support nested comments, your example would typically parse into a single token, COMMENT.
That is, the lexer would see /* as a start-comment marker and then consume everything up to and including a */ sequence.
Use the regexp's algorithm, search from the beginning of the string working way back to the current location.
if (chars[currentLocation] == '/' and chars[currentLocation - 1] == '*') {
for (int i = currentLocation - 2; i >= 0; i --) {
if (chars[i] == '/' && chars[i + 1] == '*') {
// .......
}
}
}
It's like applying the regexp /\*([^\*]|\*[^\/])\*/ greedy and bottom-up.
One way to solve this would be to have your lexer return:
/
*
/
*
/
And have your parser deal with it from there. That's what I'd probably do for most programming languages, as the /'s and *'s can also be used for multiplication and other such things, which are all too complicated for the lexer to worry about. The lexer should really just be returning elementary symbols.
If what the token is starts to depend too much on context, what you're looking for may very well be a simpler token.
That being said, CSS is not a programming language so /'s and *'s can't be overloaded. Really afaik they can't be used for anything else other than comments. So I'd be very tempted to just pass the whole thing as a comment token unless you have a good reason not to: /\*.*\*/

What languages have a while-else type control structure, and how does it work?

A long time ago, I thought I saw a proposal to add an else clause to for or while loops in C or C++... or something like that. I don't remember how it was supposed to work -- did the else clause run if the loop exited normally but not via a break statement?
Anyway, this is tough to search for, so I thought maybe I could get some CW answers here for various languages.
What languages support adding an else clause to something other than an if statement? What is the meaning of that clause? One language per answer please.
Python.
Example use:
for element in container:
if element == target:
break
else:
# this will not be executed if the loop is quit with break.
raise ElementNotFoundError()
From the Python docs:
it is executed when the loop
terminates through exhaustion of the
list (with for) or when the condition
becomes false (with while), but not
when the loop is terminated by a break
statement.
There is so-called "Dijkstra's Loop" (also called "Dijkstra's Guarded Loop"). It was defined in The Guarded Command Language (GCL). You can find some information about it syntax and semantic in the above Wikipedia article at the section 6 Repetition: do.
Nowadays I actually know one programming language which supports this control struture directly. It is Oberon-07 (PDF, 70 KB). And it supports "Dijkstra's Loop" in thу form of while statement. Take a look at section 9.6. While statements in the above PDF.
WHILE m > n DO m := m – n
ELSIF n > m DO n := n – m
END
Interestingly, neither the Python or the Oberon construct are the one I've been searching for. In C, I frequently find myself often wanting an 'otherwise' or 'elsewhile' construct that is executed only if the loop was never taken. Perhaps this is the construction you are looking for as well?
So instead of:
if (condition) {
do {
condition = update(something);
} while (condition);
} else {
loop_never_taken(something);
}
I could write:
while (condition) {
condition = update(something);
} otherwhile {
loop_never_taken(something);
}
It's definitely shorter, and I would find it much clearer to read. It even translates easily into (pseudo) assembly:
while: test condition
bz elsewhile
loop: push something
call update
test: test condition
bnz loop
jmp done
elsewhile: push something
call loop_never_taken
done: ...
I feel like it's a basic enough structure that it deserves a little more sugar. But apparently there haven't been any successful language designers who rely on this structure as much as I do. I wonder how much I should read into that!

Resources