A bit of a philosophical question, here. Any thoughts welcome.
So I've adapted a project to use Guice to create, say, object Alpha, which gets @Inject-ed into other objects. Everything works fine.
In theory, no code in the project (other than unit-tests) should ever use 'new' to create an Alpha. Suppose I want to
enforce that? What can I do?
- I could @Deprecate the constructor (and explain it in a comment) so that anyone who attempts to try to use 'new' on it will at least get warned.
- I could make the constructor default or protected, and put Alpha in the same package as the Guice module class.
- I could add some horrible static to Alpha, that keeps track of how (or how many) times it gets constructed, and throw an exception. (YUCK!!)
- I could examine the stack trace in the constructor, and throw an exception if Guice is not in the chain. (Ditto ditto testing class.) (Also yuck.)
- I could let go of my need to micro-manage things, accept the philosophy behind IOC, and simply accept that Guice will construct Alpha, and the rest of my team won't do really dumb things. (OK, maybe I could add a comment to the constructor, too :-) ) See for example, Uncle Bob at http://blog.cleancoder.com/uncle-bob/2015/07/01/TheLittleSingleton.html
- I could argue with the developers of Java 10 (11, 12...?) and beg them to please put something like "friend" in Java, so I could (in this case) make the Guice module a "friend" of Alpha (or is it vice-versa?).
Did I miss anything? How would you argue this in your shop?
Cheers!