1

I found this code in old legacy system and I don't want to touch it, if there is nothing wrong with it.

But I feel like this code has some flaw and I can't locate it. Is this just not common pattern or there is some hidden pitfalls or memory leaks?

private static final Foo action =  new Foo() {

    @Override
    public void onAction(MyDialogFragment fragment) {
        if (fragment.getContext() != null) {
            fragment.getActivity().finish();
        }
    }
};

This code is used in a fragment

UPDATE: I suspect that an object of anonymous inner class has a reference to a parent fragment and since an object of this class saved in static field, it will never be collected, so parent fragment will never be collected too. Are my reasonings wrong?

Maksim Turaev
  • 4,115
  • 1
  • 29
  • 42

3 Answers3

3

There is nothing wrong with the approach, since the logic deals only with the values passed as parameters. Using a static simply avoids creating multiple instances of the Foo class.

Steve11235
  • 2,849
  • 1
  • 17
  • 18
  • Thanks, I was thinking that an object of anonymous inner class has a reference to a parent fragment and since an object of this class saved in static field, it will never be collected, so parent fragment will never be collected too. Are my reasonings wrong? – Maksim Turaev Sep 21 '18 at 06:16
1

Yes there is. It's better to get the fragment like this:

MyDialogFragment fragment = MyDialogFragment.instance();
fragment.setNavigator(this);
getSupportFragmentManager().beginTransaction().replace(R.id.activity_myDialog_layout, fragment).commit();

There is a better way. You can create 3 classes and an interface which will be implemented by the 3 classes. Activity, Fragment and Presenter. The interface will be Contracts. This is more advanced.

siqqQ
  • 43
  • 1
  • 10
  • Sure I can, but I found this in legacy system and I don't want to touch it if there is nothing wrong here. If you could explain what is the problem with this approach, please do. – Maksim Turaev Sep 20 '18 at 16:08
  • If it is in legacy system it's normal. – siqqQ Sep 22 '18 at 08:16
0

Best explanation is here: https://stackoverflow.com/a/27739694/5868421

Anonymous class in static context don't hold a reference to outer object.

Maksim Turaev
  • 4,115
  • 1
  • 29
  • 42