Saturday, 23 April 2016

What are the problems in object publication ?


What is publishing an object ?
To make object available to code outside of its current scope.

public static Set<Secret> knownSecrets;

Publishing one object may indirectly publish others.
For example, Set object can publish multiple Secret objects.


PROBLEMS
1. Allow escaping internal mutable state
private String[] states = new String[] { "AK", "AL" ... };
public String[] getStates() { return states; }

Any caller can modify its contents.
Solution : Use proper encapsulation

2. Escaping this reference
Common mistake is to start a thread from a constructor, which shares this reference with new thread (by passing to constructor or owning object uses Thread / Runnable as the inner class)

Solution : Create thread in constructor, but don't start it.
Expose a start or init method that starts the owned thread.

No comments:

Post a Comment

Note: only a member of this blog may post a comment.