Introspection: how do we get the name of a class within a class? - metaprogramming

Say we have
class Foo {}
Is there a way to obtain "Foo" from within the class?

Yes.
class Foo {
say ::?CLASS.^name; # OUTPUT: Foo
}

Kaiepi's solution has its place, which I'll get to below, but also consider:
class Foo {
say Foo.perl; # Foo
say OUR.WHO; # Foo
::?PACKAGE
}
Foo.perl
This provides a simple answer to your literal question (though it ignores what you're really after, as explained in your comment below and as suggested by the metaprogramming tag and your use of the word "introspection").
OUR.WHO
I think this is typically more appropriate than ::?CLASS.^name for several reasons:
Looks less line-noisy.
Works for all forms of package, i.e. ones declared with the built in declarators package, module, grammar, or role as well as class, and also custom declarators like actor, monitor, etc.
Will lead readers to mostly directly pertinent issues if they investigate OUR and/or .WHO in contrast to mostly distracting arcana if they investigate the ::?... construct.
::?CLASS vs ::?PACKAGE
OUR.WHO only works in a value grammatical slot, not a type grammatical slot. For the latter you need a suitable ::?... form, eg:
class Foo { has ::?CLASS $bar }
And these ::?... forms also work as values:
class Foo { has $bar = ::?CLASS }
So, despite their relative ugliness, they're more general in this particular sense. That said, if generality is at a premium then ::?PACKAGE goes one better because it works for all forms of package.

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.

export class vs functions

In case of utility module, I can have either class with static methods or just export methods. I think the first solution is better, though I saw a lot of implementations with second option. Are there any "nuances" here which I am not considering?
I would argue that a class with static methods is better for the following reasons:
If your class name is Utils, all imports will by default import it as Utils too. With exported functions however, they could be imported as Utils yet that would only be a convention , one that likely won't be the case in all the different places.
A class named Utils in a file named utils.js with all the utility methods neatly grouped together is aesthetically more pleasant than flat functions defined all over the place.
A class could have properties that are used among its methods, for this you'd need #babel/plugin-proposal-class-properties though. Again, much nicer than variables defined all over the place.
Exporting methods is safer because you don't give access to class properties. Note also that in javascrpt the concept of class does not have a lot of sense, it's been introduced to make feel more confortable developers with oo languages background. Try to work with Object prototyping instead.
A couple options I can think of, if the methods are intended to be a utility method on another class, you could use handbaked mixins: http://coffeescriptcookbook.com/chapters/classes_and_objects/mixins or rely on something similar in underscore/lowdash
If you want the encapsulation of methods and still have the ability to extend, you can do this:
class Foo
foo = -> alert 'foo'
#static: -> foo()
Foo.static() #=> 'foo'
Foo.foo #=> undefined
new Foo().foo #=> undefined
class Bar extends Foo
Bar.static() # => 'foo'
jsfiddle: http://jsfiddle.net/4ne7ccxk/

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?

Base class containing a generic instance created in derived class?

I'm trying to figure out if this is possible.
I have a class, BaseGameEntity, from this I currently derive NormalDrop and OtherDrop each of which has an instance of a StateMachine< T > where T is NormalDrop and OtherDrop respectively.
From here relevant states can be called that apply to those kinds of drop.
What I want to do is put another layer in, the Drop class, which derives from BaseGameEntity which the other forms of drop then derive from.
Within Drop I want a StateMachine< T > where the "T" becomes NormalDrop or OtherDrop depending on what is using it as its base class.
Is this actually possible?
Yes, you can use the curiously recurring template pattern:
public class Drop<T> where T : Drop<T> { ... }
public class NormalDrop : Drop<NormalDrop> { ... }
public class OtherDrop : Drop<OtherDrop> { ... }
Then within the Drop base class T is always NormalDrop or OtherDrop.
This pattern generally isn't considered developer friendly as upon first glance it is confusing and there are probably better ways to structure code (though possibly not always). Eric Lippert wrote a very good blog post about this pattern and some of its shortcomings here.

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