Saturday, February 19, 2011





Thursday, February 10, 2011

Is Newables/Injectables a fundamental distinction?

In To “new” or not to “new”… Misko Hevery advices us to divide object classes into Injectables and Newables. Newables are objects that cannot be injected with DI frameworks (that is by one type of DI frameworks), Injectables are those that can. The point is to build Injectables only from other Injectables and Newables only from other Newables. To complete this recursive definition the simple Newables are defined as objects that have attributes of only primitive types. It is not so clear what are the atomic Injectables. I guess technically this needs be classes with parameter-less constructors. The examples given suggest things that you get from the OS or external libraries like an audio device or socket, or database connection. Of course sockets are not really parameterless - you need to pass the port number as an argument to the external libraries that create one, neither are audio devices if you have more then one attached to your computer - so this will only work if we assume that the given program works with just one port number or only with '/dev/audio'. What if you wanted to test it on another port? And what if you wanted to have and object containing an array of available sockets - you could not pass the number of the sockets in its constructor, because this would spoil its Injectableness. Parameter-less constructors are only hiding globals.

This distinction between Newables and Injectables proves to be rather constraining - it would be much cleaner if every class (and indeed also primitive types) were Injectable. Fortunately it is only an artefact of the DI framework chosen - there are DI frameworks that can inject any value, because they find them by name not by type. In these frameworks all classes are Injectables - but it might still be useful to keep the name of Newables for objects that can be build internally without calling any external libraries.