Strong Reference class - java

Why is there no java.lang.ref.StrongReference class in jdk1.7? (see JDK-6392701)
I am trying to implement a behavior that needs to be able to store Objects in different reference strengths. So my first thought was to use a field of type Reference<T> and asign a Referece with of desired strength. But there is no class for Strong references and extending Reference manually seems like the completely wrong direction.
The alternative would be to have two field, one that is a Reference and the other that is of the desired type and have only one set but a Reference that strongly stores the values would make the code much cleaner.

...and extending Reference manually seems like the completely wrong direction.
It's worse than that. According to the API:
Because reference objects are implemented in close cooperation with the garbage collector, this class may not be subclassed directly.
If you want to be able to store multiple different kinds of references, including strong, in the same structure, the best bet is probably to make your own reference interface and make two implementations: one wrapping a Reference<T> and one wrapping a normal object.

Related

Referring to Object of Object of Object

Assuming we have an object inside an object, inside another object, what is the best way to retrieve the value of a private variable outside the two objects?
The simplest way seems to be to do something like this:
object1.object2.object3.getvalue();
Is this acceptable? Or would it be better to call a method which calls a method, which calls a method?
The second option seems unnecessarily laborious, considering you would basically be having the same method created in 3 different classes.
use getter to get any object
ex: Object obj = object1.getObject2().getObject3();
It depends on your definition of "acceptable". It may be acceptable in your case. It is hard to tell without proper context.
However, there are something you may consider, level-by-level:
1. Use of getters
Although such kind of getters are still far from satisfactory, it is still better than using direct property access
i.e. Instead of accessing object1.object2 by direct field access, provide Object2 getObject2() in Object1, so that the code looks like:
object1.getObject2().getObject3().getValue()
2. Null handling
Usually when we chained such kind of property navigation, we will have problem that in some level, null is returned, which makes object1.getObject2().getObject3().getValue() throwing NPE.
If you are using Java 8, consider returning Optional<>. e.g. in Object1, getter of object2 should look like Optional<Object2> getObject2()
With such change, your code can be made null-safe by something like:
Value value = object1.getObject2()
.flatMap(Object2::getObject3)
.map(Object3::getValue)
.orElse(Value.emptyValue())
3. Law of Demeter
In order to make a more loosely-coupled design, you may want to provide access to that value in API of Object1, instead of exposing multiple levels of indirection. Hence:
Value value = object1.getFooValue();
(Keep using Optional<> if it fit your need)
for which internally it retrieve the value from Object3. (Of course, Object2 may also want to do something similar)
4. Getter is evil
Always remember you should try to avoid providing internal representation of your object. Your objects should provide meaningful behavior instead of simply act as a value object for you to get or set data. It is hard to give an example here but ask yourself, why do you need to get the value for? Is that action more appropriate to be provided by your object itself?
The best way is to not think of your objects as data stores. A class should be defined to have some work to do, some cluster of related responsibilities. In order to perform that work to fulfill those responsibilities some internal data may be kept, and some nested objects contained. Serving out data should not be the goal of your objects, generally speaking.
Encapsulation
The whole idea of encapsulation in object-oriented programming is to not expose that internal data and nested objects. Instead publish the various available chores by declaring methods on your higher/outer object. Encapsulation frees you to change those internals without breaking the outside calling code – avoiding fragility is the goal.
For example, an Invoice object can contain a collection of LineItem objects. In turn each LineItem object contains other objects for product, quantity, price, extended cost, taxability, tax rate, tax amount, and line cost. If you want to know the total amount of sales tax added across the items, instead of asking the Invoice for the LineItem, and then asking the LineItem for TaxAmount object, define this chore as a method on Invoice, getTotalTaxAmount. Let that method figure out (and keep to itself!) how to go through the contained objects to collect the relevant information.
If you absolutely must expose that nested data, again define a method at the highest level that returns a copy of the desired data or a collection of the desired objects (probably copies of those objects). Again, the goal is to avoid exposing the objects within objects within objects.
Then, within that highest method, as the correct Answer by Raaga stated, define a getter that calls a getter.
Getter Methods versus Direct Member Access
In a very simple structure of data you could access the objects directly. But generally better to use getter methods. Again the reason is encapsulation. Having a getter method allows you the flexibility of redefining the implementation details of the stored data.
For example, presently you could store the "Sex" variable as a String with values of "F" or "M". But later you may decide to take advantage of Java's nifty enum feature. So you replace those single-character "F" & "M" strings with enum instances Sex.FEMALE and Sex.MALE. Having a getter provides a level of insulation, so the Strings can be replaced internally with enums. The getter method continues to return a String (and internally translating the enum to an "F" or "M" String to be returned). This way you can work on restructuring your class without breaking those dependent outside objects.
object1.object2.object3.getvalue();
This chaining seems incorrect...Object chaining under such scenario is always object1.someMethod().someOtherMethod(). Or something like suggested above in an answer using getter object1.getObject2().getObject3().
I hope it helps.
What you described may be the simplest way (if object2 and object3 are accessible) but it is definitely not the way to go. As Raaga pointed out getters are a lot better to retrieve members of a class and these members should then be private or protected to prevent errors.
If you can do
object1.object2.object3.getvalue();
you can also do something like
object1.object2 = null;
which is most likely not what you want to allow. This is one of the basic concepts of object oriented programming. Classes should handle their implementation details / secrets and not directly offer them to the outside! This is what getters/setters are for.
This way you have more control over the access and what can be done and what can't. If you should only be able to retrieve object2 from object1 but not be able to change it, you can only offer a getter and no setter.
If you should also be able to change it, it is also better to use setter for more control, because you can do checking in your setter to prevent my example where I put a null pointer as your object2
And just in case you worry about efficiency that calling a method might not be as efficient as directly accessing a member, you can rely on Java to internally optimize your method call that it is not any slower than the direct access.

