How to put annotation on getter or setter automatically generated by Groovy compiler? - scala

Groovy automatically generates getters and setters, so e.g. when I type:
int someField
I get the field + getter + setter. Now I want to put an annotation on the setter (e.g. #Requires/Ensures from GContracts):
#Ensures({someField >= 0 && someField <= 100})
int someField
And then I get error: Annotation groovy.lang.GrUnit is not allowed on element FIELD - GrUnit and GContracts recognize annotations on methods only. The workaround for this is coding getter explicitly:
#Requires({...})
void setSomeField(int newValue) { ... }
Is there a better solution for this? In Scala there is an elegant solution for this: http://www.scala-lang.org/api/current/scala/annotation/target/package.html
Is there something like that in Groovy? Or alternatively: maybe some workaround for GContracts to allow such annotations?

There are 9 compile phases in the Groovy compiler. The getters and setters are generated very late in the compilation phases, and they are generated after GContracts runs.
If you want to have your code appear as if generated getters/setters are annotated then you'll have to generate the getter/setter pairs yourself and annotate them. Specifically, add two new FieldNodes to the ClassNode (as long as they don't already exist). A field node is an AnnotatedNode, so you can add whatever annotations you want. As long as you do this in a phase before GContracts runs, then GContracts should never know the different.
That said, this sounds like a GContracts feature request.

As you've noted, GContracts does not provide field annotations (current version: 1.2.4). It even does not execute AST transformations on synthetic (generated) methods which might have been added before GContracts runs.
In a nutshell: an easy workaround is to add a custom setter method.
On the other hand, if you would annotate a class with #Invariant holding a class invariant, it would pre-generate setter methods for all properties to check the class invariant before and after execution of the setter method.
That being said, it might be worth to think about including #Requires and #Ensures in that process - i created an issue: http://gcontracts.lighthouseapp.com/projects/71511-gcontracts-core/tickets/32

Related

OPAL: Manually creating an annotated method

in the OPAL framework, is it possible to manually create an annotated method?
I currently have the following code:
Method(0, "signaturePolymorphicMethod",
MethodDescriptor(ObjectType("java/lang/Object"), VoidType), Seq())
and I want to add the annotation
#java.lang.invoke.MethodHandle$PolymorphicSignature
to this method. How can I do this?
Annotations are generally stored using the JVM's general "Attributes" mechanism.
In this case the annotation is a non-public inner class of MethodHandle with the "Runtime Retention Policy". Hence, to mark a method as having a "Polymorphic Signature" it is necessary to add the RuntimeVisibibleAnnotations_Attribute to the respective method's attributes table. However, given that the visibility of the annotation is limited to the java.lang.invoke package this is (in this specific case) probably rarely useful. Nevertheless, it is possible to query methods in the respective package

EnumType.STRING ignored by ebean and Play 2

I have a field definition that is set as an enumeration with EnumType.STRING.
Typically, this works nicely, but on two occasions, it has ignored the EnumType attribute and used the ordinal value for the enumeration.
My declaration looks like this:
#Basic(optional=true) #Enumerated(EnumType.STRING)
public StationFormat stationFormat;
I've tried:
Changing the name of the field
It still creates it as an ordinal
Doing a clean compile
Still uses ordinal value
Adding a second field on the same class
Still uses ordinal value
What the heck? I had this happen before, and at some point it magically resolved itself.
-John
I found a solution to this problem, thought I believe the underlying issue is a bug.
To workaround, add the same enum to a DIFFERENT model class. Does not matter which one, and you can delete it immediately afterwards. It will be added correctly to the new class, as well as the existing class will be amended to use the name() value rather than the ordinal.

Intersystems Cache - Correct syntax for %ListOfObjects

The documentation says this is allowed:
ClassMethod GetContacts() As %ListOfObjects(ELEMENTTYPE="ContactDB.Contact")
[WebMethod]
I want to do this:
Property Permissions As %ListOfObjects(ELEMENTTYPE="MyPackage.MyClass");
I get an error:
ERROR #5480: Property parameter not declared:
MyPackage.Myclass:ELEMENTTYPE
So, do I really have to create a new class and set the ELEMENTTYPE parameter in it for each list I need?
Correct syntax for %ListOfObjects in properties is this one
Property Permissions As list of MyPackage.MyClass;
Yes, a property does sometimes work differently than a method when it comes to types. That is an issue here, in that you can set a class parameter of the return value of a method declaration in a straightforward way, but that doesn't always work for class parameters on the class of a property.
I don't think the way it does work is documented completely, but here are some of my observations:
You can put in class parameters on a property if the type of the property is a data-type (which are often treated differently than objects).
If you look at the %XML.Adaptor class it has the keyword assignment statement
PropertyClass = %XML.PropertyParameters
This appears to add its parameters to all the properties of the class that declares it as its PropertyClass. This appears to be an example of Intersystems wanting to implement something (an XML adaptor) and realizing the implementation of objects didn't provide it cleanly, so they hacked something new into the class compiler. I can't really find much documentation so it isn't clear if its considered a usable API or an implementation detail subject to breakage.
You might be able to hack something this way - I've never tried anything similar.
A possibly simpler work around might be to initialize the Permissions property in %OnNew and %OnOpen. You will probably want a zero element array at that point anyway, rather than a null.
If you look at the implementation of %ListOfObjects you can see that the class parameter which you are trying to set simply provides a default value for the ElementType property. So after you create an instance of %ListOfObjects you could just set it's ElementType property to the proper element type.
This is a bit annoying, because you have to remember to do it every time by hand, and you might forget. Or a maintainer down the road might not now to do it.
You might hope to maybe make it a little less annoying by creating a generator method that initializes all your properties that need it. This would be easy if Intersystems had some decent system of annotating properties with arbitrary values (so you could know what ElementType to use for each property). But they don't, so you would have to do something like roll your own annotations using an XData block or a class method. This probably isn't worth it unless you have more use cases for annotations than just this one, so I would just do it by hand until that happens, if it ever does.

