4

Hi I have a very simple dagger questions for android.

class Fooz {
    @Inject Foo1 mFoo1;
    public Fooz() {
        ....
    }
}

class Fooz {
    private Foo1 mFoo1;

    @Inject public Fooz(Foo1 foo1) {
        mFoo1 = foo1;
    }
}

How are the two classes identical? The first one injects Foo1 field directly while the second one assignes mFoo1 in the constructor. For the second one, does Foo1 get injected from object graph as soon as Fooz is created and added to object graph? If they are different, why so? Thanks!

Mikhail Kholodkov
  • 23,642
  • 17
  • 61
  • 78
user2062024
  • 3,541
  • 7
  • 33
  • 44
  • Possible duplicate of https://stackoverflow.com/questions/36078137/dagger-2-when-to-use-constructor-injections-and-when-to-use-field-injections?rq=1 – Ricardo Costeira Nov 20 '18 at 17:03

2 Answers2

4

Constructor injection gives you more control over the object instantiation since using field injections means to restrict your class creation to reflection and rely on support to these particular injection annotations. Besides that, having the dependencies clearly on the constructor let the code easier to maintain and to test.

As far as I know, there is no difference regarding the way it is held on the dagger graph but a constructor call is always faster than injected fields.

In my opinion, we should use property only when we do not have control over the object creation, as in Activities and Fragments, per example.

haroldolivieri
  • 2,173
  • 18
  • 29
1

These classes will behave the same when Fooz will be Injected using dependency injection. However they will behave differently when constructed using Constructor's you defined.

Example 1. Calling new Fooz() will result in mFoo1 being null.

Example 2. Calling new Fooz(foo1) will result in mFoo1 being initialized to foo1.

The preferred (personal opinion) way is to use dependency injection annotation on constructor, because it will avoid null pointer exceptions, as explained when comparing example 1 and example 2. What is more such constructor gives more flexibility when testing your classes as you can provide mocks, much easier.

These is sonarqube rule with better description, explaining what I mentioned https://sonarcloud.io/coding_rules?open=squid%3AS3306&rule_key=squid%3AS3306 .

DonatasD
  • 651
  • 6
  • 14