Explanation of the statement below about Groovy closures. - groovy

I'm reading this: A closure looks a lot like a regular Java or Groovy code block, but actually it's not the same. The code within a regular code block (whether its a method block, static block, synchronized block, or just a block of code) is executed by the virtual machine as soon as it's encountered. With closures the statements within the curly brackets are not executed until the call() is made on the closure. In the previous example the closure is declared in line, but it's not executed at that time. It will only execute if the call() is explicitly made on the closure
And I'm thinking, how is this true, in Java if you have an instance method, the code is only executed when the method is called then how are they saying above that is executed by the VM as soon as it sees it ?
If I have a method func(){int a =5; return a+5;} this will be executed only when called is my understanding.

The description might be better taken with just synchronized block or regular scope braces. What it's attempting to show is that when the thread of execution hits a regular code block, it continues on executing the contents. With closure definitions, the code in the block is not immediately executed - it's used to define/instantiate a closure object (say, clos) which contains that logic, and which can be later executed via clos.call() (or just clos()).
example:
def x = 1
synchronized(this) {
x = 1000
}
println x //x == 1000
vs.
def x = 1
Closure clos = {
x = 1000
}
println x // x == 1
clos() // or clos.call()
println x // x == 1000
W/R/T method/static blocks: It's unclear to me if there is some nuanced way in which "encountered" and "executed" can be used in a JVM context that makes that part of the statement correct, but for practical purposes, it's at best misleading. Methods are still only executed when called, and not by virtue of their declarations being located in the apparent path of code execution, as the following can be run in groovyConsole to show:
def x = 1
void methodA() {
x = 1000
}
def b = {
x = x + 1
}
println x // x is still 1

Another analogy, which is not necessarily technically accurate, is to think about Closures as anonymous inner classes that have a single method (the body of the closure).
Doing either closure.call() or closure() (short-hand for call()), invokes that single method.
Closures have additional features, of course, but I think that this is a good way to think about the basics.

Related

How to make closure have its own copy of variable -does groovy have lambda

What is the command in groovy to ensure a class variable is unaffected by a closure? As we know a closure captures the environment that its wrapped in. So, if I have a closure that increments an integer class variable for example, then that variable is changed for the class. What I want is for a closure to have its own copy of a variable so it does not affect the class variable. Is it possible? In Objective C for example we would use the __Block command and that would make the block be able to change the value of a captured variable. Now, I am asking for the opposite of __Block in my case as closures are already changing the variables they are scoped in.
Lets take a look at a clear example of what I want:
def class myCoolClass {
def x=1
def myMethodThatReturnsClosure(){
//lets return a closure who's scope will include the x=1
myClosure
}
def showMeXFromMyCoolClass(){
println "this is x from myCoolClass:$x"
}
def myClosure={
println "im printing x:$x"
//lets change x now from within closure
x++
}
}
def x = new myCoolClass();
def c=x.myMethodThatReturnsClosure();
c(); //we are changing x ...x = 1
c(); //we are changing x again ...x = 2
c(); //we are changing x again ...x = 3
x.showMeXFromMyCoolClass(); //...x = 4
//i dont want x to be 4 in the last call, i want x to be 1.
//i want it unchanged. how to tell closure to take its own copy
I realize in groovy a closure knows about its environment. It "closes out" around the function that its wrapped in. Is there lambda in groovy then? I think lambda would not know about its environment right? But lets say I want only want variable to not know about its environment and others should, then lambda would not be good.
Your example code is not valid Groovy syntax. You may want to debug it and update the example with the fixes. Nevertheless, you got your point across.
One way of making the closure use a copy of the class variable is to make a copy of the variable and use it instead of x in the closure.:
def myMethodThatReturnsClosure() {
def myX = x
{
println "im printing x:$myX"
myX++
}
}
This assumes the variable is a primitive, which grooy handles differently so that a copy is made. Otherwise the new variable would just be a reference to the original. In the latter case, you'd have to clone the object to get a copy.

