Java Reference
In-Depth Information
manager.initDatabase();
Reservation r = new Reservation();
r.reserve();
}
The DBManager implies a global state. Without instantiating the database first, you
won't be able to make a reservation. Internally, the Reservation uses the DBManager
to access the database. Unless documented, the Reservation class hides its depen-
dency on the database manager from the programmer because the API doesn't give us
a clue. Listing 5.5 provides a better implementation.
Listing 5.5
Avoiding global state
public void reserve() {
DBManager manager = new DBManager();
manager.initDatabase();
Reservation r = new Reservation (manager);
r.reserve();
}
In this example, the Reservation object is constructed with a given database man-
ager. Strictly speaking, the Reservation object should be able to function only if it
has been configured with a database manager.
Avoid global state; when you provide access to a global object, you share not only
that object but also any object to which it refers.
As Miško Hevery 2 says in his blog:
You can live in a society where everyone (every class) declares who their friends
(collaborators) are. If I know that Joe knows Mary but neither Mary nor Joe knows Tim,
then it is safe for me to assume that if I give some information to Joe he may give it to Mary,
but under no circumstances will Tim get hold of it. Now, imagine that everyone (every
class) declares some of their friends (collaborators), but other friends (collaborators which
are singletons) are kept secret. Now you are left wondering how in the world did Tim got
hold of the information you gave to Joe.
Here is the interesting part. If you are the person who built the relationships (code)
originally, you know the true dependencies, but anyone who comes after you is baffled, since
the friends which are declared are not the sole friends of objects, and information flows in
some secret paths which are not clear to you. You live in a society full of liars.
5.2.6
Singletons pros and cons
Although we just discouraged you from using global state, the Singleton 3 is a useful
design pattern that ensures a class has only one instance. You can extend the concept
2
http://misko.hevery.com/about/
3
You can find more on the Singleton pattern in Design Patterns: Elements of Reusable Object-Oriented Software , by
Erich Gamma, Richard Helm, Ralph Johnson, and John M. Vlissides.
 
 
 
 
 
Search WWH ::




Custom Search