Revision: 1054
Author: ffaber
Date: Thu Aug 6 10:20:19 2009
Log: first cut of visibility practices
http://code.google.com/p/google-guice/source/detail?r=1054
Added:
/wiki/KeepConstructorsHidden.wiki
=======================================
--- /dev/null
+++ /wiki/KeepConstructorsHidden.wiki Thu Aug 6 10:20:19 2009
@@ -0,0 +1,48 @@
+=Keep constructors on guice-instantiated classes as hidden as possible.=
+
+
+Consider this simple interface:
+{{{
+public interface DataReader {
+
+ Data readData(DataSource dataSource);
+}
+}}}
+
+It's a common reflex to implement this interface with a public class:
+{{{
+public class DatabaseDataReader {
+
+ private final ConnectionManager connectionManager;
+
+ @Inject
+ public DatabaseDataReader(
+ ConnectionManager connectionManager) {
+ this.connectionManager = connectionManager;
+ }
+
+ @Override
+ public Data readData(DataSource dataSource) {
+ // ... read data from the database
+ return Data.of(readInData, someMetaData);
+ }
+}
+}}}
+
+A quick inspection of this code reveals nothing faulty about this
implementation. Unfortunately, such an inspection excludes the dimension
of time and the inevitability of an unguarded code base to become more
tightly coupled within itself over time.
+
+Similar to the old axiom,
[http://www.google.com/webhp#hl=en&q=nothing+good+happens+after+midnight
Nothing good happens after midnight], we also know that Nothing good
happens after making a constructor public: A public constructor _will_
have illicit uses introduced within a code base. These uses necessarily
will:
+
+ * make refactoring more difficult.
+ * break the interface-implementation abstraction barrier.
+ * introduce tighter coupling within a codebase.
+
+
+Perhaps worst of all, any direct use of a constructor circumvents Guice's
object instantiation.
+
+As a correction, simple limit the visibility of both your implementation
classes, and their constructors. Typically package private is preferred
for both, as this facilitates:
+
+ * binding the class within a `Module` in the same package
+ * unit testing the class through means of direct instantiation
+
+As a simple, mnemonic remember that `public` and `...@inject` are like
[http://en.wikipedia.org/wiki/Dwarf_(Middle-earth) Elves and Dwarfs]: they
_can_ work together, but in an ideal world, they would coexist
independently.
--~--~---------~--~----~------------~-------~--~----~
You received this message because you are subscribed to the Google Groups
"google-guice-dev" group.
To post to this group, send email to [email protected]
To unsubscribe from this group, send email to
[email protected]
For more options, visit this group at
http://groups.google.com/group/google-guice-dev?hl=en
-~----------~----~----~----~------~----~------~--~---