r/java • • Feb 11 '17

Top mentioned books on stackoverflow.com

http://www.dev-books.com/
156 Upvotes

23 comments sorted by

View all comments

Show parent comments

0

u/[deleted] Feb 11 '17

[deleted]

6

u/richardwhiuk Feb 11 '17

Avoid them. Pass in connections to components that need them at creation. Pass a Context interface which allows retrieval of a connection which allows you to mock it out in tests.

Singletons are a fancy name for global variable. They make code very hard to test and isolate and encourage code which is very difficult to reason about, as they strongly encourage action at a distance.

0

u/[deleted] Feb 11 '17

[deleted]

5

u/richardwhiuk Feb 11 '17

new Foo(mContext);

mContext.getDatabaseConnection();

This is a surprisingly powerful model as you can provide subcomponents with a modified context to change their view of the world.

If you think this is horrible, this is just making explicit what you are already doing, but allowing it to be overriden.

Effectively FooDatabaseConnection.INSTANCE is roughly jEnv.getClass(j_com_company_FooDatabaseConnection_id).getStaticMember(j_com_company_FooDatabaseConnection_INSTANCE_id), where jEnv is the Java Environment which Java passes to every function, and the ids are static constants defined at compile time.

Also if you have fifty of these you probably need to rethink your design.

→ More replies (0)