How to make an object globally available to other classes

In my main method, I first create an object X
Later in the same main method, I create several more objects (A, B, and C) that all need to be aware of object X. Right now, I pass a reference to object X into the constructor of classes A, B, and C.
This works fine, but I was wondering if, in the spirit of OOP, there is a better way to make object X globally available to other classes?
There is nothing in the 'spirit of OOP' that makes it better to make an object globally available, rather than to the objects that need it. In fact the spirit of Good Programming expects that you will make objects available only to those that need them. If you make an object globally available you cannot guarantee that at any time any other object will modify it. Even if it is unmodifiable you have less control over what the object is used for, and thus will have to make tighter controls on maintenence.
The right thing to do in this case is exactly what you are doing. Pass references to the object explicitly, ideally in their constructors. If the object is available when they are constructed then it makes complete sense to do it.
If you find in some other circumstances that you truly need to make a class available globally, and you cannot possibly find a way around it, then a Singleton is probably the best way. But do that absolutely only if there is no other way.

Collection of objects of all classes which implement a particular interface

I have an interface TestInterface and different classes may implement the interface. Is it possible to have a collection of all the objects which implements the interface? The collection can be created using
LinkedList<TestInterface> store
where store is the name of the collection. But how to keep track of the object creations of classes which implement the TestInterface. And moreover where to keep the collection?
Not knowing what you want this for, it's hard to tell.
But anyway, yes you can create a collection but in order to track and store references to the TestInterface objects, you must control their creation.
The easiest way would be to have a TestInterfaceFactory (see AbstractFactory pattern), this is also a good place to keep the store collection with the instance references.
Is it possible to have a collection of all the objects which implements the interface?
In theory yes.
In reality, it will only work if everything that creates an instance of the object also adds it to the list. And that probably makes it impractical ... unless you change the way the objects are created.
One approach use factories, but there is nothing to stop some code creating an instance without using your carefully implemented factory.
Another approach would be to replace the interface with an abstract base class whose constructor(s) guarantee that every new instance is added to the list. This can't be subverted using normal code. However, if you use Java Object Serialization (or similar) you'll need to put a "hook" into the base class to make sure that deserialized objects are added to the list.
Note that a collection that contains all instances of some interface or class is potentially a huge memory leak. You'll probably need to do something about this; e.g. using weak references.
If you desperately need to make this automatic, then in principle, you could:
use the Java instrumentation framework, adding a ClassFileTransformer to ensure that any class implementing your interface is redefined to have its constructors automatically add instances to your collection (look at something like the Bytecode Engineering Library, BCEL, if you were to go down this route);
possibly easier but still quite a lot of work: use the JVM Tool Interface to write an agent that can query the heap on the fly for instances of your object.
Either way, if the interface is yours, then introducing a programming convention whereby all instances of implementations of that interface are added to the collection is definitely easier, if more error-prone.

