How Does "Use" work in groovy? - groovy

Hi I have the following Code Snippet;
class StringCalci
{
static def plus(Integer self, Integer Operand)
{
return self.toInteger() * Operand.toInteger()
}
}
use (StringCalci)
{
println("inside the Use method!")
println( 12 + 3 )
}
println(12+3)
I was been shocked to see the use of Use in groovy. The thing is this I can add methods to the Class at run-time(my own methods).when I was looking at the above code, I was Thinking how does Groovy make things possible like this! The use of println inside the Use is multiplying the two given numbers(because I have Override the plus method) , where as the outside println adds it! My question is how does Groovy recognise the println executes in Use and println outside the Use. Is Use is a keyword/method? I need to understand behind the scenes of this process.. Please let me know :)
Thanks in Advance :)

Welcome to the wonderful world of dynamic languages where everything is possible and nothing is certain!
This feature is called Categories. As for the implementation:
use is in fact not a keyword but a method which the Groovy runtime adds to the Object class, which makes it available everywhere.
I think the functionality is implemented mainly in the class GroovyCategorySupport
Judging from the Javadoc, it's based on keeping a map of overriden methods in a ThreadLocal which is then consulted for every method call.
yeah, that's not so great for performance, but so are pretty much all the dynamic "magic" features that Groovy and similar languages offer (and there's lots of them).

Related

How to define and call a function in Jenkinsfile?

I've seen a bunch of questions related to this subject, but none of them offers anything that would be an acceptable solution (please, no loading external Groovy scripts, no calling to sh step etc.)
The operation I need to perform is a oneliner, but pipeline limitations made it impossible to write anything useful in that unter-language...
So, here's minimal example:
#NonCPS
def encodeProperties(Map properties) {
properties.collect { k, v -> "$k=$v" }.join('|')
}
node('dockerized') {
stage('Whatever') {
properties = [foo: 123, bar: "foo"]
echo encodeProperties(properties)
}
}
Depending on whether I add or remove #NonCPS annotation, or type declaration of the argument, the error changes, but it never gives any reason for what happened. It's basically random noise, that contradicts the reality of the situation (at times it would claim that some irrelevant object doesn't have a method encodeProperties, other times it would say that it cannot find a method encodeProperties with a signature that nobody was trying to call it with (like two arguments instead of one) and so on.
From reading the documentation, which is of disastrous quality, I sort of understood that maybe functions in general aren't serializable, and that is why you need to explain this explicitly to the Groovy interpreter... I'm sorry, this makes no sense, but this is roughly what documentation says.
Obviously, trying to use collect inside stage creates a load of new errors... Which are, at least understandable in that the author confesses that their version of Groovy doesn't implement most of the Groovy standard...
It's just a typo. You defined encodeProperties but called encodeProprties.

Intellij idea gdsl. Add constructor to the class. Documentation for GDSL

I have an annotation which adds some methods and default constructor to annotated class.
I have managed to create a gdsl, to enable autocompletion in idea for methods, but I'm stuck with constructor and documentation is very poor.
Does anyone have any ideas, how to do this?
Maybe I could find a solution, in existing gdsl, but I can't remember any Transformation, related to constructors. Maybe you can remind me of any of them.
def objectContext = context(ctype: "java.lang.Object")
contributor(objectContext) {
if (hasAnnotation("com.xseagullx.SomeAnnotation")) {
// Here I want to add constructor's declaration(with empty arg's)
// …
// And then my methods.
method name: 'someMethod', type: 'void', params: [:]
}
}
EDITED: OK, if it's as #jasp say, and there is no DSL construct for declaring Constructors, I'm still asking for a good documentation sources, other than JB's confluence page. Tutorials and other sources. I'm familiar with embedded dsl's for groovy, grails and gradle.
Need smth. more structured, if it's possible.
All function invocations inside of GroovyDSL are just calls to wrappers around internal IDEA's Program Structure Interface (PCI). However it doesn't cover all of PCI's abilities, including default constructors functionality I believe. One of an evidence for that is singletonTransform.gdsl, which is bundled into IDEA from 9 version and describes #Singleton AST transformation. Here is it's code:
contributor(context()) {
if (classType?.hasAnnotation("groovy.lang.Singleton")) {
property name: "instance",
type: classType?.getQualifiedName() ?: "java.lang.Object",
isStatic: true
}
}
As you can see it doesn't change a constructor and it's visibility, so IDEA will autocomplete this invalid code:
#Singleton class Foo {}
def foo = new Foo()
Futhermore GDSL that describes the semantics of GroovyDSL (which is actually the part of /plugins/groovy/resources/standardDsls/metaDsl.gdsl of IDEA sources) doesn't provide any ability for describing of constructors.
In this case I suggest you use newify transformation which allows you to describe targetClass.name method returning created instance.
I know this is a bit old, but I found myself looking for something similar.
The DSL you are looking for is
method params: [:], constructor: true although I don't understand why you'd need it; if a class doesn't declare any constructors doesn't IDEA always suggest the default one?

