I’ve defined an interface RecordVisitor, declared as follows:
public interface RecordVisitor<K, V, Result> {
public Result visit(Record<K, V> rec);
}
The idea is that implementations of visit will get called with a Record object, do their logic, and return a result. I would like to prevent implementations from stashing away the rec value and using it outside of the visit invocation.
The only way I’ve thought to do this is by adding state to Record, and throwing IllegalStateException if any method is called on the record object while it is not “active”. Then I would write dire warnings into the javadoc, and hope that implementers read it.
Is there a more robust way to prevent using the Record object from being used outside of the visit method? If possible, I’d like to build an interface that results in compile-time errors if the contract is violated.
There is no way to prevent an implementor from storing a reference to an object as part of their implementation of
visit.However, there is a bigger philosophical issue here. If you don’t trust the code that implements the
RecordVisitorinterface, then why are you using that code? If you do, then why is it a problem if that code keeps a reference to an object?If you don’t trust the programmers who are implementing your
RecordVisitorinterface, this still isn’t enough. There’s nothing to prevent the implementor from creating a new methodwhich to
Recordwill appear as an invocation from insidevisitbut won’t actually be from insidevisit.