Java variable aliasing workaround

I've recently moved to Java, but I've had some problems with variable aliasing. I've searched everywhere, but I can't seem to find the proper way to copy the contents of one object to another object without just referencing to the same object. Does anyone have any suggestions?
Edit: What if it is an int that I am having aliasing problems with? Should I be avoiding situations like this in the first place? If so, how?
If your class implements the Clonable interface, then you can use the Object.clone() method to create a hard copy. The Wikipedia entry has some good details.
An alternative is to use copy constructors, which according to this page are safer.
It depends on the "content". For example, you cannot just copy a FileInputStream and then assume that both will continue loading from the same file.
Basically, there are two ways: If the class supports "Cloneable" interface, you can clone it by calling clone(). If not, it often has a copy constructor, that copies in data from another object.
Usually, you will end up with a shallow copy (i. e. all fields of the class are copied, but they point to the same object).
On the other hand, a lot of objects are designed to be immutable (like the String class), and there is no need to copy such an object as it cannot be changed anyway.
Another option is to design your class to create immutable objects:
http://docs.oracle.com/javase/tutorial/essential/concurrency/immutable.html
This avoids the need for cloning or a copy-constructor because the object cannot be changed once it is created. So multiple variables can point to the same object, but none of them can change the state of the object.
java.lang.Cloneable is what you are looking for.
You cannot have an implicit reference to a reference in Java so you cannot alias a variable.
Perhaps if you explain what you are trying to achieve, we can help do that without "aliases"
Edit: You really need to explain what you mean by aliasing an int value. An int value is anonymous at runtime so aliasing it doesn't make any sense.

Considering object encapsulation, should getters return an immutable property?

