views:

265

answers:

3

I'm running Pharo and I'm just in a use case that sort of screams for Dependency Injection à la Guice. Is there something similar for Smalltalk?

I understand that you can sort of do it all by foot, by just passing in your dependencies explicitly. But that feels awkward and verbose to me.

A: 

I am not really an expert but I found this article on google: http://codebetter.com/blogs/jeremy.miller/archive/2006/05/05/144172.aspx

I hope this will lead you in the right direction.
:)

AKRamkumar
I saw this myself. It points to two articles: One on DI, and one on Smalltalk. But it doesn't point to anything that discusses both at once.
nes1983
A: 

With Guice, it looks like you define your classes to take certain interfaces as constructor parameters. Then you tell Guice "this interface maps to that class implementing said interface".

That sort've thing is completely unnecessary in Smalltalk, because Smalltalk classes only care about protocols.

If we translated the example into Smalltalk, we could pass any object we liked into the RealBillingService's constructor, as long as that object responded to #logChargeResult: and #logConnectException:, i.e., as long as that object implemented the protocol required of a TransactionLog.

Here's a link to a similar answer to the above.

Frank Shearar
What guice does is, it injects things into your program depending on a configuration. Think of, say, SandstoneDB (http://onsmalltalk.com/sandstonedb-simple-activerecord-style-persistence-in-squeak). There, you write "person save" to write the person object to disk. How does the person find its own database? It looks into a global constant for the default database. That's an elegant API, but sucks for testing. Guice would give the person a clean way to find its database. I assure you, the problem that Guice solves was not introduces by interfaces.
nes1983
+4  A: 

There is a Smalltalk dialect with strong emphasis on dependency injection. It extends the language such that not only method names but also class names use a dynamic lookup. The novel lookup of class names is most similar to that of methods, except that bubbles up through a series of nested classes rather than along an inheritance chain. Thus you can change the injected classes by changing the nesting environment.

To learn more about the dialect, follow this link.

Adrian
Yea, I know of Newspeak. But Guice lets you inject more than classnames. You can also use it to elegantly inject different database connections, depending on whether you're testing or not (scope). Surely, you can model that in Newspeak elegantly. But, in and by itself, it doesn't come with a notion of "scope," which would be useful for my use case.
nes1983