Статьи

Инъекция зависимости — 3 вопроса!

Обычно причина, по которой я пишу блоги, заключается в том, чтобы информировать других людей об интересных вещах, которые я нашел или о которых я думаю. Сегодня я задам несколько вопросов и жду вашего ответа;-)

Одно из моих последних сообщений было о весеннем богатом клиенте. Благодаря этому проекту и picocontainer я много читал о шаблонах дизайна. Наиболее очевидный шаблон проектирования весной называется внедрением зависимостей . Этот шаблон проектирования помогает архитектору программного обеспечения беспрепятственно соединять компоненты. Это может работать следующим образом (только для JSE-разработчиков под нами):

class ClassA {
MyInterface objectA;
public void setMyInterface(MyInterface objA) {objectA = objA;}
}

где мы могли бы определить интерфейс следующим образом:

interface MyInterface{ String toString(); }

Теперь ClassA определяет зависимость от экземпляра MyInterface, и инфраструктура (для Java, например, picocontainer , spring , juice или другие ) будет внедрять экземпляр реализации MyInterface в ClassA . Это зависит от конфигурации, если objA является вновь созданным экземпляром или это «синглтон». (MyInterface также может быть классом.)

Например, если вы звоните

ClassA classA = framework.getBean(ClassA.class); //code is similar to picocontainer; not to spring!

Вы получите обратно экземпляр класса ClassA , где objectA не равно NULL ! Зависимость была определена методом (setMyInterface) — это называется установочным внедрением . Другие виды инъекций:

  • инъекция на основе аннотации :
    class ClassA { @Inject Object objectA; } 
    

  • конструктор инъекций :
    class ClassA { Object objectA;
    public ClassA(ObjectA objA) {objectA = objA;}
    }

Где picocontainer проводит кампанию за конструктор и пружину за закачку сеттера (но оба проекта предлагают как минимум упомянутые виды закачки).

Это верно, что вы можете создать свой собственный небольшой каркас или даже настроить объекты вручную для достижения того же: внедрение зависимости. Но я полагаю, вы ленивы и выберете один из фреймворков с открытым исходным кодом.

Теперь все объясняется, чтобы понять мои 3 вопроса. Надеюсь, у кого-то там будет ответ!

1. Как мне оформить библиотеку?

Позволь мне объяснить. Вы хотите продать красиво оформленную, но сложную библиотеку. Библиотека предлагает множество функций, и вы хотите разделить ее на слабо связанные компоненты. Это означает, что вы должны использовать внедрение зависимостей (DI), но вы не знаете, есть ли у клиента или нужна такая DI-структура.

So, if you use e.g. the annotation-based injection it would be nearly impossible for the customer to use your library; with setter or constructor injection it is quite difficult to set up the objects for using your library.

I don’t know what to do: Should I really use dependency injection here? Or should I use a (dynamic) service locator instead; to decouple my components within the library?

Martin Fowler says:

“It (dependency injection) tends to be hard to understand and leads to problems when you are trying to debug. […] This isn’t to say it’s a bad thing, just that I think it needs to justify itself over the more straightforward alternative (service locator).”

A common reason people give for preferring dependency injection is that it makes testing easier. The point here is that to do testing, you need to easily replace real service implementations with stubs or mocks. However there is really no difference here between dependency injection and service locator: both are very amenable to stubbing. I suspect this observation comes from projects where people don’t make the effort to ensure that their service locator can be easily substituted.

“So the primary issue is for people who are writing code that expects to be used in applications outside of the control of the writer. In these cases even a minimal assumption about a Service Locator is a problem.”

So: What would you do? Would you use a service locator or dependency injection inside the library?

And this leads me to the next important question:

2. Why is a singleton an antipattern?

I stumbled over this question while I used picocontainer. They say you have to avoid singletons, because it is difficult to test and to replace. My question is: why? Imagine the following singleton:

class LogFactory{
public static Logger getLogger(Class clazz) { … }
}

Now it is really easy to replace the implementation of the Logger interface e.g. if one defines a setImpl method:

LogFactory.setImpl(LoggerForTesting.class);

So what’s soo wrong with a singleton?

3. How can I avoid making all classes public?

I don’t know if it is the case for autowiring in spring. But in picocontainer you have to set-up the configuration for the wiring of the classes by yourself e.g. in a separate class (with Java; no xml! compiler checks references! yeah!) or in a separate file with a scripting language (or xml) and nanocontainer. That means you could specify the implementations of the interface by:

framework.setImpl(MyInterface.class, FirstImpl.class);

But wouldn’t it mean that I have to add the modifier public to the class FirstImpl? (To let picocontainer call the default constructor.) This can’t be good design to allow the user of my library to see the implementations of MyInterface.

Whats wrong with my use case and my conclusion?

From http://karussell.wordpress.com