When a getter returns a property, such as returning a List of other related objects, should that list and it's objects be immutable to prevent code outside of the class, changing the state of those objects, without the main parent object knowing?
For example if a Contact object, has a getDetails getter, which returns a List of ContactDetails objects, then any code calling that getter:
can remove ContactDetail objects from that list without the Contact object knowing of it.
can change each ContactDetail object without the Contact object knowing of it.
So what should we do here? Should we just trust the calling code and return easily mutable objects, or go the hard way and make a immutable class for each mutable class?
It's a matter of whether you should be "defensive" in your code. If you're the (sole) user of your class and you trust yourself then by all means no need for immutability. However, if this code needs to work no matter what, or you don't trust your user, then make everything that is externalized immutable.
That said, most properties I create are mutable. An occasional user botches this up, but then again it's his/her fault, since it is clearly documented that mutation should not occur via mutable objects received via getters.
It depends on the context. If the list is intended to be mutable, there is no point in cluttering up the API of the main class with methods to mutate it when List has a perfectly good API of its own.
However, if the main class can't cope with mutations, then you'll need to return an immutable list - and the entries in the list may also need to be immutable themselves.
Don't forget, though, that you can return a custom List implementation that knows how to respond safely to mutation requests, whether by firing events or by performing any required actions directly. In fact, this is a classic example of a good time to use an inner class.
If you have control of the calling code then what matters most is that the choice you make is documented well in all the right places.
Joshua Bloch in his excellent "Effective Java" book says that you should ALWAYS make defensive copies when returning something like this. That may be a little extreme, especially if the ContactDetails objects are not Cloneable, but it's always the safe way. If in doubt always favour code safety over performance - unless profiling has shown that the cloneing is a real performance bottleneck.
There are actually several levels of protection you can add. You can simply return the member, which is essentially giving any other class access to the internals of your class. Very unsafe, but in fairness widely done. It will also cause you trouble later if you want to change the internals so that the ContactDetails are stored in a Set. You can return a newly-created list with references to the same objects in the internal list. This is safer - another class can't remove or add to the list, but it can modify the existing objects. Thirdly return a newly created list with copies of the ContactDetails objects. That's the safe way, but can be expensive.
I would do this a better way. Don't return a list at all - instead return an iterator over a list. That way you don't have to create a new list (List has a method to get an iterator) but the external class can't modify the list. It can still modify the items, unless you write your own iterator that clones the elements as needed. If you later switch to using another collection internally it can still return an iterator, so no external changes are needed.
In the particular case of a Collection, List, Set, or Map in Java, it is easy to return an immutable view to the class using return Collections.unmodifiableList(list);
Of course, if it is possible that the backing-data will still be modified then you need to make a full copy of the list.
Depends on the context, really. But generally, yes, one should write as defensive code as possible (returning array copies, returning readonly wrappers around collections etc.). In any case, it should be clearly documented.
I used to return a read-only version of the list, or at least, a copy. But each object contained in the list must be editable, unless they are immutable by design.
I think you'll find that it's very rare for every gettable to be immutable.
What you could do is to fire events when a property is changed within such objects. Not a perfect solution either.
Documentation is probably the most pragmatic solution ;)
Your first imperative should be to follow the Law of Demeter or ‘Tell don't ask’; tell the object instance what to do e.g.
contact.print( printer ) ; // or
contact.show( new Dialog() ) ; // or
contactList.findByName( searchName ).print( printer ) ;
Object-oriented code tells objects to do things. Procedural code gets information then acts on that information. Asking an object to reveal the details of its internals breaks encapsulation, it is procedural code, not sound OO programming and as Will has already said it is a flawed design.
If you follow the Law of Demeter approach any change in the state of an object occurs through its defined interface, therefore side-effects are known and controlled. Your problem goes away.
When I was starting out I was still heavily under the influence of HIDE YOUR DATA OO PRINCIPALS LOL. I would sit and ponder what would happen if somebody changed the state of one of the objects exposed by a property. Should I make them read only for external callers? Should I not expose them at all?
Collections brought out these anxieties to the extreme. I mean, somebody could remove all the objects in the collection while I'm not looking!
I eventually realized that if your objects' hold such tight dependencies on their externally visible properties and their types that, if somebody touches them in a bad place you go boom, your architecture is flawed.
There are valid reasons to make your external properties readonly and their types immutable. But that is the corner case, not the typical one, imho.
First of all, setters and getters are an indication of bad OO. Generally the idea of OO is you ask the object to do something for you. Setting and getting is the opposite. Sun should have figured out some other way to implement Java beans so that people wouldn't pick up this pattern and think it's "Correct".
Secondly, each object you have should be a world in itself--generally, if you are going to use setters and getters they should return fairly safe independent objects. Those objects may or may not be immutable because they are just first-class objects. The other possibility is that they return native types which are always immutable. So saying "Should setters and getters return something immutable" doesn't make too much sense.
As for making immutable objects themselves, you should virtually always make the members inside your object final unless you have a strong reason not to (Final should have been the default, "mutable" should be a keyword that overrides that default). This implies that wherever possible, objects will be immutable.
As for predefined quasi-object things you might pass around, I recommend you wrap stuff like collections and groups of values that go together into their own classes with their own methods. I virtually never pass around an unprotected collection simply because you aren't giving any guidance/help on how it's used where the use of a well-designed object should be obvious. Safety is also a factor since allowing someone access to a collection inside your class makes it virtually impossible to ensure that the class will always be valid.

Categories