Difference between immutable and final - groovy

What is the difference between immutable and final?
For example, this
#Immutable
public MyClass {
String property1
MyOtherClass property2
List myLIst
}
and
public final MyClass {
final String property1
final MyOtherClass property2
final List myLIst
}

The #Immutable annotation instructs the compiler to execute an AST transformation which adds the necessary getters, constructors, equals, hashCode and other helper methods that are typically written when creating immutable classes with the defined properties.
[1]
So, #Immutable generates helper functionality, similar to "case classes" in Scala.
The final keyword instructs the compiler that the particular variable is immutable, as it means in Java.
The first class is equivalent to the second class with several helper functions.
[1] http://groovy.codehaus.org/gapi/groovy/transform/Immutable.html

The #Immutable annoatation causes the compiler to transform a class such that it cannot be changed after construction. The final modifier - when applied to a variable/field - ensures that the variable cannot be reassigned after construction. When applied to a class, final prevents the class from being extended.
When a class is declared immutable, the types of all the properties must also be immutable, or the compiler must know how to make them immutable, which it does for Date, Collection, Map, etc. So in your example above MyOtherClass must also be immutable.
To illustrate the difference between a final field and an immutable field
class FinalClass {
final List list
}
because list is final, you cannot reassign it after construction like this:
def fc = new FinalClass(list: [])
fc.list = [] // throws a ReadOnlyPropertyException
But you can mutate this field, e.g.
def fc = new FinalClass(list: [])
fc.list << new Object()
By contrast, a field of an immutable class can neither be reassigned nor mutated. For example, if FinalClass is annotated with #Immutable the following attempt to mutate a field would cause an exception to be thrown
def fc = new FinalClass(list: [])
fc.list << new Object() // throws an UnsupportedOperationException

Related

How can I determine whether a nested class is static in a Groovy AST transformation?

In an AST transformation, I am trying to detect whether a class Foo has nested classes and, if so, whether they are static or inner classes:
#MyTransform
class Foo {
static class A {}
class B {}
}
When I examine fooCn.innerClasses, both Foo$A and Foo$B are listed. ClassNode includes a method called isStaticClass, but by the Javadoc, this only tells me whether a nested class is declared within a static method (as a local class), not whether it is a "static class" by the JLS definition. Both a.staticClass and b.staticClass return false, and both a and b return Foo for outerClass.
How can I inspect the class nodes for Foo$A and Foo$B and determine that Foo$A is a static nested class?
The ClassNode representing each class has a property modifiers containing the modifier flags for the class; bit 4 (value 8) is defined as the STATIC modifier. The utility method java.lang.reflect.Modifier.isStatic(classNode.modifiers) will indicate whether the class is static nested or inner.

Calling closure on different object?

Suppose I have this class:
class MyClass {
int myInt
MyClass(myInt) {
this.myInt = myInt
}
def myMethod() {
print this.myInt
}
}
And somewhere I have:
def myClass1 = new MyClass(1)
def myMethodClosure = myClass1.&myMethod
def myClass2 = new MyClass(2)
Now if I call myMethodClosure() it will call myMethod() on myClass1 instance which will print 1. What I want is to call the same myMethodClosure but on a different instance, in this case on myClass2 so it can print 2. Is this possible?
I have tried using setDelegate(), but it does not work. I have also seen that there is field thisObject inside the closure class, but it does not have a setter, only a getter.
There were two methods added to Groovy to aid serialization of Closures, dehydrate and rehydrate. Basically, they strip (and reconstruct) a Closure's owner, thisObject and delegate. In this example, you could do:
myMethodClosure.rehydrate( myClass2, myClass2, myClass2 )()
To get the output 2, however I'd be wary about doing this as it is not what the method was intended for and there could be serious unforeseen consequences.
A better solution would probably be to write a factory method that gets a method reference for the given instance of MyClass. There may be other -- better -- solutions, but it depends on the situation you are in (that I suspect is not shown by the example in the question)
I believe closure "includes" the enclosing object to act upon. It is not possible override "this" inside a closure at runtime.

Are these values also Value Objects?

