Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Java equivalent of Smalltalk's become:

Is there a way to swap myself (this) with some other object in Java?

In Smalltalk we could write

Object subclass:myClass [
    "in my method I swap myself with someone else"
    swapWith:anObject [
        self become:anObject.
        ^nil
    ]
]

myClass subclass:subClass [
]

obj := myClass new.
obj swapWith:subClass new.
obj inspect.

Result is An instance of subClass, obviously.

I need to do following in Java:

  • I am in a one-directional hierarchy (directed acyclic graph)
  • in one of my methods (event listener method to be exact) I decide that I am not the best suited object to be here, so:
  • I create a new object (from a subclass of my class to be exact), swap myself with him, and let myself to be garbage-collected in near future

So, in short, how can I achieve in Java self become: (someClass new:someParameters)? Are there some known design patterns I could use?

like image 536
user2622016 Avatar asked Aug 14 '13 12:08

user2622016


2 Answers

In its most general form, arbitrary object swapping is impossible to reconcile with static typing. The two objects might have different interfaces, so this could compromise type safety. If you impose constraints on how objects can be swapped, such a feature can be made type safe. Such feature never became mainstream, but have been investigated in research. Look for instead at Gilgul.

Closely related is reclassification, the ability to change the class of an object dynamically. This is possible in Smalltalk with some primitives. Again, this puts type safety at risks, never became mainstream, but has been investigated in research. Look at Wide Classes, Fickle, or Plaid.

A poor man's solution to object swapping is a proxy that you interpose between the client and the object to swap, or the use of the state and strategy design patterns.

like image 119
ewernli Avatar answered Oct 23 '22 14:10

ewernli


Here is an interesting thread on the official forum. I believe that object encapuslation in combination with strong types makes this function unable to work in Java. Plus for already slow JVM, this could lead to disaster...

like image 44
Michal Avatar answered Oct 23 '22 14:10

Michal