Metaprogramming: adding equals(Object o) and hashCode() to a library class

I have a library of domain objects which need to be used in the project, however we've found a couple of the classes haven't got an equals or hashCode method implemented.
I'm looking for the simplest (and Grooviest) way to add those methods. Obviously I could create a subclass which only adds the methods, but this would be confusing for developers used to the library and would mean we'd have to refactor existing code.
It is not possible to get the source changed (currently).
If I could edit the class I would just use the #EqualsAndHashCode annotation to carry out an AST transformation (at compile time?), but I can't find a way to instruct the compiler to carry out the transformation on a class which I can't directly annotate.
I'm currently trying to work up an example using the ExpandoMetaClass, so I'd do something like:
MySuperClass.metaClass.hashCode = { ->
// Add dynamic hashCode calculation bits here
}
MySuperClass.metaClass.equals = { ->
// Add dynamic hashCode calculation bits here
}
I don't really want to hand-code the hashCode/equals methods for each class, so I'm looking for something dyamic (like #EqualsAndHashCode) which will work with this.
Am I on the right track? Is there a groovier way?
AST Transforms are only applied at compile time, so you'll get no help from the likes of #EqualsAndHashCode. MetaClass hacks are going to be your only option. That said, there are more-elegant ways to impose MetaClass behavior.
Shameless Self Plug I did a talk about this kind of stuff last year at SpringOne 2GX: http://www.infoq.com/presentations/groovy-app-architecture
In short, you might find benefit in creating extensions (unless you're in Grails) - http://mrhaki.blogspot.com/2013/01/groovy-goodness-adding-extra-methods.html, or by explicitly adding mixins - http://groovy.codehaus.org/Runtime+mixins ... But in general, these are just cleaner ways to do the exact same thing you're already doing.

Making a Java library "Groovy"

I fell in love with Groovy and try to use it more and more. Now I have to work with Oracle Forms Jdapi library. When working with this library, you write a lot of code like this:
JdapiIterator progIterator = getWorkForm().getProgramUnits();
while(progIterator.hasNext()) {
ProgramUnit currProgUnit = (ProgramUnit) progIterator.next();
...
}
and of cource I would like to write
getWorkForm().programUnits.each {
...
}
However, I never wrote a Groovy interface to an existing Java library and need some assistance. I know about Groovy 2.0's extension methods, but in that case I am thinking about a class with the same name in a different namespace which delegates only to the functions I would like to keep.
What is the best approach for providing the each functionality, but also all other closures applicable for collections? I would appreciate if you point me in the right direction!
The only method you need to provide is the iterator() method. You then get all of the Groovy Object iteration methods (each(), find(), any(), every(), collect(), ...) for free!

Are there any reasons not to use "this" ("Self", "Me", ...)?

I read this answer and its comments and I'm curious: Are there any reasons for not using this / Self / Me ?
BTW: I'm sorry if this has been asked before, it seems that it is impossible to search for the word this on SO.
Warning: Purely subjective answer below.
I think the best "reason" for not using this/self/me is brevity. If it's already a member variable/function then why redundantly add the prefix?
Personally I avoid the use of this/self/me unless it's necessary to disambiguate a particular expression for the compiler. Many people disagree with this but I haven't ever had it be a real sticking point in any group I've worked for.
I think most of the common scenarios have been covered in the two posts already cited; mainly brevity and redundancy vs clarity - a minor addition: in C#, it is required to use "this" in order to access an "extension method" for the current type - i.e.
this.Foo();
where Foo() is declared externally as:
public static void Foo(this SomeType obj) {...}
It clarifies in some instances, like this example in c#:
public class SomeClass
{
private string stringvar = "";
public SomeClass(string stringvar)
{
this.stringvar = stringvar;
}
}
If you use StyleCop with all the rules on, it makes you put the this. in. Since I started using it I find my code is more readable, but that's personal preference.
I think this is a non-issue, because it only adds more readability to the code which is a good thing.
For some languages, like PHP, it is even mandatory to prefix with $this-> if you need to use class fields or methods.
I don't like the fact that it makes some lines unnecessarily longer than they could be, if PHP had some way to reference class members without it.
I personally find that this.whatever is less readable. You may not notice the difference in a 2-line method, but wait until you get this.variable and this.othervariable everywhere in a class.
Furthermore, I think that use of this. was found as a replacement for a part of the much hated Hungarian notation. Some people out there found out that it's still clearer for the reader to see that a variable is a class member, and this. did the trick. But why fool ourselves and not use the plain old "m_" or simply "_" for that, if we need the extra clarity? It's 5 characters vs. 2 (or even 1). Less typing, same result.
Having said that, the choice of style is still a matter of personal preference. It's hard to convince somebody used to read code in a certain way that is useful to change it.
well, eclipse does color fields, arguments and local variables in different colors, so at least working in eclipse environment there is no need to syntactically distinguish fields in order to specially mark them as "fields" for yourself and generations to come.
It was asked before indeed, in the "variable in java" context:
Do you prefix your instance variable with ‘this’ in java ?
The main recurrent reason seems to be:
"it increases the visual noise you need to sift through to find the meaning of the code."
Readability, in other word... which I do not buy, I find this. very useful.
That sounds like nonsense to me. Using 'this' can make the code nicer, and I can see no problems with it. Policies like that is stupid (at least when you don't even tell people why they are in place).
as for me i use this to call methods of an instantiated object whereas self is for a static method
In VB.NET one of the common practice I use is the following code :
Class Test
Private IntVar AS Integer
Public Function New(intVar As Integer)
Me.Intvar = intvar
End Function
End Class
Not all the time but mostly Me / this / self is quite useful. Clarifies the scope that you are talking.
In a typical setter method (taken from lagerdalek's answer):
string name;
public void SetName(string name)
{
this.name = name;
}
If you didn't use it, the compiler wouldn't know you were referring to the member variable.
The use of this. is to tell the compiler that you need to access a member variable - which is out of the immediate scope of the method. Creating a variable within a method which is the same name as a member variable is perfectly legal, just like overriding a method in a class which has extended another class is perfectly legal.
However, if you still need to use the super class's method, you use super. In my opinion using this. is no worse than using super. and allows the programmer more flexibility in their code.
As far as I'm concerned readability doesn't even come into it, it's all about accessibility of your variables.
In the end it's always a matter of personal choice. Personally, I use this coding convention:
public class Foo
{
public string Bar
{
get
{
return this.bar;
}
/*set
{
this.bar = value;
}*/
}
private readonly string bar;
public Foo(string bar)
{
this.bar = bar;
}
}
So for me "this" is actually necessary to keep the constructor readable.
Edit: the exact same example has been posted by "sinje" while I was writing the code above.
Not only do I frequently use "this". I sometimes use "that".
class Foo
{
private string bar;
public int Compare(Foo that)
{
if(this.bar == that.bar)
{
...
And so on. "That" in my code usually means another instance of the same class.
'this.' in code always suggests to me that the coder has used intellisense (or other IDE equivalents) to do their heavy lifting.
I am certainly guilty of this, however I do, for purely vanity reasons, remove them afterwards.
The only other reasons I use them are to qualify an ambiguous variable (bad practice) or build an extension method
Qualifying a variable
string name; //should use something like _name or m_name
public void SetName(string name)
{
this.name = name;
}

Resources