Path: csiph.com!news.swapon.de!eternal-september.org!feeder.eternal-september.org!reader01.eternal-september.org!.POSTED!not-for-mail From: Andreas Leitgeb Newsgroups: comp.lang.java.programmer Subject: Re: How to make my library independent using DI Date: Wed, 30 Jan 2019 10:11:40 -0000 (UTC) Organization: A noiseless patient Spider Lines: 53 Message-ID: References: Reply-To: avl@logic.at Injection-Date: Wed, 30 Jan 2019 10:11:40 -0000 (UTC) Injection-Info: reader02.eternal-september.org; posting-host="e7d9ac6ef7f001fe9f820a341396d1f5"; logging-data="3036"; mail-complaints-to="abuse@eternal-september.org"; posting-account="U2FsdGVkX1+z+a/Ac+YLNab5G6zsBB/e" User-Agent: slrn/1.0.3 (Linux) Cancel-Lock: sha1:fpRVGtYl8JlBCmTwngq+p1yiqRU= Xref: csiph.com comp.lang.java.programmer:38721 mike wrote: > In my library I have the following classes: > public interface MyDataClass { > [...] > } > public class MyDataClassImpl implements MyDataClass{ > private ExternalDataService externalDataService; > public MyDataClassImpl(ExternalDataService externalDataService){ > this.externalDataService = externalDataService; > } I'd consider this design already fine w.r.t. independence of lib from app. > public String productNumber() { > //Here we have a dependency to an external library call it x > return externalDataService.productNumber(); > } You might want to wrap this with a null check for the field, such that if a user of the lib doesn't provide an implementation (but instead null), they could still get around. If the lib doesn't make sense without at least some implementation of ExternalDataService, then you can leave it as is here, and instead let the constructor throw some exception for a null argument. There might even be @NotNull annotations, but I don't know how reliable they are, or whether they are already available in the versions of Java you use. > public interface ExternalDataService { > public String productNumber(); > public String version(); > } > > Then in the application using this lib I have: > public class AHelper implements ExternalDataService{ > [...] > } > I have two questions: > > 1. How can I inject AHelper into MyDataClassImpl without creating > a "hard dependency" without using a DI container? Not sure what you mean by inject, but according to your code snippet, there is no "hard dependency" to AHelper in your lib. Unless you strictly disallow "null", there isn't even a necessity that a user even implements ExternalDataService at all. > 2. If I used a container like Guice how would that look like? I don't know Guice, so can't tell.