Programming Language Evaluation Strategies

Could you please explain differences between and definition of call by value, call by reference, call by name and call by need?
Call by value
Call-by-value evaluation is the most common evaluation strategy, used in languages as different as C and Scheme. In call-by-value, the argument expression is evaluated, and the resulting value is bound to the corresponding variable in the function (frequently by copying the value into a new memory region). If the function or procedure is able to assign values to its parameters, only its local copy is assigned — that is, anything passed into a function call is unchanged in the caller's scope when the function returns.
Call by reference
In call-by-reference evaluation (also referred to as pass-by-reference), a function receives an implicit reference to a variable used as argument, rather than a copy of its value. This typically means that the function can modify (i.e. assign to) the variable used as argument—something that will be seen by its caller. Call-by-reference can therefore be used to provide an additional channel of communication between the called function and the calling function. A call-by-reference language makes it more difficult for a programmer to track the effects of a function call, and may introduce subtle bugs.
differences
call by value example
If data is passed by value, the data is copied from the variable used in for example main() to a variable used by the function. So if the data passed (that is stored in the function variable) is modified inside the function, the value is only changed in the variable used inside the function. Let’s take a look at a call by value example:
#include <stdio.h>
void call_by_value(int x) {
printf("Inside call_by_value x = %d before adding 10.\n", x);
x += 10;
printf("Inside call_by_value x = %d after adding 10.\n", x);
}
int main() {
int a=10;
printf("a = %d before function call_by_value.\n", a);
call_by_value(a);
printf("a = %d after function call_by_value.\n", a);
return 0;
}
The output of this call by value code example will look like this:
a = 10 before function call_by_value.
Inside call_by_value x = 10 before adding 10.
Inside call_by_value x = 20 after adding 10.
a = 10 after function call_by_value.
call by reference example
If data is passed by reference, a pointer to the data is copied instead of the actual variable as is done in a call by value. Because a pointer is copied, if the value at that pointers address is changed in the function, the value is also changed in main(). Let’s take a look at a code example:
#include <stdio.h>
void call_by_reference(int *y) {
printf("Inside call_by_reference y = %d before adding 10.\n", *y);
(*y) += 10;
printf("Inside call_by_reference y = %d after adding 10.\n", *y);
}
int main() {
int b=10;
printf("b = %d before function call_by_reference.\n", b);
call_by_reference(&b);
printf("b = %d after function call_by_reference.\n", b);
return 0;
}
The output of this call by reference source code example will look like this:
b = 10 before function call_by_reference.
Inside call_by_reference y = 10 before adding 10.
Inside call_by_reference y = 20 after adding 10.
b = 20 after function call_by_reference.
when to use which
One advantage of the call by reference method is that it is using pointers, so there is no doubling of the memory used by the variables (as with the copy of the call by value method). This is of course great, lowering the memory footprint is always a good thing. So why don’t we just make all the parameters call by reference?
There are two reasons why this is not a good idea and that you (the programmer) need to choose between call by value and call by reference. The reason are: side effects and privacy. Unwanted side effects are usually caused by inadvertently changes that are made to a call by reference parameter. Also in most cases you want the data to be private and that someone calling a function only be able to change if you want it. So it is better to use a call by value by default and only use call by reference if data changes are expected.
call by name
In call-by-name evaluation, the arguments to a function are not evaluated before the function is called — rather, they are substituted directly into the function body (using capture-avoiding substitution) and then left to be evaluated whenever they appear in the function.
call by need
Lazy evaluation, or call-by-need is an evaluation strategy which delays the evaluation of an expression until its value is needed (non-strict evaluation) and which also avoids repeated evaluations

Throwing NoSuchElementException for ranges