What is the philosophy behind making instance variables public by default in Scala?

What is the philosophy behind making the instance variables public by default in Scala. Shouldn't making them private by default made developers make less mistakes and encourage composition?
First, you should know that when you write:
class Person( val name: String, val age: Int ) {
...
}
name and age aren't instance variables but accessors methods (getters), which are public by default.
If you write instead:
class Person( name: String, age: Int ) {
...
}
name and age are only instance variables, which are private as you can expect.
The philosophy of Scala is to prefer immutable instance variables, then having public accessors methods is no more a problem.
Private encourages monoliths. As soon as it's easier to put unrelated functionality into a class just because it needs to read some variables that happen to be private, classes start to grow.
It's just a bad default and one of the big reasons for classes with more than 1000 lines in Java.
Scala defaults to immutable, which removes a massive class of errors that people often use private to restrict (but not remove, as the class' own methods can still mutate the variables) in Java.
with immutables which are preferred in many places, public isn't so much of an problem
you can replace a public val with getters and setters without changing the client code, therefore you don't need the extra layer of getters and setters just in case you need it. (Actually you do get that layer but you don't notice it most of the time.)
the java anti pattern of private field + public setters and getters doesn't encapsulate much anyway
(An additional view supplementing the other answers:)
One major driver behind Java's encapsulation of fields was the uniform access policy, i.e. you didn't have to know or care whether something was implemented simply as a field, or calculated by a method on the fly. The big upside of this being that the maintainer of the class in question could switch between the two as required, without needing other classes to be modified.
In Java, this required that everything was accessed via a method, in order to provide the syntactic flexibility to calculate a value if needed.
In Scala, methods and fields can be accessed via equivalent syntax - so if you have a simple property now, there's no loss in encapsulation to expose it directly, since you can choose to expose it as a no-arg method later without your callers needing to know anything about the change.

What is exactly the point of auto-generating getters/setters for object fields in Scala?

As we know, Scala generates getters and setters automatically for any public field and make the actual field variable private. Why is it better than just making the field public ?
For one this allows swapping a public var/val with a (couple of) def(s) and still maintain binary compatibility. Secondly it allows overriding a var/val in derived classes.
First, keeping the field public allows a client to read and write the field. Since it's beneficial to have immutable objects, I'd recommend to make the field read only (which you can achieve in Scala by declaring it as "val" rather than "var").
Now back to your actual question. Scala allows you to define your own setters and getters if you need more than the trivial versions. This is useful to maintain invariants. For setters you might want to check the value the field is set to. If you keep the field itself public, you have no chance to do so.
This is also useful for fields declared as "val". Assume you have a field of type Array[X] to represent the internal state of your class. A client could now get a reference to this array and modify it--again you have no chance to ensure the invariant is maintained. But since you can define your own getter you can return a copy of the actual array.
The same argument applies when you make a field of a reference type "final public" in Java--clients can't reset the reference but still modify the object the reference points to.
On a related note: accessing a field via getters in Scala looks like accessing the field directly. The nice thing about this is that it allows to make accessing a field and calling a method without parameters on the object look like the same thing. So if you decide you don't want to store a value in a field anymore but calculate it on the fly, the client does not have to care because it looks like the same thing to him--this is known as the Uniform Access Principle
In short: the Uniform Access Principle.
You can use a val to implement an abstract method from a superclass. Imagine the following definition from some imaginary graphics package:
abstract class circle {
def bounds: Rectangle
def centre: Point
def radius: Double
}
There are two possible subclasses, one where the circle is defined in terms of a bounding box, and one where it's defined in terms of the centre and radius. Thanks to the UAP, details of the implementation can be completely abstracted away, and easily changed.
There's also a third possibility: lazy vals. These would be very useful to avoid recalculating the bounds of our circle again and again, but it's hard to imagine how lazy vals could be implemented without the uniform access principle.