this is a fairly general question about whether people should be using brackets on method calls that take parameters or not.
i.e.
def someFunc(def p) {
...
}
then calling:
someFunc "abc"
vs...
someFunc("abc")
Is this just a question of consistency, or is there specific use cases for each?
It's primarily a question of consistency and readability, but note that Groovy won't always let you get away with omitting parentheses. For one, you can't omit parentheses in nested method calls:
def foo(n) { n }
println foo 1 // won't work
See the section entitled "Omitting parentheses" in the Style guide.
There's no specific case where you must remove them, you can always use them. It's just prettier to leave them out.
There are cases where you can't do that (where you could confuse a list/map parameter with a subscript operator for instance, nested calls, or when the statement is an assignment), but the general rule is that the outmost call can have no parenthesis if there is no ambiguity.
(deleted several lines, as I've just received notification that there is a post already with that info)
Groovy 1.8 will allow even more cases to omit parenthesis, you can check them out at
http://groovyconsole.appspot.com/script/355001
"an empty pair of parentheses is just useless syntactical noise!"
It seems to me that they are encouraging you to use parenthesis when they serve a purpose, but omit them when they are just "noise"
Related
In an Android Studio (and presumably ANY) gradle file, the following code works:
task build {
}
And one minor change causes a complete meltdown:
task build
{
}
This has come up in other threads before, but in the context of fixing the build files. My question is why can't gradle/groovy be made to deal with either bracing style? Many other languages cope just fine with it, so what's the big deal here?
It's actually all right there in the error message:
build file '.../build.gradle': 80: Ambiguous expression could be a parameterless closure expression, an isolated open code block, or it may continue a previous statement;
solution: Add an explicit parameter list, e.g. {it -> ...}, or force it to be treated as an open block by giving it a label, e.g. L:{...}, and also either remove the previous newline, or add an explicit semicolon ';' # line 80, column 1.
Because of a Groovy syntax sugar to make methods with a lambda as the last parameter look line language constructs, the following code blocks:
task build {}
task build2(type: Copy) {}
are equal to their more regular form:
task build({})
task build(type: Copy, {})
Now, you do not really want those curly braces there to delimit a regular code block, but a Groovy lambda, which should be passed as a parameter to the build method.
Yet from the looks of it, Groovy can't really decide if it really is a lambda being passed as a parameter to the method in the previous line or an unrelated code block when you put a newline in between. And there you go, an ambiguousness as described in the error message, right there.
Following the advice in the error message, you can also use the following syntax instead of the one where you are escaping the new-line character:
task build
{ ->
}
Finally, the task keyword used to invoke the dynamic method (named build in your example) is not Groovy specific, but a Gradle DSL feature.
In case anyone reading this is wondering, the work-around is simple enough.
task build \
{
}
I was just wondering as to the "why"...
I'm trying to implement the TPTP grammar in PEG. It contains a rule for an empty sequence, which is used in many other rules, and PEG is rejecting this. A Google search finds https://github.com/pegjs/pegjs/commit/df154daafb9c6c952351493af02d3a55e0b05c59#commitcomment-10667420 which seems to be saying PEG by design does not allow empty sequence rules, which would make it unsuitable for implementing grammars such as TPTP which contain such. Do I understand this correctly, or am I missing something?
I believe it is still possible to do so, as explained in the posted link; instead of matching with nothing, you can match with "", and then return whatever you want to return :
Empty
= "" {return null;}
Why nested comments use by some programming languages such as MATLAB ,I just want to know usage of this kind comments in a program and what are the advantages we can gain by using this nested comments ?
The answer is nested comments allows commented-out code that contains comments itself
example in C++ has block comments delimited by /../ that can span multiple lines and line comments delimited by //.
Usually, coding standards for a particular project or program have rules about which comment style to use when; a common convention is to use block comments (/* */) for method and class documentation, and inline comments (//) for remarks inside method bodies and such, e.g.:
/**
* Helper class to store Foo objects inside a bar.
*/
public class Foobar {
/**
* Stores a Foo in this Foobar's bar, unless the bar already contains
* an equivalent Foo.
* Returns the number of Foos added (always 0 or 1).
*/
public int storeFoo(Foo foo) {
// Don't add a foo we already have!
if (this.bar.contains(foo)) {
return 0;
}
// OK, we don't have this foo yet, so we'll add it.
this.bar.append(foo);
return 1;
}
}
If someone wants to temporarily disable entire methods or classes in the above program.It's very helpful, if that language allows nested comments.
You can use comments...:
to temporally disable some lines of code.
as titles for sections.
to comment each line.
to add some notations or comments on other comments.
to send macro orders.
And you can mix all of them. That's why we need different ways to mark comments and create nested comments.
Good old Turbo Pascal aka Borland Pascal allows multi-line comments either with curly braces { } or with parenthesis star (* *), which nest independently of one another even though multi-line comments in the same style do not nest.
A good workaround from my old work place was use of typical brace { } comments for all informational comments and specialized use of the less common parenthesis star (* *) only to comment out code. Marking the middle lines of commented out code with something like ** is still a decent idea, and macros can be used to achieve this in programmer editors
function ComputeCost(var x : longint);
{ Wide version: Apply discounts to raw price.}
(* CODE GRAVEYARD!
** function ComputeCost(var x : integer);
** {Apply discounts to raw price.}
*)
Minimalists will always discount the need for nested comments by saying that C style languages allow constructs like #ifdef SOMETHING or the elegantly short #if 0 to disable code. True minimalists want old code removed completely and say version control takes the place of keeping old code. A good counter is that commented out code together with programmer editors with folding support, e.g. Vim, allows visually stepping over dead code while keeping it for reference.
I feel that nested comments are not necessary! In general a comment is omitted by the compiler so comments serve a main purpose for indicating the programmer what he had done or a new programmer to know the flow of the program..why unnecessarily nest comments..just an indication that can be without nesting.. eg:
for(;;)
{
if()
{
}
}/* a loop with an if condition*/
**need not be as**
/*a loop/*if condition*/for n times*/
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).
Is there any functionality in IDL that will allow it to evaluate a a string as code?
Or, failing that, is there a nice, dynamic way of including /KEYWORD in functions? For example, if I wanted to ask them for what type of map projection the user wants, is there a way to do it nicely, without large if/case statements for the /Projection_Type keyword it needs?
With even a small number of user options, the combinations would cause if/case statements to get out of hand very quickly to handle all the possible options.
The best bet is to use a case statement because you can't trust that your user is going to type in the same string for Projection_Type that you're expecting as in the keyword.
Though if you are set on doing something like this, there is the EXECUTE function that treats a string as an IDL statement:
Result = EXECUTE(String [, QuietCompile] [, QuietExecution])
Edited to add, there's also CALL_FUNCTION and CALL_PROCEDURE that are faster but maybe less flexible. Look them all up in the IDL help and see what works for you.