Lets say I have the following (ideone):
x = [1,2,3]
y = x.iterator();
println y.next();
println y.next();
println y.next();
println y.next();
This outputs:
1
2
3
Caught: java.util.NoSuchElementException
java.util.NoSuchElementException
at java_util_Iterator$next.call(Unknown Source)
at prog.run(prog.groovy:7)
As expected.
But lets change x = [1,2,3] to x = 1..3, so the code is the following (ideone):
x = 1..3
y = x.iterator();
println y.next();
println y.next();
println y.next();
println y.next();
Now we get the output:
1
2
3
null
And no exception is thrown. Why is this the case? It's really unexpected that [1,2,3] and 1..3 behave differently when iterating through them. It seems like such behaviour doesn't comply with iterator's contract.
Is there a way for me to fix this behaviour, and will such a fix break anything else?
Edit: Let me try to be clearer:
This is the correct usage of the Iterator class:
x = 1..3
y = x.iterator();
while(y.hasNext()) {
println y.next();
}
The NoSuchElement exception is an unchecked (AKA runtime) exception. The reason it's not checked is that it's something that should be avoidable completely without relying on the exception. This is different than, for example, IOExceptions, which are checked and far more likely to occur during normal use.
It's not explicitly stated one way or the other in the docs, but the only time I see the next() method throwing a NoSuchElementException when the Iterator is used correctly as above is if you have a modifiable collection in an unsynchronized, multi-threaded environment that has an item removed between the moment you call hasNext and access the item using next.
Because the Range class is unmodifiable, there is no chance, ever, of that situation rising.
You should not rely on unchecked Exceptions to determine the functionality or state of an item.
So, I don't really think the contract has been broken. The contract for using an iterator is to use hasNext before next, and the Range class's Iterator is not required to throw an exception just because it is being used incorrectly.
use :
While(y.hasNext()){
println y.next();
}
It's because IntRangeIterator returns null when it has gone off the end of the Range
As you can see in the source code for it here
I guess if you feel that this is incorrect behaviour, you should ask on the mailing lists, or post a bug to the Groovy JIRA, but as it's been that way for 6 years I would imagine it's going to stay that way (as it would be a breaking change)
As other people say, you should use a for or each mechanism to iterate the Iterator, or if that's not possible wrapping your calls to next() in a hasNext() check should catch all cases where you're off the end.

Is good to call function in other function parameter?

I suppose this:
public static string abc()
{
return "abc";
}
Is better to call this function in this way:
string call = abc();
Console.writeline(call);
Than this?
console.writeline(abc());
is there any reason to prefer one to the other?
Both are valid. However, out of experience I have concluded that the first option is more suitable for readability and ease of maintenance. I can't count how many times I have changed from the "compact" style to the first one as a help for a debugging session.
For example, this style makes it easy to check the correctness intermediate of an intermediate result:
string call = abc();
assert(!call.empty()); // Just an example.
Console.writeline(call);
Also, it helps to make the code more robust later, adding a conditional check before the subsequent action that checks call's value, for example if the design does not guarantee that the condition of the previous assert holds but you still need to check it.
string call = abc();
if (!call.empty())
{
Console.writeline(call);
}
Note also that with this style you will be able to easily inspect the value of call in your debugger.
Given your exact example (one parameter, value not used elsewhere, no side effects), it's just a matter of style. However, it gets more interesting if there are multiple parameters and the methods have side effects. For example:
int counter;
int Inc() { counter += 1; return counter }
void Foo(int a, int b) { Console.WriteLine(a + " " + b); }
void Bar()
{
Foo(Inc(), Inc());
}
What would you expect Foo to print here? Depending on the language there might not even be a predictable result. In this situation, assigning the values to a variable first should cause the compiler (depending on language) to evaluate the calls in a predictable order.
Actually I don't see a difference if you don't have any error checking.
This would make a difference
string call = abc();
# if call is not empty
{
Console.writeline(call);
}
The above method could avoid empty string being written.

Groovy: what's the purpose of "def" in "def x = 0"?