I think I understand Value Objects ( they have no conceptual identity, set of its attributes is its definition etc) and how they differ from Entities, but I'm still puzzled whether a value of a primitive type ( int, string ...) being assigned directly to property of an Entity is also considered a VO.
For example, in the following code an object ( of type Name ) assigned to Person.Name is a VO, but are values assigned to Person.FirstName, Person.LastName and Person.Age also considered VO?
public class Person
{
public string FirstName = ...
public string LastName = ...
public int Age = ...
public Name Name = ...
...
}
public class Name
{
public string FirstName = ...
public string LastName = ...
public int Age = ...
}
thank you
It doesn't matter if a value is a primitive type (such as string or int) or a complex type composed of primitive types (such as Name). What matters is that you think of it as a mere "value" without any identity -- then it is a value object.
The decision to keep it a primitive or wrap it in a class is an implementation detail. Specific types are easier to extend in the future / add functionality than primitive types.
Check this related question... Value objects are more an implementation thing that a "conceptual" one... If you think about it, singleton and flyweight pattern are about turning an object with an identity to an value object for optimization purposes... It's also related to choosing to implement something as mutable or immutable. You can always say that Person is immutable, but after a while, you are a "new" person with different attributes. It's an implementation decision, not a domain or conceptual one. (Immutable things tend to be value objects, and the mutable ones identity objects).

How a property, of type string, is passed

