0

As I had been placing null checks in Android findFragmentByTag(), the code inspection suggested me to add Objects.requireNonNull() method. When I applied this check, no more warning on code inspection. So which one is better?

I have gone through this SO Question. And as per my understanding (I might be wrong), NullPointerException will be thrown anyway.

           //3. Hide analytics fragment
            //if (fragmentManager.findFragmentByTag(TAG_ANALYTICS_FRAGMENT) != null) {
                ft.hide(Objects.requireNonNull(fragmentManager.findFragmentByTag(TAG_ANALYTICS_FRAGMENT)));
            //}
            //4. Hide settings fragment
            if (fragmentManager.findFragmentByTag(TAG_SETTINGS_FRAGMENT) != null) {
                ft.hide(fragmentManager.findFragmentByTag(TAG_SETTINGS_FRAGMENT));
            }
Phantômaxx
  • 37,901
  • 21
  • 84
  • 115
Faizan Mubasher
  • 4,427
  • 11
  • 45
  • 81

1 Answers1

0

From the Objects.requireNonNull Javadoc

This method is designed primarily for doing parameter validation in methods and constructors

That said, the benefits of using it are that your code gets freed up from some of the noise that explicit if null checks cause.

Matt Berteaux
  • 763
  • 4
  • 12