In the following piece of code (taken from the Groovy Semantics Manual page), why prefix the assignment with the keyword def?
def x = 0
def y = 5
while ( y-- > 0 ) {
println "" + x + " " + y
x++
}
assert x == 5
The def keyword can be removed, and this snippet would produce the same results. So what's the effect of the keyword def ?
It's syntactic sugar for basic scripts. Omitting the "def" keyword puts the variable in the bindings for the current script and groovy treats it (mostly) like a globally scoped variable:
x = 1
assert x == 1
assert this.binding.getVariable("x") == 1
Using the def keyword instead does not put the variable in the scripts bindings:
def y = 2
assert y == 2
try {
this.binding.getVariable("y")
} catch (groovy.lang.MissingPropertyException e) {
println "error caught"
}
Prints: "error caught"
Using the def keyword in larger programs is important as it helps define the scope in which the variable can be found and can help preserve encapsulation.
If you define a method in your script, it won't have access to the variables that are created with "def" in the body of the main script as they aren't in scope:
x = 1
def y = 2
public bar() {
assert x == 1
try {
assert y == 2
} catch (groovy.lang.MissingPropertyException e) {
println "error caught"
}
}
bar()
prints "error caught"
The "y" variable isn't in scope inside the function. "x" is in scope as groovy will check the bindings of the current script for the variable. As I said earlier, this is simply syntactic sugar to make quick and dirty scripts quicker to type out (often one liners).
Good practice in larger scripts is to always use the "def" keyword so you don't run into strange scoping issues or interfere with variables you don't intend to.
Ted's answer is excellent for scripts; Ben's answer is standard for classes.
As Ben says, think of it as "Object" -- but it is much cooler in that it does not constrain you to the Object methods. This has neat implications with respect to imports.
e.g. In this snippet I have to import FileChannel
// Groovy imports java.io.* and java.util.* automatically
// but not java.nio.*
import java.nio.channels.*
class Foo {
public void bar() {
FileChannel channel = new FileInputStream('Test.groovy').getChannel()
println channel.toString()
}
}
new Foo().bar()
e.g. But here I can just 'wing it' as long as everything is on the classpath
// Groovy imports java.io.* and java.util.* automatically
// but not java.nio.*
class Foo {
public void bar() {
def channel = new FileInputStream('Test.groovy').getChannel()
println channel.toString()
}
}
new Foo().bar()
According to this page, def is a replacement for a type name and can simply be thought of as an alias for Object (i.e. signifying that you don't care about the type).
As far as this single script is concerned there is no practical difference.
However, variables defined using the keyword "def" are treated as local variables, that is, local to this one script. Variables without the "def" in front of them are stored in a so called binding upon first use. You can think of the binding as a general storage area for variables and closures that need to be available "between" scripts.
So, if you have two scripts and execute them with the same GroovyShell, the second script will be able to get all variables that were set in the first script without a "def".
The reason for "def" is to tell groovy that you intend to create a variable here. It's important because you don't ever want to create a variable by accident.
It's somewhat acceptable in scripts (Groovy scripts and groovysh allow you to do so), but in production code it's one of the biggest evils you can come across which is why you must define a variable with def in all actual groovy code (anything inside a class).
Here's an example of why it's bad. This will run (Without failing the assert) if you copy the following code and paste it into groovysh:
bill = 7
bi1l = bill + 3
assert bill == 7
This kind of problem can take a lot of time to find and fix--Even if it only bit you once in your life it would still cost more time than explicitly declaring the variables thousands of times throughout your career. It also becomes clear to the eye just where it's being declared, you don't have to guess.
In unimportant scripts/console input (like the groovy console) it's somewhat acceptable because the script's scope is limited. I think the only reason groovy allows you to do this in scripts is to support DSLs the way Ruby does (A bad trade-off if you ask me, but some people love the DSLs)
Actually, I don't think it would behave the same...
variables in Groovy still require declaration, just not TYPED declaration, as the right-hand side generally contains enough information for Groovy to type the variable.
When I try to use a variable that I haven't declared with def or a type, I get an error "No such property", since it assumes that I'm using a member of the class containing the code.

Resources