I have the following code (note the code below doesnt update the property)
private void queryResultsFilePath_Click(object sender, EventArgs e)
{
Library.SProc.Browse browser = new Browse();
browser.selectFile(QueryResultFilePath);
}
and
public class Browse
{
public void selectFile(string propertyName)
{
...
propertyName = browserWindow.FileName;
}
}
Now i realise that i need to change the second method so that it returns a string and manually assign it to the property in the first example.
What im unsure of is that i thought that when i assigned a ref type as an actual parameter of a method, a copy of its value on the stack (ie its memory address in the heap) was copied to the new location on the stack for the methods formal parameter, so they are both pointing to the same memory address on the heap. So when i changed the value of the formal parameter, it would actually change the value stored on the heap and thus the actual parameters value.
Obviously im missing something since im having to return a string and manually assign it to the property. If someone could point out what ive misunderstood id appreciate it.
Thanks.
I believe the missing piece here is: strings are immutable.
Although you pass it by reference, as soon as anything attempts to mutate the string, a new string is created leaving the old one intact.
I believe it is the only reference type that has enforced immutability.
From MSDN:
Strings are immutable--the contents of a string object cannot be
changed after the object is created, although the syntax makes it
appear as if you can do this. For example, when you write this code,
the compiler actually creates a new string object to hold the new
sequence of characters, and that new object is assigned to b. The
string "h" is then eligible for garbage collection.
Further reading:
http://social.msdn.microsoft.com/Forums/en/netfxbcl/thread/e755cbcd-4b09-4a61-b31f-e46e48d1b2eb
If you wish the method to "change" the caller's string then you can simulate this using the ref keyword:
public void SelectFile(ref string propertyName)
{
propertyName = browserWindow.FileName;
}
In this example, the parameter propertyName will be assigned to in the method, because of ref being used, this also changes the string that the caller is pointing to. Note here that immutability is still enforced. propertyName used to point to string A, but after assignment now points to string B - the old string A is now unreferenced and will be garbage collected (but importantly still exists and wasn't changed - immutable). If the ref keyword wasn't used, the caller would still point at A and the method would point at B. However, because the ref keyword was used the callers variable now points to string B.
This is the same effect as the following example:
static void Main(string[] args)
{
MyClass classRef = new MyClass("A");
PointToANewClass(ref classRef);
// classRef now points to a brand new instance containing "B".
}
public static void PointToANewClass(ref MyClass classRef)
{
classRef = new MyClass("B");
}
If you try the above without the ref keyword, classRef would still point to an object containing "A" even though the class was passed by reference.
Don't get confused between string semantics and ref semantics. And also don't get confused between passing something by reference and assignment. Stuff is technically never passed by reference, the pointer to the object on the heap is passed by value - hence ref on a reference type has the behaviour specified above. Also hence not using ref will not allow a new assignment to be "shared" between caller and method, the method has received its own copy of the pointer to the object on the heap, dereferencing the pointer has the usual effect (looking at the same underlying object), but assigning to the pointer will not affect the callers copy of the pointer.
I'm really grateful to Adam Houldsworth, because I've finally understood how the .NET framework uses reference parameters and what happens with the string.
In .NET there are two kind of data types:
value type: primitive types like int, float, bool, and so on
reference type: all the other objects, including string
In the case of reference type, the object is stored in the heap, and a variable only holds a reference pointing to this object. You can access the object's properties through the reference and modify them. When you pass one of this variables as parameter, a copy of the reference pointing to the same object is passed on to the method body. So, when you access and modify properties, you are modifyin gthe same object stored on the heap. I.e, this class is a reference object:
public class ClassOne
{
public string Desc { get; set; }
}
When you do this
ClassOne one = new { Desc = "I'm a class one!" };
there's an object on the heap pointed to by the reference one. If you do this:
one.Desc = "Changed value!";
the object on the heap has been modified. If you pass this reference as a parameter:
public void ChangeOne(ClassOne one)
{
one.Desc = "Changed value!"
}
The original object on the heap is also changed, because one helds a copy of the original reference that points to the same object on the heap.
But if you do this:
public void ChangeOne(ClassOne one)
{
one = new ClassOne { Desc ="Changed value!" };
}
The original object is unchanged. That's because one was a copy of the reference that it's now pointing to a different object.
If you pass it explicitly by reference:
public void ChangeOne(ref ClassOne one)
{
one = new ClassOne { Desc ="Changed value!" };
}
one inside this method is not a copy of the outer refernce, but the reference itself, so, the original reference now points to this new object.
strings are inmutable. This means that you cannot change a string. if you try to do so, a new string is created. So, if you do this:
string s = "HELL";
s = s + "O";
The second line creates a new instance of string, with the value "HELLO" and "HELL" is abandoned on the heap (left to be garbage collected).
So it's not possible to change it if you pass it as a parameter like this:
public void AppendO(string one)
{
one = one + "O";
}
string original = "HELL";
AppendO(original);
the original string is left as is. The code inside the function creates a new object, and assign it to one, which is a copy of original reference. But original keeps pointing to "HELL".
In the case of value types, when they are passed as parameters to a function, they are passed by value, i.e. the function receives a copy of the original value. So, any modification done to the object inside the function body won't affect the original value outside the function.
The problem is that, although string is a reference type, it looks as if it behaves like a value type (this applies to comparisons, passing parameters, and so on).
However, as explained above, it's possible to make the compiler pass a reference type by reference using the ref keyword. This also also works for strings.
You can check this code, and you'll see that the string is modified (this would also apply to an int, float or any other value type):
public static class StringTest
{
public static void AppednO(ref string toModify)
{
toModify = toModify + "O";
}
}
// test:
string hell = "HELL";
StringTest.AppendO(ref hell);
if (hell == "HELLO")
{
// here, hell is "HELLO"
}
Note that, for avoiding errors, when you define a parameter as ref, you also have to pass the parameter with this modifier.
Anyway, for this case (and similar cases) I'd recommend you to use the more natural functional syntax:
var hell = StringTest.AppendO(hell);
(Of course, in this case, the function will have this signature and corresponding implementation:
public static string AppendO(string value)
{
return value + "O";
}
If you're going to make many changes to a string, you should use the StringBuilder class, which works with "mutable strings".
How a property, of type string, is passed
Strings are immutable and therefore you are passing copies of them to methods. This means that the copy changes but the original parameter stays the same.

Groovy named and default arguments

Groovy supports both default, and named arguments. I just dont see them working together.
I need some classes to support construction using simple non named arguments, and using named arguments like below:
def a1 = new A(2)
def a2 = new A(a: 200, b: "non default")
class A extends SomeBase {
def props
A(a=1, b="str") {
_init(a, b)
}
A(args) {
// use the values in the args map:
_init(args.a, args.b)
props = args
}
private _init(a, b) {
}
}
Is it generally good practice to support both at the same time? Is the above code the only way to it?
The given code will cause some problems. In particular, it'll generate two constructors with a single Object parameter. The first constructor generates bytecode equivalent to:
A() // a,b both default
A(Object) // a set, b default
A(Object, Object) // pass in both
The second generates this:
A(Object) // accepts any object
You can get around this problem by adding some types. Even though groovy has dynamic typing, the type declarations in methods and constructors still matter. For example:
A(int a = 1, String b = "str") { ... }
A(Map args) { ... }
As for good practices, I'd simply use one of the groovy.transform.Canonical or groovy.transform.TupleConstructor annotations. They will provide correct property map and positional parameter constructors automatically. TupleConstructor provides the constructors only, Canonical applies some other best practices with regards to equals, hashCode, and toString.

Resources